beads/cmd/bd/sync_is_scoped_test.go
Afik 98f3cb43a5
fix(linear): wire parent-child relationships to Linear's parent field (#3930)
* fix(linear): wire parent-child relationships to Linear's parent field

bd-ena: bd linear sync wasn't pushing parent-child relationships to
Linear, leaving epic trees flat (every issue parent=null on the Linear
side). Concretely on the houmanoids_www rig: a 73-issue tree push
created HOU-151..HOU-209 all with parent=null, even though the local
beads structure was correctly parent-child-linked.

Root cause: Tracker.CreateIssue and UpdateIssue never set parentId; the
GraphQL client's buildIssueCreateInput didn't accept it; the field
mapper's IssueToTracker dropped parent entirely.

Fix: post-sync reconciliation pass.

After engine.Sync completes (push, non-dry-run, success, full scope):
1. Walk local store for beads with Linear external_refs and a
   parent-child dependency to a parent that also has an external_ref.
2. For each (child, parent) pair, fetch both from Linear (cached by
   identifier so repeated parents cost one fetch).
3. If child's remote parent doesn't match the desired parent UUID,
   issue IssueUpdate{parentId} on the child's host team-client.

Idempotent: re-running on a healthy tree produces only Skipped++ events,
no API mutations. This means a single run of `bd linear sync` will both:
  (a) wire up new trees that were just pushed in the same sync, AND
  (b) repair pre-existing orphan trees from before this fix landed
      (HOU-164..209 on houmanoids will get parents on next sync).

Multi-team correctness: fetchIssueAcrossTeams returns the host client
alongside the issue, and the update reuses that client. Avoids a
silent fall-through to the primary team's client (clientForExternalID's
non-rate-limit error path falls back to primary, which would silently
update the wrong team's issue in a multi-team rig).

Rate-limit safety: the pass aborts immediately when Linear's circuit
breaker trips. Already-applied updates are reported in the partial
"Reconciled N parent links" line before the warning surfaces.

Scope safety: skipped on scoped syncs (--parent / --type / --exclude-
type / --issue-id) since the reconciler walks the full local tree, not
just the in-scope subset. A subsequent unscoped sync picks up the work.

Tests (internal/linear/parent_reconcile_test.go, 9 cases):
- HappyPath, IdempotentSkip, RewiresWrongParent
- FetchCaching (parent-shared-by-N children fetched once)
- MissingChildOrParent (NotFound, no errors)
- EmptyLinks, BlankIdentifiersSkipped (defensive)
- MultiTeam (cross-team probing + correct host-client routing)
- AbortsOnRateLimit (circuit breaker stops the pass cleanly)

Codex-Reviewed-By: codex-rescue (2 rounds; second round caught the
multi-team silent-fallback hazard and the scoped-sync interaction)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* feat(linear): dry-run preview for parent reconciler

bd-5zh: the bd-ena parent-child reconciler had no dry-run mode — every
call mutated Linear via UpdateIssue, so callers were forced to gate on
`!dryRun` at the call site. That defeats the point of
`bd linear sync --dry-run` as a pre-flight: the orphan-repair scope
(HOU-164..209 on the houmanoids_www rig) was invisible until you
committed to a wet sync.

API change: `ReconcileParents(ctx, links)` → `ReconcileParents(ctx,
links, dryRun bool)`. ParentReconcileStats gains:
  - WouldUpdate int     — count of mutations that WOULD fire (dry-run);
                          zero in wet-run
  - Mutations []ParentLink — (child, parent) pairs that were applied
                          (wet-run, only after IssueUpdate success) or
                          that would apply (dry-run). Lets callers print
                          per-link detail without re-deriving.

When dryRun is true the per-link logic still runs through fetch,
fetch-caching, and idempotency-check — only the API mutation is skipped.
The preview is therefore trustworthy: same NotFound/Skipped behavior,
same Mutations set as wet-run for the same input (locked by
TestReconcileParents_DryRunMatchesWetRunMutationSet).

