Skip to content

fix(chain): --chain successors branch from main, not predecessor's committed work (up-front worktree provisioning) #748

Closed

Description

@admarble

Summary

sequant run <a> <b> --chain does not make successor issues branch from their predecessor's committed work on a fresh run. Each successor branches from main, contradicting the flag's help text ("Chain issues: each branches from previous") and the code's own intent comment.

Repro

sequant run 125 126 --chain --qa-gate -Q --testgen

Banner printed Chain: main → #125 → #126, but git ancestry afterward:

merge-base(#125, #126) = b5a61c4   # == run startCommit (main)
#125's exec commit c520341 is NOT an ancestor of #126

So #126 was built on plain main, missing all of #125's work.

Root cause

ensureWorktreesChain (src/lib/workflow/worktree-manager.ts:905-942) is called once at src/lib/workflow/run-orchestrator.ts:769 — before any issue executes. It loops over all issues up front, branching each successor from the predecessor's branch name. At provisioning time the predecessor branch still points at main (it hasn't committed yet), so every successor effectively branches from main.

There is no re-rebase of a successor onto its predecessor's completed tip on a fresh run:

  • The chain-rebase inside ensureWorktree (worktree-manager.ts:580-651) only fires when a branch already exists (re-run path only).
  • rebaseBeforePR (src/lib/workflow/batch-executor.ts:1142-1155) rebases the last chain issue onto origin/main, not onto its predecessor; intermediate issues skip it.
  • The AC-1/AC-2 comment at batch-executor.ts:1139-1141 says intermediate branches "must stay based on their predecessor" — but the code never achieves this on a fresh run.

--stacked does not fix this: it only sets the GitHub PR base (predecessorBranch/stackManifest → createPR, run-orchestrator.ts:973-986). There is no execution-time rebase, so --stacked would produce a PR targeting the predecessor whose branch still doesn't contain the predecessor's commits.

Why tests didn't catch it

  • __tests__/run-orchestrator.test.ts mocks ensureWorktreesChain entirely — real ancestry is never exercised.
  • src/commands/run.test.ts:836-855 ("chain branch naming") is tautological: expect(baseBranch).toBe(issues[i-1].branch).
  • src/commands/run.test.ts:857-893 only tests the re-run rebase guard — the one path where rebase actually fires.

No test does real git on a fresh run asserting git merge-base --is-ancestor <predecessor-tip> <successor>.

Fix options

  1. Lazy per-issue worktree creation — provision each successor's worktree just-in-time inside the sequential loop, after the predecessor completes/commits. Most correct; honors the contract directly. Larger refactor (worktree creation, cleanup registration, and chain-break detection move out of setup into the execution loop; loses the up-front "all worktrees ready" UX).
  2. Re-rebase successor onto predecessor tip immediately before it executes — keep up-front provisioning, but git rebase <predecessorBranch> at the top of executeOneIssue for chain issues. Smaller; reuses existing conflict/abort machinery. Must target the local predecessor branch, not origin/main.
  3. Fix help text only (bin/cli.ts:292) — documentation retreat; leaves users with no working code-stacking path.

Recommend option 1 or 2 (option 2 is lower-risk).

Acceptance criteria

  • On a fresh --chain run, a successor's branch contains its predecessor's committed work (or the help text + docs are corrected to describe actual behavior, if WONTFIX-by-design).
  • A real-git integration test asserts git merge-base --is-ancestor <predecessor-exec-commit> <successor-HEAD> on a fresh chain run.
  • bin/cli.ts:292 help text accurately reflects final behavior.

Related

Cross-references #289, #126, #133, #604, #605. #289 and #126 (closed) addressed only the pre-existing-worktree rebase path; #133 added --qa-gate for staleness. None covers the up-front-provisioning timing on a fresh run.

