beads/internal/github/links_test.go
Sam bcf4da3c65
feat(github): sync epic/child and blocks relationships to GitHub (#5971)
* feat(github): sync epic/child and blocks relationships to GitHub

bd github sync only ever pushed issue content (title/body/labels/state);
Epic-child links and beads "blocks" dependencies never reached GitHub's
relationships panel. Adds a GitHub relationship-sync pass, mirroring the
existing GitLab dependency-link push, using GitHub's sub-issues and issue
dependencies REST APIs:

- internal/github/client.go: AddSubIssue/ListSubIssues and
  AddBlockedBy/ListBlockedBy against GitHub's sub_issues and
  dependencies/blocked_by endpoints.
- internal/github/links.go: DependencyLink + LinkResolver, converting beads
  epic/child parent-child dependencies into GitHub sub-issues and beads
  "blocks" dependencies into GitHub blocked_by relationships. Idempotent
  (lists current relationships before creating) and additive (stale remote
  relationships are left untouched).
- cmd/bd/github.go, cmd/bd/sync_push_pull.go: wires the push pass into both
  `bd github sync` and `bd github push`.

Verified against a live GitHub repo (create, list, and idempotent re-push
all confirmed via the real API), in addition to httptest-mocked unit tests.

Fixes gastownhall/beads#5970

* fix(github): update last_sync after relationship push to prevent sync churn

When AddSubIssue or AddBlockedBy is called, GitHub updates the issue's
updated_at timestamp as a side effect. Without updating last_sync after
the relationship push completes, the next sync would see those issues as
'changed' and pull/push them again, causing unnecessary churn.

This fix updates last_sync to the current time after a successful
relationship push (only if links were created), accounting for any
timestamp changes GitHub made during relationship creation.

Fixes continuous sync churn observed when running bd github sync
multiple times with no local changes.

* fix(github): use relationship reader for link sync

* fix(bazel): enumerate links.go and its tests in internal/github BUILD.bazel

The base advance added internal/github/BUILD.bazel with explicitly
enumerated srcs (gazelle-generated). This PR adds links.go,
links_test.go and review_fixes_test.go, which the base-generated
enumeration cannot know about, so //internal/github:github failed to
build:

  internal/github/tracker.go:41:35: undefined: LinkResolver
  internal/github/tracker.go:244:30: undefined: RefScope

Regenerated with `bazel run //:gazelle` (not hand-edited). Purely
additive; no deps change is needed because links.go only imports
//internal/types, already declared.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(github): scope the relationship pass to --parent and report skipped links

Maintainer review fixup for PR #5971, adopt-pr review iterations 1 and 3.

filterGitHubLinkScopedIssues reimplemented four of the SyncOptions
selectors and dropped ParentID, so `bd github sync --push --parent X`
narrowed the content push to the subtree and then created GitHub
sub-issue and blocked-by links for every GitHub-linked issue in the
workspace -- outward API writes on issues the user had excluded. It now
resolves the subtree and requires membership in it. The traversal moves
from gitlab.go to sync_flags.go as buildSyncDescendantSet, beside the
--parent flag that populates the field, and the GitLab and GitHub link
passes share the one copy. The doc comments that claimed parity with the
engine's push loop now enumerate the selectors this path actually
applies, and name the three it does not (State, ExcludeIDPrefix,
ExcludeIDPatterns -- no GitHub command sets them today).

PushLinkResult.UnsupportedSkipped had no reader anywhere in the repo, so
a host without the sub-issue/dependency APIs reported nothing at all.
pushGitHubDependencyLinks now emits one curated line for it, and a 404
on the source issue is classified apart from a 404 on the relationship
endpoint: collapsing the two reported a deleted, renumbered or
permission-hidden issue as an unsupported host. The classifying probe is
memoized per issue number, so a source carrying both link types costs
one extra read.

`bd github push --dry-run` printed "Synced N relationship links" for
links it had only planned, because PushLinks counts planned links in
Created. The `bd github sync` twin already gated that line on its
dry-run flag; the push side now does too.

Tests: a table test over filterGitHubLinkScopedIssues with a row per
selector -- its three ParentID rows fail without the scope fix -- plus a
direct pin that a blocks-edge dependent is not a descendant, and
httptest cases driving 404 through the list call, the create call and
the source-issue probe.

Not fixed here: the PR body still describes a `lastSync` advance that
commit ee6d65692 removed from this PR. That is a PR-surface edit, not a
code change, and is left to the finalize step.

Also not fixed here, and named in buildSyncDescendantSet's doc comment
so the shared helper does not read as covering every tracker: the ADO
link pass has the same scope hole this commit closes for GitHub.
pushADOLinks takes no sync options, so `bd ado sync --push --parent X`
still writes ADO relations for the whole workspace. That predates this
PR, and ADO is outside its diff.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Julian Knutsen <julian@gastownhall.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
2026-10-01 01:22:00 -07:00

298 lines
11 KiB
Go

package github
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
func TestSubIssueLinkFromParentChild(t *testing.T) {
child := githubIssue("bd-child", "https://github.com/o/r/issues/10", types.TypeTask)
parent := githubDep("bd-epic", "https://github.com/o/r/issues/5", types.DepParentChild)
link, ok := SubIssueLinkFromParentChild(child, parent)
if !ok {
t.Fatal("SubIssueLinkFromParentChild returned false")
}
if link.FromNumber != 5 || link.ToNumber != 10 || link.LinkType != githubLinkSubIssue {
t.Fatalf("link = %+v, want parent #5 sub_issue #10", link)
}
// Same issue number should not produce a self-referential link.
same := githubDep("bd-epic", "https://github.com/o/r/issues/10", types.DepParentChild)
if _, ok := SubIssueLinkFromParentChild(child, same); ok {
t.Fatal("self-referential parent link should not be produced")
}
}
func TestBlockedByLinkFromBeadsDependency(t *testing.T) {
issue := githubIssue("bd-a", "https://github.com/o/r/issues/10", types.TypeTask)
blocker := githubDep("bd-b", "https://github.com/o/r/issues/20", types.DepBlocks)
link, ok := BlockedByLinkFromBeadsDependency(issue, blocker)
if !ok {
t.Fatal("BlockedByLinkFromBeadsDependency returned false")
}
if link.FromNumber != 10 || link.ToNumber != 20 || link.LinkType != githubLinkBlockedBy {
t.Fatalf("link = %+v, want #10 blocked_by #20", link)
}
related := githubDep("bd-c", "https://github.com/o/r/issues/30", types.DepRelatesTo)
if _, ok := BlockedByLinkFromBeadsDependency(issue, related); ok {
t.Fatal("non-blocks dependency type should not produce a blocked_by link")
}
}
func TestDeduplicateLinks(t *testing.T) {
links := []DependencyLink{
{FromNumber: 10, ToNumber: 20, LinkType: githubLinkBlockedBy},
{FromNumber: 10, ToNumber: 20, LinkType: githubLinkBlockedBy},
{FromNumber: 5, ToNumber: 10, LinkType: githubLinkSubIssue},
}
got := DeduplicateLinks(links)
if len(got) != 2 {
t.Fatalf("deduped links len = %d, want 2", len(got))
}
}
func TestPushLinksAddsMissing(t *testing.T) {
var posted bool
var capturedBody map[string]interface{}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/dependencies/blocked_by"):
_ = json.NewEncoder(w).Encode([]Issue{})
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/issues/20"):
_ = json.NewEncoder(w).Encode(Issue{ID: 2000, Number: 20})
case r.Method == http.MethodPost && strings.Contains(r.URL.Path, "/issues/10/dependencies/blocked_by"):
posted = true
_ = json.NewDecoder(r.Body).Decode(&capturedBody)
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(Issue{ID: 2000, Number: 20})
default:
t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
resolver := NewLinkResolver(NewClient("token", "o", "r").WithBaseURL(server.URL))
res := resolver.PushLinks(context.Background(), []DependencyLink{
{FromNumber: 10, ToNumber: 20, LinkType: githubLinkBlockedBy},
}, PushLinkOptions{})
if len(res.Errors) != 0 {
t.Fatalf("PushLinks errors = %v", res.Errors)
}
if res.Created != 1 || !posted {
t.Fatalf("Created = %d, posted = %v, want one created POST", res.Created, posted)
}
if int(capturedBody["issue_id"].(float64)) != 2000 {
t.Fatalf("issue_id = %v, want 2000", capturedBody["issue_id"])
}
}
func TestPushLinksIdempotentExistingLink(t *testing.T) {
var posts int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/sub_issues"):
_ = json.NewEncoder(w).Encode([]Issue{{ID: 2000, Number: 20}})
case r.Method == http.MethodPost:
posts++
t.Fatalf("unexpected POST for existing link")
default:
t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
resolver := NewLinkResolver(NewClient("token", "o", "r").WithBaseURL(server.URL))
res := resolver.PushLinks(context.Background(), []DependencyLink{
{FromNumber: 5, ToNumber: 20, LinkType: githubLinkSubIssue},
}, PushLinkOptions{})
if len(res.Errors) != 0 {
t.Fatalf("PushLinks errors = %v", res.Errors)
}
if res.Created != 0 || posts != 0 {
t.Fatalf("Created = %d, posts = %d, want no created links", res.Created, posts)
}
}
func TestPushLinksDryRunDoesNotPost(t *testing.T) {
var posts int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/sub_issues"):
_ = json.NewEncoder(w).Encode([]Issue{})
case r.Method == http.MethodPost:
posts++
t.Fatalf("unexpected POST during dry-run")
default:
t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
}
}))
defer server.Close()
var planned []DependencyLink
resolver := NewLinkResolver(NewClient("token", "o", "r").WithBaseURL(server.URL))
res := resolver.PushLinks(context.Background(), []DependencyLink{
{FromNumber: 5, ToNumber: 20, LinkType: githubLinkSubIssue},
}, PushLinkOptions{
DryRun: true,
OnPlan: func(link DependencyLink) {
planned = append(planned, link)
},
})
if len(res.Errors) != 0 {
t.Fatalf("PushLinks errors = %v", res.Errors)
}
if res.Created != 1 || posts != 0 || len(planned) != 1 {
t.Fatalf("Created = %d, posts = %d, planned = %d; want one dry-run plan and no POST", res.Created, posts, len(planned))
}
}
func githubIssue(id, ref string, issueType types.IssueType) *types.Issue {
return &types.Issue{
ID: id,
ExternalRef: &ref,
IssueType: issueType,
Status: types.StatusOpen,
}
}
func githubDep(id, ref string, depType types.DependencyType) *types.IssueWithDependencyMetadata {
return &types.IssueWithDependencyMetadata{
Issue: *githubIssue(id, ref, types.TypeTask),
DependencyType: depType,
}
}
// The 404 degradation path: a relationship endpoint that is absent on this
// host and a source issue that is gone both surface as 404 on the list call,
// but they are different operator problems and must not be counted together.
func TestPushLinksUnavailableEndpointCountsUnsupported(t *testing.T) {
var probes int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/dependencies/blocked_by"):
w.WriteHeader(http.StatusNotFound)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/issues/10"):
// The source issue is readable, so the 404 above is the endpoint.
probes++
_ = json.NewEncoder(w).Encode(Issue{ID: 1000, Number: 10})
default:
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusInternalServerError)
}
}))
defer server.Close()
resolver := NewLinkResolver(NewClient("token", "o", "r").WithBaseURL(server.URL))
res := resolver.PushLinks(context.Background(), []DependencyLink{
{FromNumber: 10, ToNumber: 20, LinkType: githubLinkBlockedBy},
}, PushLinkOptions{})
if len(res.Errors) != 0 {
t.Fatalf("PushLinks errors = %v, want none (degradation is counted, not raised)", res.Errors)
}
if res.UnsupportedSkipped != 1 {
t.Fatalf("UnsupportedSkipped = %d, want 1", res.UnsupportedSkipped)
}
if res.SourceMissing != 0 {
t.Fatalf("SourceMissing = %d, want 0 - the source issue was readable", res.SourceMissing)
}
if res.Created != 0 {
t.Fatalf("Created = %d, want 0", res.Created)
}
if probes != 1 {
t.Fatalf("source issue probed %d times, want 1", probes)
}
}
func TestPushLinksMissingSourceIssueIsNotUnsupported(t *testing.T) {
var probes int
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/dependencies/blocked_by"):
w.WriteHeader(http.StatusNotFound)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/sub_issues"):
w.WriteHeader(http.StatusNotFound)
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/issues/10"):
// The source issue itself is gone: deleted, renumbered, or hidden.
probes++
w.WriteHeader(http.StatusNotFound)
default:
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusInternalServerError)
}
}))
defer server.Close()
resolver := NewLinkResolver(NewClient("token", "o", "r").WithBaseURL(server.URL))
res := resolver.PushLinks(context.Background(), []DependencyLink{
{FromNumber: 10, ToNumber: 20, LinkType: githubLinkBlockedBy},
{FromNumber: 10, ToNumber: 30, LinkType: githubLinkSubIssue},
}, PushLinkOptions{})
if len(res.Errors) != 0 {
t.Fatalf("PushLinks errors = %v, want none", res.Errors)
}
if res.SourceMissing != 2 {
t.Fatalf("SourceMissing = %d, want 2", res.SourceMissing)
}
if res.UnsupportedSkipped != 0 {
t.Fatalf("UnsupportedSkipped = %d, want 0 - the endpoint was never shown to be absent", res.UnsupportedSkipped)
}
// Both link types hang off issue #10, and the classification is a property
// of the issue, so one probe answers for both.
if probes != 1 {
t.Fatalf("source issue probed %d times, want 1", probes)
}
}
func TestPushLinksCreateNotFoundCountsUnsupported(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/dependencies/blocked_by"):
_ = json.NewEncoder(w).Encode([]Issue{})
case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/issues/20"):
_ = json.NewEncoder(w).Encode(Issue{ID: 2000, Number: 20})
case r.Method == http.MethodPost && strings.HasSuffix(r.URL.Path, "/dependencies/blocked_by"):
// Listing worked and the target resolved, so a 404 here can only
// be the create endpoint.
w.WriteHeader(http.StatusNotFound)
default:
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
w.WriteHeader(http.StatusInternalServerError)
}
}))
defer server.Close()
resolver := NewLinkResolver(NewClient("token", "o", "r").WithBaseURL(server.URL))
res := resolver.PushLinks(context.Background(), []DependencyLink{
{FromNumber: 10, ToNumber: 20, LinkType: githubLinkBlockedBy},
}, PushLinkOptions{})
if len(res.Errors) != 0 {
t.Fatalf("PushLinks errors = %v, want none", res.Errors)
}
if res.UnsupportedSkipped != 1 {
t.Fatalf("UnsupportedSkipped = %d, want 1", res.UnsupportedSkipped)
}
if res.SourceMissing != 0 {
t.Fatalf("SourceMissing = %d, want 0", res.SourceMissing)
}
if res.Created != 0 {
t.Fatalf("Created = %d, want 0", res.Created)
}
}