cmd/bd/linear.go:
- Drops the `!dryRun` gate; reconcile pass now runs in dry-run too.
- `reconcileLinearParents` takes new dryRun + jsonOutput params.
- In dry-run: prints `[dry-run] Would reconcile N parent links` summary
  + one `[dry-run] Would set parent of CHILD → PARENT` per Mutations
  entry. Suppressed when --json is set so the JSON envelope stays clean.
- `effectivePush := push || (!push && !pull)` mirrors engine.Sync's
  bidirectional default so `bd linear sync --dry-run` (no direction
  flag) still previews the reconcile.

Wet-run contract tightened (codex round 1 catch): Mutations is now
appended only AFTER the UpdateIssue API call succeeds, so the list
reflects state actually propagated to Linear — not attempted writes
that failed. Locked by TestReconcileParents_WetRunFailureDoesNotRecordMutation.

Scoped-sync skip preserved (codex confirmed): a scoped sync that
silently expanded its surface in dry-run mode would surprise the user.

Tests: 9 existing tests updated to pass `false` for dryRun (no behavior
change). 5 new tests:
- DryRunNoMutations — mixed already-correct + needs-parent; verifies
  WouldUpdate, Skipped, Mutations contents + ordering, zero mock.updates.
- DryRunIdempotentSkipUnchanged — all correct → zero WouldUpdate.
- DryRunMissingTargetsNotFound — unresolvable identifiers surface in
  NotFound during dry-run too.
- DryRunMatchesWetRunMutationSet — symmetry property: dry-run and
  wet-run produce identical Mutations sets for identical input.
- WetRunFailureDoesNotRecordMutation — issueUpdate returning
  success=false produces Errors entry, NOT a Mutations entry.

Known gap: reconcile preview lines aren't surfaced in --json output
(would require Linear-specific field on shared SyncResult; deferred).
Errors still flow through SyncResult.Warnings either way.

Codex-Reviewed-By: codex-rescue (2 rounds; caught Mutations-recorded-
before-success contract bug, --json output mixing, and the
bidirectional-default gate hole)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* fix(linear): persistent linear.exclude_types no longer disables parent reconcile

bd-9w3: on the houmanoids_www rig the post-sync parent reconciler was
silently skipped on every full sync — HOU-164..209 stayed orphaned
despite the surrounding sync running clean. Traced via debug prints:
syncIsScoped(&opts) returned true because opts.ExcludeTypes was non-
empty (the rig has persistent `linear.exclude_types = "molecule,event"`,
merged into opts by the CLI). The gate then skipped reconcile.

Fix: drop ExcludeTypes from syncIsScoped. The reconcile pass only
mutates the parent FIELD on the child issue — it never touches the
parent issue itself — so excluding "molecule" or "event" types from
push doesn't conflict with wiring up parent-child for the remaining
types. ExcludeTypes is primarily a persistent-config knob, not a
temporary user scoping intent for THIS invocation.

Kept as scoping signals (all explicit-CLI-only):
  - ParentID  (--parent)
  - IssueIDs  (--issues / --issue-id)
  - TypeFilter (--type)

Tests: cmd/bd/sync_is_scoped_test.go covers 8 sub-cases including the
regression "exclude types only (persistent config)" → false, plus the
combined cases (exclude_types + parent_id → still scoped; exclude_types
+ type_filter → still scoped).

Verified on the houmanoids_www rig (via the integration sibling
binary, since the upstream binary's schema is incompatible with the
rig DB):
  bd linear sync --pull --push --dry-run
  → "[dry-run] Would reconcile 62 Linear parent links"
  → HOU-164 → HOU-159, HOU-165 → HOU-205, ... Phase epics → root epic.

Mayor's bd-9w3 nudge raised an "epic-aware silent skip" hypothesis from
the bd-2og epics-as-projects design — confirmed NOT present on this
code path. The reconciler treats all bead types (including epics)
identically; the 62 planned mutations include Phase-epic → root-epic
links (HOU-202 → HOU-159, HOU-205 → HOU-159).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-07-06 22:16:07 -07:00

64 lines
2.2 KiB
Go

//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)
}
})
}
}