Activity

  1. added
    bug
    cli
    multi-agent
    on Jun 26, 2026
  2. admarble commented on Jun 28, 2026

    @admarble
    ContributorAuthor

    → PROCEED — --chain successors branch from main not predecessor; root cause + fix options identified, clear ACs.

    Workflow: exec → qa (skip spec — bug label, root cause pinned to ensureWorktreesChain timing; issue already recommends option 2 / re-rebase). Quality loop on (real-git integration test required).

    ⚠ Overlaps #749 on batch-executor.ts + run-orchestrator.ts — run sequentially, not parallel.

    npx sequant run 748 -q --phases exec,qa
    
  3. admarble commented on Jun 28, 2026

    @admarble
    ContributorAuthor

    /spec Plan — #748

    Approach: Option 2 (re-rebase each chain successor onto its predecessor's local committed tip, just before the successor executes). Lower-risk than lazy provisioning; reuses existing conflict/abort machinery.

    Plan

    • executeOneIssue (run-orchestrator.ts:1059): for chain issues with i>0, resolve the local predecessor branch from worktreeMap (independent of --stacked) and rebase the successor's worktree onto it before its phases run.
    • Rebase targets the local feature/<predecessor> ref (NOT origin/main). Extract a rebaseOntoLocalBranch helper from the existing chain-rebase block (worktree-manager.ts:580-651); do not reuse rebaseBeforePR (origin-targeted, PR-time).
    • Conflict → abort + warn + mark chain broken (don't silently green a broken link).
    • Update --chain help text (bin/cli.ts:292) to match (AC-3).

    Verification

    • AC-1: Fresh --chain run — successor branch contains predecessor's committed work (Integration / real git)
    • AC-2: Test asserts git merge-base --is-ancestor <predecessor-exec-commit> <successor-HEAD>, with no mock of ensureWorktreesChain or the rebase step (Integration)
    • AC-3: bin/cli.ts:292 help text accurate (Unit / grep)

    Open questions

    1. Audit for any cached pre-rebase successor SHA (PR creation / state.json).
    2. Intermediate-link conflict policy: abort + warn (recommended) vs hard-fail.

    ⚠️ Overlaps #749 on batch-executor.ts/run-orchestrator.ts — sequence the merges, don't run in parallel.

    Workflow: exec → qa, quality loop on.

  4. added
    planned
    on Jun 28, 2026
  5. admarble commented on Jun 28, 2026

    @admarble
    ContributorAuthor

    /exec Progress Update — #748

    Approach: Option 2 (re-rebase each chain successor onto its predecessor's local committed tip just before it runs). Implemented per /spec plan.

    AC Coverage

    AC Description Status Evidence
    AC-1 Fresh --chain run: successor contains predecessor's committed work ✅ Implemented executeSequential rebase step in run-orchestrator.ts; integration test
    AC-2 Real-git test: git merge-base --is-ancestor <pred-exec-commit> <succ-HEAD> on a fresh run, no mock of ensureWorktreesChain/rebase ✅ Implemented src/lib/workflow/chain-rebase.integration.test.ts
    AC-3 bin/cli.ts:292 --chain help text accurate ✅ Implemented Now reads "each successor is rebased onto the previous issue's committed work before it runs"

    Key files changed

    • src/lib/workflow/worktree-manager.ts — new exported rebaseOntoLocalBranch helper (+ LocalRebaseResult type); existing chain-rebase block (re-run path) refactored to reuse it (de-dup).
    • src/lib/workflow/run-orchestrator.ts — executeSequential rebases each chain successor (i>0) onto predecessor's local branch before execution; conflict → abort + warn (don't silently green a broken link).
    • bin/cli.ts — --chain help text (AC-3).
    • src/lib/workflow/chain-rebase.integration.test.ts (new) — 3 real-git tests: re-chain success, successor's own commits carried forward, conflict abort+restore. Reproduces the pre-fix BUG state (is-ancestor false) before asserting the fix.
    • __tests__/run-orchestrator.test.ts — wiring tests (rebases each successor onto predecessor's local branch; no rebase when chain off) + mock export.

    Open questions resolved

    1. Cached pre-rebase SHA? No execution-time SHA is cached before the rebase — PR base (predecessorBranch/stackManifest) is computed at PR-creation time, and the rebase runs at the top of the loop iteration before phases. Safe.
    2. Intermediate-link conflict policy: abort + warn + continue (spec-recommended). The successor keeps its existing base and still executes; the warning ensures the broken link is never silent.

    Checks

    • npm run build ✅ · npm run lint ✅
    • chain-rebase.integration.test.ts ✅ 3/3 · run-orchestrator.test.ts ✅ 22/22
    • Full workflow + run suites green except one unrelated phase-registry.integration.test.ts tsx-spawn timeout flake (passes in isolation).

    PR

    ✅ Created: #752

    ⚠️ Overlaps #749 on batch-executor.ts/run-orchestrator.ts — merge sequentially, not in parallel.

  6. admarble commented on Jun 28, 2026

    @admarble
    ContributorAuthor

    /qa Review for Issue #748

    Verdict: READY_FOR_MERGE ✅

    Focused, well-scoped bug fix for the --chain up-front-provisioning timing bug. All 3 ACs MET, CI green (5/5), quality checks clean. One documentation defect found during adversarial re-read and fixed in-PR (commit 29bf48c).

    AC Coverage

    AC Source Description Status Evidence
    AC-1 Original Fresh --chain run: successor branch contains predecessor's committed work ✅ MET executeSequential rebases each successor (i>0) onto predecessor's local branch before it runs (run-orchestrator.ts:976-998); proven by integration test
    AC-2 Original Real-git test asserts git merge-base --is-ancestor <pred-exec-commit> <succ-HEAD> on a fresh run, no mock of rebase step ✅ MET chain-rebase.integration.test.ts:43,98,107 — real git, asserts false pre-rebase (bug repro) + true post-rebase; zero mocks
    AC-3 Original bin/cli.ts --chain help text accurate ✅ MET Updated to "each successor is rebased onto the previous issue's committed work before it runs" (bin/cli.ts:291)

    Coverage: 3/3 ACs fully met.

    Quality Plan Verification

    N/A — spec had no Feature Quality Planning section (bug fix, root cause pinned; no derived ACs).

    CI Status (PR #752, commit 29bf48c)

    Check State Impact
    typecheck SUCCESS ✅ MET
    build (22.x) SUCCESS ✅ MET
    node-floor-guard SUCCESS ✅ MET
    validate-skills SUCCESS ✅ MET
    validate-plugin SUCCESS ✅ MET

    CI Summary: 5 passed, 0 pending, 0 failed.

    Quality Metrics

    Metric Value Status
    Type issues (any/as any/@ts-ignore) 0 ✅ OK
    Deleted tests 0 ✅ OK
    Files changed 6 ✅ OK
    Lines +391 / −26 -
    Security patterns 0 critical/0 warn ✅ OK

    Test Coverage Analysis

    Changed File Tier Has Tests?
    src/lib/workflow/worktree-manager.ts Standard ✅ chain-rebase.integration.test.ts (real-git rebaseOntoLocalBranch) + checkpoint.integration.test.ts
    src/lib/workflow/run-orchestrator.ts Standard ✅ run-orchestrator.test.ts (#748 wiring: rebases each successor onto predecessor's local branch; not rebased when chain off)
    bin/cli.ts Optional help-text string — verified via source grep + CI typecheck

    Coverage: All changed source files covered. No critical-path (auth/payment/etc.) changes.

    Code Review

    Strengths:

    • Correct ordering: rebase fires at the top of iteration i, after predecessor i-1 has executed + committed (the loop breaks on predecessor failure, so a reached successor always has a committed predecessor). This is exactly what makes the chain contract hold.
    • Targets the local feature/<predecessor> branch (not origin/main) and is independent of --stacked — precisely the issue's Option 2.
    • Good de-duplication: extracted rebaseOntoLocalBranch is reused by the pre-existing re-run rebase path in ensureWorktree, removing duplicated conflict/abort logic.
    • Conflict handling aborts + warns loudly ("Chain link broken…") rather than silently greening a broken link — matches spec open-question docs: Add pre-release checklist #2 resolution.
    • spawnSync array form (no shell:true) — no injection surface for the branch-name arg.

    Issues (fixed in-PR):

    Suggestions (non-blocking, no action required):

    • LocalRebaseResult.performed is always true and unused by callers (mirrors RebaseResult shape) — harmless.
    • On a re-run, the successor may be rebased twice (once in ensureWorktreesChain, once in executeSequential) — idempotent no-op, acceptable.

    Call-Site Review

    New exported function: rebaseOntoLocalBranch — 2 non-test call sites:

    Call Site Loop? Condition AC Match
    worktree-manager.ts:603 (re-run path) No if chainMode && baseBranch ✅ preserves existing re-run rebase behavior
    run-orchestrator.ts:982 (chain successor) Yes if options.chain && i > 0 ✅ Matches AC-1 — runs for every successor (AC says "each branches from previous"), correctly unguarded beyond i>0

    Unlike the #295 precedent (where rebaseBeforePR should fire only for the last chain link), AC-1 here genuinely wants every successor rebased — so the unconditional-in-loop call (modulo i>0) is correct, not a missing guard. Function is used (not dead).

    Execution Evidence

    bin/cli.ts (CLI) changed, but the change is a static help-text string (Risk: None). Runtime run --help could not render in this worktree (Node 20.17 < 22.12 engine floor #734 exits early) — Waived; verified via source grep + green CI typecheck/build. scripts/ not touched, so /verify not required.

    Risk Assessment

    • Likely failure mode: A predecessor whose worktree has uncommitted changes at successor-rebase time would make git rebase fail (not a conflict) → caught as success:false, conflict:false → loud "Chain link broken" warning, successor proceeds on its existing base. Loud, not silent — acceptable.
    • Not tested: The dirty-worktree non-conflict failure branch isn't unit-tested (only success + merge-conflict are). Low risk — it's a warning path, behavior is graceful, and ensureWorktreesChain already guards dirty re-run worktrees upstream.
    • Sibling sites considered (cross-file, §5): None — rebaseBeforePR (origin/main, PR-time) and ensureWorktreesChain (up-front provisioning, the root cause now compensated) are distinct concerns, not siblings with the same root cause.
    • Sibling-line audit (intra-file, §4 Q5): The adjacent --stacked predecessorBranch block computes a PR base, not an execution-time rebase — different purpose, no shared root cause. Single logical fix site.

    Adversarial Re-Read

    Findings: Walked the 5 checks. (1) The integration test operationalizes the issue body's verbatim repro (merge-base(#125,#126) ancestry) — predecessor commits, successor rebased, ancestry asserted. (2) The "evidence" is honest: it asserts the pre-fix BUG state (is-ancestor == false) and the post-fix validation (== true), not a repro masquerading as validation. (3) Process state inspected — the uncommitted package-lock.json is pre-existing npm libc-field drift, unrelated and correctly left out of the PR; branch is 4 behind main (below threshold 5, MERGEABLE). (4) Sibling sites cited above. (5) No Non-Goals expanded — fix stayed on Option 2, did not drift into Option 1 (lazy provisioning). The single doc-orphan gap surfaced was fixed in-PR.

    Status: Clean

    CHANGELOG Verification

    Check Status
    CHANGELOG.md exists ✅
    User-facing change (fix:) ✅
    [Unreleased] entry for #748 ✅ Present, well-formed

    Documentation

    • CHANGELOG [Unreleased] entry added
    • --chain help text updated
    • N/A — internal workflow fix; no README/docs surface

    Next Steps

    1. Merge PR fix(#748): --chain successors branch from predecessor's committed work, not main #752. ⚠️ Sequence with fix(run): AC_MET_BUT_NOT_A_PLUS QA verdict misrouted into quality loop → fails with no PR (should break to PR) #749 (both touch run-orchestrator.ts/batch-executor.ts) — merge one, rebase the other.
    2. Optional follow-up (non-blocking): unit-test the dirty-worktree non-conflict rebase-failure branch.
  7. added
    ready-for-review
    on Jun 28, 2026
  8. admarble commented on Jun 28, 2026

    @admarble
    ContributorAuthor

    QA Review for Issue #748 (PR #752)

    Verdict: READY_FOR_MERGE ✅

    --chain Option 2 fix: executeSequential now re-rebases each chain successor's worktree onto its predecessor's local committed tip just before the successor runs, via an extracted rebaseOntoLocalBranch helper (reused by the re-run path). All 3 ACs met.

    AC Coverage

    AC Description Status Evidence
    AC-1 Fresh --chain run: successor branch contains predecessor's committed work ✅ MET run-orchestrator.ts:972-998 rebases successor onto local predecessor branch at top of sequential loop iteration i (after predecessor i-1 has executed/committed). Verified by integration + wiring tests.
    AC-2 Real-git test asserts merge-base --is-ancestor <pred-exec-commit> <succ-HEAD> on a fresh run, no mock of rebase step ✅ MET chain-rebase.integration.test.ts — real git, asserts pre-fix BUG state (isAncestor === false) → fix → isAncestor === true; plus conflict-abort and carry-forward cases.
    AC-3 bin/cli.ts --chain help text accurate ✅ MET Updated to "each successor is rebased onto the previous issue's committed work before it runs".

    Coverage: 3/3 ACs fully met.

    Quality Metrics

    Metric Value Status
    Type issues (any) 0 OK
    Deleted tests 0 OK
    Files changed 6 OK
    Lines +391 / −26 -

    CI Status

    All 5 checks pass: build (22.x), node-floor-guard, typecheck, validate-plugin, validate-skills. Mergeable: MERGEABLE.

    Tests

    Targeted run green locally: chain-rebase.integration.test.ts + run-orchestrator.test.ts → 25/25 pass.

    Code Review

    Strengths:

    • Clean helper extraction (rebaseOntoLocalBranch) consolidates conflict/abort logic; the pre-existing re-run path now reuses it (DRY, removes duplicated CONFLICT-detection block).
    • Rebase placement is correct: top of sequential iteration i, so predecessor i-1 has already committed. Targets the local predecessor branch, not origin/main — exactly the issue's root cause.
    • Independent of --stacked (the PR-targeting half stays separate, as designed).
    • Conflict path aborts to restore branch state and warns loudly rather than silently greening a broken link.
    • Tests directly answer the issue's "why tests didn't catch it": integration test asserts the pre-fix BUG state, wiring tests assert the actual call args (not tautological).

    Notes (non-blocking):

    • The integration test reproduces the up-front-provisioning shape with raw worktrees rather than driving ensureWorktreesChain end-to-end (justified: that path installs deps + mutates process cwd). The ensureWorktreesChain → executeSequential seam is covered via the wiring test's worktreeMap branch values rather than a true E2E run — acceptable, minor residual gap.
    • On rebase conflict the successor continues building on its un-rebased base (with warning) rather than breaking the chain. Reasonable design choice; documented in the warning text.

    Risk Assessment

    • Likely failure mode: Predecessor that produces no commit → rebase onto predecessor branch is a no-op onto base (no regression). Conflict → warned + continues on old base.
    • Not tested: No full E2E through ensureWorktreesChain; predecessor-with-zero-commits case not explicitly tested.
    • Sibling sites (cross-file): none — the helper is now the single rebase-onto-local-branch path, reused by the re-run path in ensureWorktree.
    • Sibling-line audit: The adjacent --stacked block (worktreeMap.get(i-1).branch) is the complementary PR-base half, not a sibling of this root cause — correct as-is.

    Adversarial Re-Read

    Findings: Verified the rebase fires after predecessor commit (sequential loop + break-on-failure means predecessor succeeded when successor is reached); confirmed local-branch target (not origin); confirmed conflict-abort restores HEAD + clean tree (integration test asserts both); help text and CHANGELOG match actual behavior; JSDoc adjacency for rebaseBeforePR correctly restored by the follow-up commit. ⚠️ Process-state note: the worktree has an uncommitted package-lock.json deletion (−42 lines) not part of this PR's origin/main...HEAD diff — ensure it is not accidentally committed into this branch before merge.

    Status: Clean

    Documentation

    Next Steps

    1. Merge-order: PR notes overlap with fix(run): AC_MET_BUT_NOT_A_PLUS QA verdict misrouted into quality loop → fails with no PR (should break to PR) #749 (and fix(#748): --chain successors branch from predecessor's committed work, not main #752 touches run-orchestrator.ts/worktree-manager.ts) — merge sequentially, not in parallel.
    2. Discard the stray uncommitted package-lock.json deletion in the worktree before merge.
    3. Branch is 4 commits behind origin/main (under threshold) — optional rebase before merge.
  9. added 5 commits that reference this issue on Jul 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugclimulti-agentplannedready-for-review

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions