diff --git a/cmd/bd/linear.go b/cmd/bd/linear.go index 3bebd195e..bc33df04f 100644 --- a/cmd/bd/linear.go +++ b/cmd/bd/linear.go @@ -379,6 +379,34 @@ func runLinearSync(cmd *cobra.Command, args []string) error { return HandleError("%v", err) } + // Post-sync: reconcile parent-child relationships into Linear's parent + // field. The per-issue create/update path can't always set parentId + // (children are sometimes pushed before parents have an external_ref), + // and previously-pushed orphan trees need a backfill. This pass is + // idempotent — no API mutation when remote parent already matches. + // + // In dry-run mode the pass still runs (read-only fetches) so the user + // gets a preview of which parents would be set; the IssueUpdate + // mutation is skipped per-link. + // + // Skipped on scoped syncs (--parent / --type / --exclude-type / --since + // / --issue-id) because the reconciler walks ALL local beads with + // external_refs, not just the in-scope ones — a scoped sync that + // silently mutated other parts of the tree would surprise the user. + // A full sync still picks up the repair on the next run. + // + // `effectivePush` mirrors engine.Sync's bidirectional default: when + // neither --pull nor --push is passed, the engine internally runs both + // directions, so the reconcile pass must also fire (otherwise + // `bd linear sync --dry-run` with no direction flag silently skips the + // preview). We can't read opts.Push after engine.Sync because Sync + // receives opts by value. + effectivePush := push || (!push && !pull) + if effectivePush && result.Success && !syncIsScoped(&opts) { + reconcileLinearParents(ctx, lt, dryRun, jsonOutput, &result.Warnings) + } + + // Record successful pull timestamp if (pull || !push) && !dryRun { if beadsDir := resolveBeadsDirForStaleness(); beadsDir != "" { _ = linear.WriteLastPullTimestamp(beadsDir) @@ -1173,3 +1201,167 @@ func getLinearHashLength(ctx context.Context) int { } return value } + +// syncIsScoped returns true when the user explicitly constrained THIS +// invocation to a specific subset of beads (via --parent, --issues, or +// --type). The parent reconcile pass is skipped on scoped syncs because +// it walks the full local tree, which could mutate Linear-side state +// outside the scope the user asked for. +// +// Notably ExcludeTypes is NOT a scoping signal: it merges with persistent +// config (linear.exclude_types), and rigs that set it default-on (e.g. +// "molecule,event") would otherwise have the reconcile pass permanently +// disabled — bd-9w3 root cause. Reconcile only ever touches the parent +// field on the child issue, so excluding types from push doesn't really +// conflict with wiring up parent-child for the remaining types. +// +// TypeFilter IS kept as a scoping signal because --type is set only via +// the CLI flag for this invocation; the user's intent to push a specific +// subset is explicit. +func syncIsScoped(opts *tracker.SyncOptions) bool { + if opts == nil { + return false + } + if opts.ParentID != "" || len(opts.IssueIDs) > 0 { + return true + } + if len(opts.TypeFilter) > 0 { + return true + } + return false +} + +// reconcileLinearParents runs as a post-sync pass to wire parent-child bead +// dependencies into Linear's parent issue field. Idempotent — no API call +// when the remote parent already matches. +// +// Two scenarios this fixes: +// +// 1. Fresh tree push: when a child is pushed before its parent in the same +// sync, the create call has no parentId to send. After all issues have +// external_refs, this pass closes the loop. +// 2. Orphan repair: existing Linear issues created in earlier bd versions +// (or by interrupted syncs) without a parent get wired up retroactively. +// +// In dry-run mode the read-only fetches still run and the per-link mutation +// plan is printed as [dry-run] lines, but no IssueUpdate is issued. Lets +// users preview the orphan-repair scope before committing to a wet sync. +// +// Human-readable output is suppressed when jsonOutput is true so the +// caller's JSON serialization (in runLinearSync's output section) isn't +// polluted with stray fmt.Printf lines. Warnings and errors still go +// through the warnings slice, which IS surfaced in JSON output via +// SyncResult.Warnings. +// +// Warnings (per-link failures, missing refs) are appended to the engine's +// warning slice so the user sees them in the standard sync output. +func reconcileLinearParents(ctx context.Context, lt *linear.Tracker, dryRun, jsonOutput bool, warnings *[]string) { + if lt == nil || store == nil { + return + } + links, err := buildLinearParentLinks(ctx, lt) + if err != nil { + *warnings = append(*warnings, fmt.Sprintf("parent reconcile: building link set failed: %v", err)) + return + } + if len(links) == 0 { + return + } + stats, err := lt.ReconcileParents(ctx, links, dryRun) + // Print mutation summary first; an abort (e.g. rate-limit circuit + // breaker) may have completed some updates before bailing, and the + // user should see that work wasn't lost. Suppress when --json is + // requested so the JSON envelope stays clean. + if stats != nil && !jsonOutput { + if dryRun { + if stats.WouldUpdate > 0 { + fmt.Printf("[dry-run] Would reconcile %d Linear parent link%s\n", + stats.WouldUpdate, plural(stats.WouldUpdate)) + for _, link := range stats.Mutations { + fmt.Printf("[dry-run] Would set parent of %s → %s\n", + link.ChildIdentifier, link.ParentIdentifier) + } + } + } else if stats.Updated > 0 { + fmt.Printf("✓ Reconciled %d Linear parent link%s\n", + stats.Updated, plural(stats.Updated)) + } + } + if err != nil { + *warnings = append(*warnings, fmt.Sprintf("parent reconcile: %v", err)) + return + } + for _, e := range stats.Errors { + *warnings = append(*warnings, fmt.Sprintf("parent reconcile: %v", e)) + } +} + +// buildLinearParentLinks enumerates local beads with a Linear external_ref +// and a parent-child dependency to a parent that also has a Linear +// external_ref. The result is the set of (child, parent) pairs whose +// Linear parent field should be set. +// +// Beads whose parent isn't yet synced to Linear are silently skipped — +// they'll get picked up on a subsequent sync once the parent has an +// external_ref. +func buildLinearParentLinks(ctx context.Context, lt *linear.Tracker) ([]linear.ParentLink, error) { + issues, err := store.SearchIssues(ctx, "", types.IssueFilter{}) + if err != nil { + return nil, err + } + // First pass: build bead_id → linear-identifier index, restricted to + // beads whose ref looks like a Linear ref. + idToIdent := make(map[string]string, len(issues)) + for _, issue := range issues { + if issue.ExternalRef == nil { + continue + } + ref := strings.TrimSpace(*issue.ExternalRef) + if !lt.IsExternalRef(ref) { + continue + } + ident := lt.ExtractIdentifier(ref) + if ident == "" { + continue + } + idToIdent[issue.ID] = ident + } + if len(idToIdent) == 0 { + return nil, nil + } + // Second pass: walk each child-bead's dependencies, find the + // parent-child edge, and emit a link if both ends are Linear-synced. + links := make([]linear.ParentLink, 0) + for _, issue := range issues { + childIdent, ok := idToIdent[issue.ID] + if !ok { + continue + } + deps, err := store.GetDependenciesWithMetadata(ctx, issue.ID) + if err != nil { + return nil, fmt.Errorf("loading deps for %s: %w", issue.ID, err) + } + for _, d := range deps { + if d == nil || d.DependencyType != types.DepParentChild { + continue + } + // child depends-on parent — the dep target's embedded Issue is the parent. + parentIdent, ok := idToIdent[d.Issue.ID] + if !ok { + continue + } + links = append(links, linear.ParentLink{ + ChildIdentifier: childIdent, + ParentIdentifier: parentIdent, + }) + } + } + return links, nil +} + +func plural(n int) string { + if n == 1 { + return "" + } + return "s" +} diff --git a/cmd/bd/sync_is_scoped_test.go b/cmd/bd/sync_is_scoped_test.go new file mode 100644 index 000000000..1252d61ac --- /dev/null +++ b/cmd/bd/sync_is_scoped_test.go @@ -0,0 +1,64 @@ +//go:build cgo + +package main + +import ( + "testing" + + "github.com/steveyegge/beads/internal/tracker" + "github.com/steveyegge/beads/internal/types" +) + +// TestSyncIsScoped covers the gate that decides whether to skip the +// post-sync parent reconcile pass. bd-9w3 root cause: ExcludeTypes is +// almost always non-empty on real rigs (via persistent +// linear.exclude_types config like "molecule,event"), so treating it as +// a scoping signal silently disabled the reconcile pass entirely on +// every full sync — orphans never got repaired. +// +// Contract: only flags the user EXPLICITLY passed this invocation count +// as scoping. Persistent config exclusions don't disable reconcile. +func TestSyncIsScoped(t *testing.T) { + cases := []struct { + name string + opts *tracker.SyncOptions + want bool + }{ + {"nil opts", nil, false}, + {"empty opts", &tracker.SyncOptions{}, false}, + {"parent id set", &tracker.SyncOptions{ParentID: "bd-foo"}, true}, + {"issue ids set", &tracker.SyncOptions{IssueIDs: []string{"bd-1", "bd-2"}}, true}, + {"type filter set", &tracker.SyncOptions{TypeFilter: []types.IssueType{types.TypeTask}}, true}, + + // bd-9w3: this is the case that was broken. A rig with persistent + // linear.exclude_types = "molecule,event" populates opts.ExcludeTypes + // on every sync — used to flip scoped=true and disable reconcile. + {"exclude types only (persistent config)", + &tracker.SyncOptions{ExcludeTypes: []types.IssueType{"molecule", "event"}}, false}, + + // Combined: exclude_types config + explicit --parent → still scoped + // (the --parent is the actual scoping signal). + {"exclude types + parent id", + &tracker.SyncOptions{ + ParentID: "bd-foo", + ExcludeTypes: []types.IssueType{"molecule"}, + }, true}, + + // Combined: exclude_types config + explicit --type → scoped + // (the --type is the scoping signal). + {"exclude types + type filter", + &tracker.SyncOptions{ + TypeFilter: []types.IssueType{types.TypeFeature}, + ExcludeTypes: []types.IssueType{"molecule"}, + }, true}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := syncIsScoped(tc.opts) + if got != tc.want { + t.Errorf("syncIsScoped(%+v) = %v, want %v", tc.opts, got, tc.want) + } + }) + } +} diff --git a/internal/linear/parent_reconcile.go b/internal/linear/parent_reconcile.go new file mode 100644 index 000000000..8a31567c7 --- /dev/null +++ b/internal/linear/parent_reconcile.go @@ -0,0 +1,249 @@ +package linear + +import ( + "context" + "errors" + "fmt" +) + +// fetchIssueAcrossTeams locates an issue by its Linear identifier across +// all configured team clients. Single-team setups hit the primary client +// directly; multi-team setups fall through each client in order until one +// returns a non-nil issue. Returns (issue, hostClient, nil) on success; +// the hostClient is the team's client that owned the issue and should be +// reused for subsequent mutations (so the update path doesn't re-probe +// and silently fall back to the wrong client on transient probe errors — +// see clientForExternalID's fallback behavior in tracker.go). +// +// Returns (nil, nil, nil) when no team has the issue. +func (t *Tracker) fetchIssueAcrossTeams(ctx context.Context, identifier string) (*Issue, *Client, error) { + if identifier == "" { + return nil, nil, nil + } + if len(t.teamIDs) <= 1 { + client := t.primaryClient() + if client == nil { + return nil, nil, errors.New("no Linear client available") + } + li, err := client.FetchIssueByIdentifier(ctx, identifier) + if err != nil { + return nil, nil, err + } + if li == nil { + return nil, nil, nil + } + return li, client, nil + } + // Multi-team: try each client. First non-nil result wins. Rate-limit + // errors abort immediately (the cross-team probe shouldn't burn + // through quota when the circuit breaker has already tripped). + for _, teamID := range t.teamIDs { + client := t.clients[teamID] + if client == nil { + continue + } + li, err := client.FetchIssueByIdentifier(ctx, identifier) + if err != nil { + if isRateLimitExhausted(err) { + return nil, nil, err + } + continue + } + if li != nil { + return li, client, nil + } + } + return nil, nil, nil +} + +// isRateLimitExhausted returns true when err (or any error it wraps) +// signals that Linear's rate-limit circuit breaker has tripped. +// Mirrors internal/tracker/engine.go isRateLimitExhausted, duplicated +// here to avoid an import cycle. +func isRateLimitExhausted(err error) bool { + if err == nil { + return false + } + type rle interface{ RateLimitExhausted() bool } + var r rle + return errors.As(err, &r) && r.RateLimitExhausted() +} + +// ParentLink describes a desired parent-child relationship to wire up +// on the Linear side. Both fields are Linear identifiers (e.g. "HOU-159") +// — typically extracted from each bead's external_ref via +// Tracker.ExtractIdentifier. +type ParentLink struct { + ChildIdentifier string + ParentIdentifier string +} + +// ParentReconcileStats summarizes a ReconcileParents run. +type ParentReconcileStats struct { + // Updated is the count of Linear issues whose parent field was changed + // (set, cleared, or rewired) by this pass. Zero in dry-run mode — see + // WouldUpdate for the dry-run counterpart. + Updated int + // WouldUpdate is the count of mutations the pass WOULD have issued + // in wet-run. Populated only in dry-run mode; zero in wet-run. + WouldUpdate int + // Mutations is the (child, parent) link list that was applied (wet-run) + // or would have been applied (dry-run). In wet-run, an entry is appended + // only after the IssueUpdate API call succeeds — so this list reflects + // state actually propagated to Linear, not attempted. In dry-run, all + // candidates that pass the idempotency check appear. Lets callers print + // per-link detail without having to re-derive it. + Mutations []ParentLink + // Skipped is the count of links where Linear's parent already matched + // the desired value — no API mutation was issued. + Skipped int + // NotFound is the list of identifiers (child or parent) that didn't + // resolve to a Linear issue (typically because their bead has no + // external_ref yet, or the Linear issue was deleted out-of-band). + // Their links are silently skipped; the next sync will retry. + NotFound []string + // Errors collects per-link failures that did not abort the pass. + Errors []error +} + +// ReconcileParents wires parent-child relationships from bead-side +// dependencies to Linear's parent issue field. Used as a post-sync pass +// to handle two cases that the per-issue create/update path can't cover: +// +// 1. New tree push: when a child is created before its parent's external +// ref is known to the engine, the create call has no parentId to send. +// This pass closes the loop after every issue in the tree has an +// external ref. +// 2. Orphan repair: existing Linear issues that were created (in earlier +// bd versions or by interrupted syncs) without parentId can be wired +// up retroactively. +// +// Idempotent: fetches each child's current parent and only issues +// IssueUpdate when the remote parent differs from the desired value. +// Each unique parent identifier is fetched once to resolve its UUID +// (IssueUpdateInput.parentId requires the internal UUID, not the +// human-readable identifier). +// +// When dryRun is true, the read-only fetches still run (so the caller +// gets accurate Skipped / NotFound counts and a populated Mutations +// list for preview output) but the IssueUpdate mutation is skipped. +// Mutations that would have fired increment stats.WouldUpdate instead +// of stats.Updated. +// +// Returns nil error when the pass completed (even if per-link errors +// were collected in Stats.Errors). A non-nil error indicates a setup-level +// failure that prevented any work from running. +func (t *Tracker) ReconcileParents(ctx context.Context, links []ParentLink, dryRun bool) (*ParentReconcileStats, error) { + stats := &ParentReconcileStats{} + if len(links) == 0 { + return stats, nil + } + if t.primaryClient() == nil { + return nil, errors.New("no Linear client available") + } + + // Cache identifier → (issue, host client) so we don't refetch when a + // parent is shared by many children, AND so the update path uses the + // SAME client that successfully fetched the child (avoids re-probing + // via clientForExternalID, which silently falls back to the primary + // client on transient probe errors and could send the update to the + // wrong team). + type entry struct { + issue *Issue + client *Client + } + fetched := make(map[string]entry, len(links)*2) + fetchIssue := func(identifier string) (entry, error) { + if cached, ok := fetched[identifier]; ok { + return cached, nil + } + issue, client, err := t.fetchIssueAcrossTeams(ctx, identifier) + if err != nil { + return entry{}, err + } + e := entry{issue: issue, client: client} + // Cache nil too — repeated lookups are still cheap. + fetched[identifier] = e + return e, nil + } + + for _, link := range links { + if link.ChildIdentifier == "" || link.ParentIdentifier == "" { + continue + } + + childE, err := fetchIssue(link.ChildIdentifier) + if err != nil { + // Rate-limit circuit breaker tripped — stop now rather than + // hammer the API for every remaining link. + if isRateLimitExhausted(err) { + return stats, fmt.Errorf("fetch child %s: %w", link.ChildIdentifier, err) + } + stats.Errors = append(stats.Errors, + fmt.Errorf("fetch child %s: %w", link.ChildIdentifier, err)) + continue + } + if childE.issue == nil { + stats.NotFound = append(stats.NotFound, link.ChildIdentifier) + continue + } + + parentE, err := fetchIssue(link.ParentIdentifier) + if err != nil { + if isRateLimitExhausted(err) { + return stats, fmt.Errorf("fetch parent %s: %w", link.ParentIdentifier, err) + } + stats.Errors = append(stats.Errors, + fmt.Errorf("fetch parent %s: %w", link.ParentIdentifier, err)) + continue + } + if parentE.issue == nil { + stats.NotFound = append(stats.NotFound, link.ParentIdentifier) + continue + } + + // Idempotency: skip if remote parent already matches by UUID. + if childE.issue.Parent != nil && childE.issue.Parent.ID == parentE.issue.ID { + stats.Skipped++ + continue + } + + if dryRun { + // Dry-run: record the intended mutation but skip the API call. + // All read-only state (fetch results, idempotency check above) + // matched wet-run, so the preview is trustworthy. + stats.Mutations = append(stats.Mutations, link) + stats.WouldUpdate++ + continue + } + + // Use the child's host client (resolved during fetch) so the + // update goes to the correct team in multi-team setups. + updated, err := childE.client.UpdateIssue(ctx, childE.issue.ID, map[string]interface{}{ + "parentId": parentE.issue.ID, + }) + if err != nil { + if isRateLimitExhausted(err) { + return stats, fmt.Errorf("set parent of %s → %s: %w", + link.ChildIdentifier, link.ParentIdentifier, err) + } + stats.Errors = append(stats.Errors, + fmt.Errorf("set parent of %s → %s: %w", + link.ChildIdentifier, link.ParentIdentifier, err)) + continue + } + // Refresh cache with the post-update issue (Linear returns the + // updated record), so a later link that references this child + // as a parent sees the freshest state. Host client is unchanged. + if updated != nil { + fetched[link.ChildIdentifier] = entry{issue: updated, client: childE.client} + } + // Record the mutation only AFTER the API call succeeds, so + // Mutations reflects actual state propagated to Linear (callers + // can trust the list for accurate post-sync reporting). + stats.Mutations = append(stats.Mutations, link) + stats.Updated++ + } + + return stats, nil +} diff --git a/internal/linear/parent_reconcile_test.go b/internal/linear/parent_reconcile_test.go new file mode 100644 index 000000000..c74d64490 --- /dev/null +++ b/internal/linear/parent_reconcile_test.go @@ -0,0 +1,644 @@ +package linear + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// linearMockHandler is a tiny GraphQL mock that routes by query keyword. +// Queries it understands: +// - "IssueByIdentifier" → returns issues[identifier] (or empty nodes) +// - "issueUpdate" → records the update and returns the (notional) issue +// +// All other queries return an empty data object. +// +// Fidelity gap (acceptable for unit tests): the real client's +// FetchIssueByIdentifier filters by team UUID AND issue number; this mock +// suffix-scans the `number.eq` value against issue identifiers and ignores +// team. That's fine here because we only care about parent-reconcile +// semantics, not the team-routing logic of FetchIssueByIdentifier itself. +type linearMockHandler struct { + t *testing.T + issues map[string]*Issue // identifier → issue (for fetch) + updates map[string]json.RawMessage // child UUID → input JSON (recorded) + fetches map[string]int // identifier → fetch call count + failNextRL bool // when true, next fetch returns ErrRateLimitExhausted + rateLimited int // count of rate-limited responses returned +} + +func newLinearMock(t *testing.T) *linearMockHandler { + return &linearMockHandler{ + t: t, + issues: map[string]*Issue{}, + updates: map[string]json.RawMessage{}, + fetches: map[string]int{}, + } +} + +func (h *linearMockHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var req GraphQLRequest + if err := json.Unmarshal(body, &req); err != nil { + h.t.Fatalf("mock: bad request JSON: %v", err) + } + w.Header().Set("Content-Type", "application/json") + + // If failNextRL is set, return rate-limit-exhausted on this single + // response (header drives the circuit breaker in Execute). + if h.failNextRL { + h.failNextRL = false + h.rateLimited++ + w.Header().Set("X-RateLimit-Requests-Remaining", "1") // < DefaultRateLimitFloor (100) + _ = json.NewEncoder(w).Encode(map[string]interface{}{"data": map[string]interface{}{}}) + return + } + + switch { + case strings.Contains(req.Query, "IssueByIdentifier"): + // FetchIssueByIdentifier filters by team + number; the mock keys + // directly by identifier extracted from the filter for simplicity. + filter, _ := req.Variables["filter"].(map[string]interface{}) + number, _ := filter["number"].(map[string]interface{}) + eq, _ := number["eq"].(float64) + // Recover identifier by scanning issues for a matching team+number. + // In the test fixture we just embed the number in identifier "TEAM-N". + var found *Issue + for ident, iss := range h.issues { + if strings.HasSuffix(ident, "-"+itoa(int(eq))) { + h.fetches[ident]++ + found = iss + break + } + } + nodes := []interface{}{} + if found != nil { + b, _ := json.Marshal(found) + var raw map[string]interface{} + _ = json.Unmarshal(b, &raw) + nodes = append(nodes, raw) + } + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "data": map[string]interface{}{ + "issues": map[string]interface{}{"nodes": nodes}, + }, + }) + return + case strings.Contains(req.Query, "issueUpdate"): + id, _ := req.Variables["id"].(string) + input, _ := json.Marshal(req.Variables["input"]) + h.updates[id] = input + // Return the (notional) updated issue. Tests don't depend on the + // exact echo, but we round-trip the relevant fields so the cached + // fetch is consistent if subsequent calls reference this child. + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "data": map[string]interface{}{ + "issueUpdate": map[string]interface{}{ + "success": true, + "issue": map[string]interface{}{ + "id": id, + "identifier": "ECHO", + "title": "echo", + "updatedAt": "2026-05-13T00:00:00Z", + }, + }, + }, + }) + return + } + _ = json.NewEncoder(w).Encode(map[string]interface{}{"data": map[string]interface{}{}}) +} + +func itoa(n int) string { + // stdlib without importing strconv twice + if n == 0 { + return "0" + } + neg := false + if n < 0 { + neg = true + n = -n + } + var b [12]byte + i := len(b) + for n > 0 { + i-- + b[i] = byte('0' + n%10) + n /= 10 + } + if neg { + i-- + b[i] = '-' + } + return string(b[i:]) +} + +func newTestLinearTracker(t *testing.T, serverURL string) *Tracker { + tr := &Tracker{ + teamIDs: []string{"team-uuid"}, + clients: map[string]*Client{ + "team-uuid": NewClient("test-key", "team-uuid").WithEndpoint(serverURL), + }, + } + return tr +} + +// newTestMultiTeamTracker wires a tracker with N teams, each pointed at its +// own mock-server URL. Returns the tracker and the same teamIDs slice in +// stable order (matching Tracker.teamIDs iteration order). +func newTestMultiTeamTracker(t *testing.T, serverURLs []string) (*Tracker, []string) { + teamIDs := make([]string, len(serverURLs)) + clients := make(map[string]*Client, len(serverURLs)) + for i, url := range serverURLs { + id := "team-" + itoa(i) + teamIDs[i] = id + clients[id] = NewClient("test-key", id).WithEndpoint(url) + } + return &Tracker{teamIDs: teamIDs, clients: clients}, teamIDs +} + +// TestReconcileParents_HappyPath verifies that a child needing its parent +// set produces exactly one fetch per unique identifier and one UpdateIssue +// call carrying the parent's UUID. +func TestReconcileParents_HappyPath(t *testing.T) { + mock := newLinearMock(t) + mock.issues["TEAM-1"] = &Issue{ID: "uuid-child", Identifier: "TEAM-1"} // child has no parent yet + mock.issues["TEAM-2"] = &Issue{ID: "uuid-parent", Identifier: "TEAM-2"} // parent + server := httptest.NewServer(mock) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-2"}, + }, false) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.Updated != 1 || stats.Skipped != 0 || len(stats.Errors) != 0 { + t.Fatalf("stats = %+v, want Updated=1 Skipped=0", stats) + } + if len(mock.updates) != 1 { + t.Fatalf("expected 1 issueUpdate call, got %d", len(mock.updates)) + } + // The update target should be the child's UUID. + input, ok := mock.updates["uuid-child"] + if !ok { + t.Fatalf("expected update on uuid-child, got updates: %v", mock.updates) + } + if !strings.Contains(string(input), `"parentId":"uuid-parent"`) { + t.Errorf("update input missing parent UUID: %s", input) + } +} + +// TestReconcileParents_IdempotentSkip verifies that when the child's +// remote parent already matches, no UpdateIssue is issued. +func TestReconcileParents_IdempotentSkip(t *testing.T) { + mock := newLinearMock(t) + mock.issues["TEAM-1"] = &Issue{ID: "uuid-child", Identifier: "TEAM-1", + Parent: &Parent{ID: "uuid-parent", Identifier: "TEAM-2"}} + mock.issues["TEAM-2"] = &Issue{ID: "uuid-parent", Identifier: "TEAM-2"} + server := httptest.NewServer(mock) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-2"}, + }, false) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.Updated != 0 || stats.Skipped != 1 { + t.Fatalf("stats = %+v, want Updated=0 Skipped=1", stats) + } + if len(mock.updates) != 0 { + t.Errorf("expected no updates (idempotent), got %d", len(mock.updates)) + } +} + +// TestReconcileParents_RewiresWrongParent verifies that a child currently +// pointing at a different parent gets its parent rewired (Linear-side state +// took precedence over local intent — bd-ena's intended behavior). +func TestReconcileParents_RewiresWrongParent(t *testing.T) { + mock := newLinearMock(t) + mock.issues["TEAM-1"] = &Issue{ID: "uuid-child", Identifier: "TEAM-1", + Parent: &Parent{ID: "uuid-WRONG-parent", Identifier: "TEAM-99"}} + mock.issues["TEAM-2"] = &Issue{ID: "uuid-parent", Identifier: "TEAM-2"} + server := httptest.NewServer(mock) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-2"}, + }, false) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.Updated != 1 { + t.Errorf("Updated = %d, want 1 (wrong parent should be rewired)", stats.Updated) + } + input := mock.updates["uuid-child"] + if !strings.Contains(string(input), `"parentId":"uuid-parent"`) { + t.Errorf("expected rewire to uuid-parent, got: %s", input) + } +} + +// TestReconcileParents_FetchCaching verifies that a parent referenced by +// multiple children is fetched only once. (Cuts API calls in the common +// case where one epic has many sub-issues.) +func TestReconcileParents_FetchCaching(t *testing.T) { + mock := newLinearMock(t) + for i, ident := range []string{"TEAM-10", "TEAM-11", "TEAM-12"} { + _ = i + mock.issues[ident] = &Issue{ID: "uuid-" + ident, Identifier: ident} + } + mock.issues["TEAM-99"] = &Issue{ID: "uuid-parent", Identifier: "TEAM-99"} + server := httptest.NewServer(mock) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + links := []ParentLink{ + {ChildIdentifier: "TEAM-10", ParentIdentifier: "TEAM-99"}, + {ChildIdentifier: "TEAM-11", ParentIdentifier: "TEAM-99"}, + {ChildIdentifier: "TEAM-12", ParentIdentifier: "TEAM-99"}, + } + stats, err := tr.ReconcileParents(context.Background(), links, false) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.Updated != 3 { + t.Errorf("Updated = %d, want 3", stats.Updated) + } + if mock.fetches["TEAM-99"] != 1 { + t.Errorf("parent fetched %d times, want 1 (caching broken)", mock.fetches["TEAM-99"]) + } +} + +// TestReconcileParents_MissingChildOrParent verifies that links with +// unresolvable identifiers go to NotFound rather than failing the pass. +func TestReconcileParents_MissingChildOrParent(t *testing.T) { + mock := newLinearMock(t) + mock.issues["TEAM-1"] = &Issue{ID: "uuid-child", Identifier: "TEAM-1"} + // TEAM-99 (parent) and TEAM-2 (child for second link) are intentionally + // absent. + server := httptest.NewServer(mock) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-99"}, // parent missing + {ChildIdentifier: "TEAM-2", ParentIdentifier: "TEAM-1"}, // child missing + }, false) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.Updated != 0 { + t.Errorf("Updated = %d, want 0", stats.Updated) + } + if len(stats.NotFound) != 2 { + t.Errorf("NotFound = %v, want 2 entries", stats.NotFound) + } + if len(mock.updates) != 0 { + t.Errorf("expected no updates when targets missing, got %d", len(mock.updates)) + } +} + +// TestReconcileParents_EmptyLinks short-circuits cleanly. +func TestReconcileParents_EmptyLinks(t *testing.T) { + tr := &Tracker{} // no client needed + stats, err := tr.ReconcileParents(context.Background(), nil, false) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.Updated != 0 || stats.Skipped != 0 { + t.Errorf("stats = %+v, want zero", stats) + } +} + +// TestReconcileParents_MultiTeam verifies cross-team probing: a child +// living on team B and a parent on team A both resolve, and the update +// goes to the team-client that owns the child (not the primary team's +// client). This guards against the silent-fallback bug in +// clientForExternalID where probe failures route to the primary client. +func TestReconcileParents_MultiTeam(t *testing.T) { + mockA := newLinearMock(t) + mockA.issues["TEAM-1"] = &Issue{ID: "uuid-A1-parent", Identifier: "TEAM-1"} + srvA := httptest.NewServer(mockA) + defer srvA.Close() + + mockB := newLinearMock(t) + mockB.issues["TEAM-2"] = &Issue{ID: "uuid-B2-child", Identifier: "TEAM-2"} + srvB := httptest.NewServer(mockB) + defer srvB.Close() + + tr, _ := newTestMultiTeamTracker(t, []string{srvA.URL, srvB.URL}) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "TEAM-2", ParentIdentifier: "TEAM-1"}, + }, false) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.Updated != 1 { + t.Fatalf("Updated = %d, want 1", stats.Updated) + } + // Update must hit team B's mock (where the child lives), not team A's. + if _, ok := mockB.updates["uuid-B2-child"]; !ok { + t.Errorf("expected update on team B mock for uuid-B2-child, got: %v / %v", + mockA.updates, mockB.updates) + } + if len(mockA.updates) != 0 { + t.Errorf("expected no updates on team A (parent's team), got: %v", mockA.updates) + } +} + +// TestReconcileParents_AbortsOnRateLimit verifies that hitting the rate- +// limit circuit breaker stops the pass immediately instead of grinding +// through the remaining links and accumulating failures. +func TestReconcileParents_AbortsOnRateLimit(t *testing.T) { + mock := newLinearMock(t) + mock.issues["TEAM-1"] = &Issue{ID: "uuid-child1", Identifier: "TEAM-1"} + mock.issues["TEAM-2"] = &Issue{ID: "uuid-child2", Identifier: "TEAM-2"} + mock.issues["TEAM-99"] = &Issue{ID: "uuid-parent", Identifier: "TEAM-99"} + mock.failNextRL = true // first request returns ErrRateLimitExhausted + server := httptest.NewServer(mock) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-99"}, + {ChildIdentifier: "TEAM-2", ParentIdentifier: "TEAM-99"}, + }, false) + if err == nil { + t.Fatal("expected error from rate-limit abort, got nil") + } + if !strings.Contains(err.Error(), "rate limit") && !strings.Contains(err.Error(), "RateLimitExhausted") { + t.Errorf("expected rate-limit error, got: %v", err) + } + // Pass should bail out — at most the first child was processed; subsequent + // links should never reach IssueUpdate. + if len(mock.updates) > 0 { + t.Errorf("expected 0 updates after rate-limit abort, got %d", len(mock.updates)) + } + if stats.Updated != 0 { + t.Errorf("Updated = %d, want 0 (no updates after abort)", stats.Updated) + } + if mock.rateLimited != 1 { + t.Errorf("expected exactly 1 rate-limited response (single failure → abort), got %d", mock.rateLimited) + } +} + +// TestReconcileParents_BlankIdentifiersSkipped — defensive guard against +// callers that build links with empty fields. +func TestReconcileParents_BlankIdentifiersSkipped(t *testing.T) { + mock := newLinearMock(t) + server := httptest.NewServer(mock) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "", ParentIdentifier: "TEAM-2"}, + {ChildIdentifier: "TEAM-1", ParentIdentifier: ""}, + }, false) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.Updated != 0 { + t.Errorf("Updated = %d, want 0", stats.Updated) + } + if len(mock.updates) != 0 || len(mock.fetches) != 0 { + t.Errorf("expected no API calls for blank links, fetches=%v updates=%v", + mock.fetches, mock.updates) + } +} + +// TestReconcileParents_DryRunNoMutations is the bd-5zh acceptance: when +// dryRun=true, the read-only fetches still run (Skipped, NotFound, and +// Mutations populate correctly) but ZERO IssueUpdate calls fire. WouldUpdate +// counts the mutations that would have been issued; Updated stays 0. +func TestReconcileParents_DryRunNoMutations(t *testing.T) { + mock := newLinearMock(t) + mock.issues["TEAM-1"] = &Issue{ID: "uuid-c1", Identifier: "TEAM-1"} // needs parent + mock.issues["TEAM-2"] = &Issue{ID: "uuid-c2", Identifier: "TEAM-2", // + Parent: &Parent{ID: "uuid-p", Identifier: "TEAM-99"}} // already correct + mock.issues["TEAM-3"] = &Issue{ID: "uuid-c3", Identifier: "TEAM-3"} // needs parent + mock.issues["TEAM-99"] = &Issue{ID: "uuid-p", Identifier: "TEAM-99"} + server := httptest.NewServer(mock) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-99"}, + {ChildIdentifier: "TEAM-2", ParentIdentifier: "TEAM-99"}, + {ChildIdentifier: "TEAM-3", ParentIdentifier: "TEAM-99"}, + }, true) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.Updated != 0 { + t.Errorf("Updated = %d, want 0 in dry-run", stats.Updated) + } + if stats.WouldUpdate != 2 { + t.Errorf("WouldUpdate = %d, want 2 (TEAM-1 + TEAM-3 need parent set)", stats.WouldUpdate) + } + if stats.Skipped != 1 { + t.Errorf("Skipped = %d, want 1 (TEAM-2 already correct)", stats.Skipped) + } + if len(mock.updates) != 0 { + t.Errorf("dry-run must not issue IssueUpdate; got %d updates: %v", len(mock.updates), mock.updates) + } + if len(stats.Mutations) != 2 { + t.Fatalf("Mutations = %v, want 2 entries", stats.Mutations) + } + // Mutations should carry the original identifiers in order of input. + if stats.Mutations[0].ChildIdentifier != "TEAM-1" || stats.Mutations[0].ParentIdentifier != "TEAM-99" { + t.Errorf("Mutations[0] = %+v, want TEAM-1 → TEAM-99", stats.Mutations[0]) + } + if stats.Mutations[1].ChildIdentifier != "TEAM-3" || stats.Mutations[1].ParentIdentifier != "TEAM-99" { + t.Errorf("Mutations[1] = %+v, want TEAM-3 → TEAM-99", stats.Mutations[1]) + } +} + +// TestReconcileParents_DryRunIdempotentSkipUnchanged verifies that when +// every link is already correct, dry-run produces zero WouldUpdate and +// matches wet-run's Skipped count. +func TestReconcileParents_DryRunIdempotentSkipUnchanged(t *testing.T) { + mock := newLinearMock(t) + mock.issues["TEAM-1"] = &Issue{ID: "uuid-c", Identifier: "TEAM-1", + Parent: &Parent{ID: "uuid-p", Identifier: "TEAM-2"}} + mock.issues["TEAM-2"] = &Issue{ID: "uuid-p", Identifier: "TEAM-2"} + server := httptest.NewServer(mock) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-2"}, + }, true) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.WouldUpdate != 0 { + t.Errorf("WouldUpdate = %d, want 0 (already correct)", stats.WouldUpdate) + } + if stats.Skipped != 1 { + t.Errorf("Skipped = %d, want 1", stats.Skipped) + } + if len(stats.Mutations) != 0 { + t.Errorf("Mutations = %v, want empty (no changes needed)", stats.Mutations) + } +} + +// TestReconcileParents_DryRunMissingTargetsNotFound verifies that dry-run +// still surfaces NotFound entries for unresolvable identifiers, so the user +// gets the same visibility into orphan targets as wet-run. +func TestReconcileParents_DryRunMissingTargetsNotFound(t *testing.T) { + mock := newLinearMock(t) + mock.issues["TEAM-1"] = &Issue{ID: "uuid-c", Identifier: "TEAM-1"} + // TEAM-99 (parent) intentionally absent. + server := httptest.NewServer(mock) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-99"}, + }, true) + if err != nil { + t.Fatalf("ReconcileParents err: %v", err) + } + if stats.WouldUpdate != 0 || stats.Updated != 0 { + t.Errorf("Would/Updated = %d/%d, want 0/0", stats.WouldUpdate, stats.Updated) + } + if len(stats.NotFound) != 1 || stats.NotFound[0] != "TEAM-99" { + t.Errorf("NotFound = %v, want [TEAM-99]", stats.NotFound) + } +} + +// TestReconcileParents_DryRunMatchesWetRunMutationSet verifies that the +// Mutations list is identical between dry-run and wet-run for the same +// input. This is the property that makes dry-run a trustworthy pre-flight: +// what you see is what you'll get. +func TestReconcileParents_DryRunMatchesWetRunMutationSet(t *testing.T) { + makeMock := func() *linearMockHandler { + m := newLinearMock(t) + m.issues["TEAM-1"] = &Issue{ID: "uuid-c1", Identifier: "TEAM-1"} + m.issues["TEAM-2"] = &Issue{ID: "uuid-c2", Identifier: "TEAM-2"} + m.issues["TEAM-99"] = &Issue{ID: "uuid-p", Identifier: "TEAM-99"} + return m + } + links := []ParentLink{ + {ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-99"}, + {ChildIdentifier: "TEAM-2", ParentIdentifier: "TEAM-99"}, + } + + // Dry-run + dryMock := makeMock() + drySrv := httptest.NewServer(dryMock) + defer drySrv.Close() + dryTr := newTestLinearTracker(t, drySrv.URL) + dryStats, err := dryTr.ReconcileParents(context.Background(), links, true) + if err != nil { + t.Fatalf("dry: %v", err) + } + + // Wet-run + wetMock := makeMock() + wetSrv := httptest.NewServer(wetMock) + defer wetSrv.Close() + wetTr := newTestLinearTracker(t, wetSrv.URL) + wetStats, err := wetTr.ReconcileParents(context.Background(), links, false) + if err != nil { + t.Fatalf("wet: %v", err) + } + + if dryStats.WouldUpdate != wetStats.Updated { + t.Errorf("dry WouldUpdate=%d vs wet Updated=%d (must match)", + dryStats.WouldUpdate, wetStats.Updated) + } + if len(dryStats.Mutations) != len(wetStats.Mutations) { + t.Fatalf("Mutations length differs: dry=%d wet=%d", + len(dryStats.Mutations), len(wetStats.Mutations)) + } + for i := range dryStats.Mutations { + if dryStats.Mutations[i] != wetStats.Mutations[i] { + t.Errorf("Mutations[%d] differ: dry=%+v wet=%+v", + i, dryStats.Mutations[i], wetStats.Mutations[i]) + } + } + // Sanity: wet-run actually issued updates, dry-run did not. + if len(dryMock.updates) != 0 { + t.Errorf("dry mock saw %d updates; expected 0", len(dryMock.updates)) + } + if len(wetMock.updates) != 2 { + t.Errorf("wet mock saw %d updates; expected 2", len(wetMock.updates)) + } +} + +// TestReconcileParents_WetRunFailureDoesNotRecordMutation verifies that +// when a wet-run UpdateIssue call fails (e.g. transient API error), the +// failed mutation is NOT appended to stats.Mutations. The contract is +// that Mutations reflects state actually propagated to Linear in wet-run, +// so callers can trust it for post-sync reporting. +func TestReconcileParents_WetRunFailureDoesNotRecordMutation(t *testing.T) { + // Custom handler: succeeds on fetch, returns success=false on update. + updateAttempts := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var req GraphQLRequest + if err := json.Unmarshal(body, &req); err != nil { + t.Fatalf("bad request: %v", err) + } + w.Header().Set("Content-Type", "application/json") + + switch { + case strings.Contains(req.Query, "IssueByIdentifier"): + filter, _ := req.Variables["filter"].(map[string]interface{}) + number, _ := filter["number"].(map[string]interface{}) + eq, _ := number["eq"].(float64) + id := "uuid-" + itoa(int(eq)) + ident := "TEAM-" + itoa(int(eq)) + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "data": map[string]interface{}{ + "issues": map[string]interface{}{ + "nodes": []interface{}{ + map[string]interface{}{"id": id, "identifier": ident, + "createdAt": "2026-05-22T00:00:00Z", "updatedAt": "2026-05-22T00:00:00Z"}, + }, + }, + }, + }) + case strings.Contains(req.Query, "issueUpdate"): + updateAttempts++ + // Return success=false to surface as an error to the client. + _ = json.NewEncoder(w).Encode(map[string]interface{}{ + "data": map[string]interface{}{ + "issueUpdate": map[string]interface{}{"success": false, "issue": nil}, + }, + }) + default: + _ = json.NewEncoder(w).Encode(map[string]interface{}{"data": map[string]interface{}{}}) + } + })) + defer server.Close() + + tr := newTestLinearTracker(t, server.URL) + stats, err := tr.ReconcileParents(context.Background(), []ParentLink{ + {ChildIdentifier: "TEAM-1", ParentIdentifier: "TEAM-2"}, + }, false) + if err != nil { + t.Fatalf("ReconcileParents: %v", err) + } + if updateAttempts != 1 { + t.Errorf("expected 1 update attempt, got %d", updateAttempts) + } + if stats.Updated != 0 { + t.Errorf("Updated = %d, want 0 (API call failed)", stats.Updated) + } + if len(stats.Mutations) != 0 { + t.Errorf("Mutations = %v, want empty (no successful mutation)", stats.Mutations) + } + if len(stats.Errors) != 1 { + t.Errorf("Errors = %v, want 1 entry", stats.Errors) + } +}