Skip to content

ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380

Closed

Description

@admarble

Epic: graph-2026-10-freeze Tier: judgment Execution: sequant_run

Summary

When a PR's worktree is more than 5 commits behind base and has no uncommitted or unpushed work, ensureWorktree "recreates fresh". In doing so it deletes the local branch and rebuilds it from base, ignoring origin/<branch>. A qa re-run then reviews base with none of the PR's commits.

Observed

admarble/thenewwayai #330 (PR #355), 2026-10-06, sequant 2.19.0 over MCP. On a qa re-run the log printed Worktree is 12 commits behind master — recreating fresh. QA then recorded "commit": null and filesModified: []. The worktree had none of the PR's commits; git log origin/master..HEAD was empty. The QA agent happened to notice and ran git show <head>:<file> itself, but nothing in sequant guards against this.

Mechanism (main @ 68446b02, src/lib/workflow/worktree-manager.ts)

  1. ensureWorktree (~L842/901): behind by more than the threshold, no uncommitted changes, !hasUnpushedCommits, so it takes the "Safe to recreate" branch. Commits already pushed to the PR count as safe.
  2. removeStaleWorktree (~L355/378) runs git branch -D <branch>.
  3. Creation checks the branch with show-ref --verify refs/heads/<branch> (~L992), which is local only. The branch was just deleted, so it falls through to git worktree add <path> -b <branch> <baseRef> (~L1055): a new branch from base. origin/<branch> is never consulted.

Impact

  • QA reviews the wrong tree, and its verdict refers to code that isn't the PR.
  • Any later commit on the recreated branch diverges from origin/<branch>. Pushing it is non-fast-forward, or a force-push overwrites the PR.
  • It's latent in any repo where a PR's branch falls more than 5 commits behind base before a qa-only re-run, which is common on a busy default branch.

Suggested fix

When origin/<branch> exists, recreate from it (worktree add -B <branch> <path> origin/<branch>) and then merge or rebase base in. Never -b <branch> <base> while a remote branch exists. A cheap guard: after any recreate, assert that git rev-list --count <base>..HEAD is greater than 0 when the issue has an open PR, and refuse or warn otherwise.

Reported from a graph-run session; mechanism traced by a sequant-repo session and re-checked against main.

Acceptance Criteria

  • AC-1: When ensureWorktree recreates a worktree and origin/<branch> exists, the recreated branch starts from origin/<branch>, so HEAD contains every commit origin/<branch> has. Evidence: a test with a temp repo whose PR branch is pushed and more than 5 commits behind base, asserting git rev-list --count HEAD..origin/<branch> is 0 after recreate, mutation-verified by restoring the -b <branch> <baseRef> path.
  • AC-2: When origin/<branch> does not exist, recreate behaves as today: a local-only branch whose HEAD is on base is recreated from the base, and a local-only branch with commits of its own is kept by the existing unpushed-commits check, not destroyed. (Clarified 2026-10-10: the spec's Open Question 1 thought ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380's guard changed the second case; a test against main shows main already keeps it.) Evidence: a test with an unpushed local-only branch whose HEAD is on base, and a test that a local-only branch with its own commits is kept.
  • AC-3: A recreate that would leave HEAD with none of an existing origin/<branch>'s commits does not proceed silently: it refuses, or prints a warning in the same style as the existing "commits behind" line (worktree-manager.ts:339) and keeps the old worktree. Evidence: a test that forces the case and asserts the warning or refusal text.
  • AC-4: The base the recreate path uses is the run's resolved base (ResolvedRun.baseBranch), or the spec records why it differs (graph doc OQ-2). Evidence: the spec comment's answer to OQ-2, and a test if the value is threaded through.

Prior fixes / producers

May touch

src/lib/workflow/worktree-manager.ts (ensureWorktree, removeStaleWorktree, worktree creation), its tests. Serialize with #1386.

Non-Goals

  • Changing the 5-commits-behind stale threshold.
  • Rebasing or merging base into the recreated branch automatically (the suggested fix mentions it; out of scope unless the spec shows a test needs it).
  • Any edit under plugin/, .claude/skills/ or templates/skills/ (plugin freeze, I-1 of the graph doc).

Activity

  1. added
    graph-2026-10-freeze
    on Oct 9, 2026
  2. added a commit that references this issue on Oct 10, 2026
  3. admarble commented on Oct 10, 2026

    @admarble
    ContributorAuthor

    Runner context for the phase agents (graph-2026-10-freeze, wave 2). This applies to spec, exec and qa by name.

    #1386 has merged (9c017df6, PR #1394), the other change to worktree-manager.ts (graph doc D-5: serialized, disjoint functions). createPR now takes the run's resolved base through resolvePrBase. Line numbers in this issue's body predate that merge: find ensureWorktree (now about L866), removeStaleWorktree (about L355) and the worktree add … -b <branch> <baseRef> call (about L1079) by name.

    Spec must answer OQ-2 before exec (graph doc docs/internal/graph-2026-10-freeze/PROJECT-DISCUSSION.md, verbatim):

    OQ-2: Is the baseRef that ensureWorktree's recreate path uses (callers at worktree-manager.ts:1190, :1242) the same value as ResolvedRun.baseBranch? Resolved by #1380's spec, before exec.

    Answer it from the code as it is on main now: trace ResolvedRun.baseBranch (run-orchestrator.ts) to ensureWorktrees and ensureWorktreesChain and into computeWorktreeBaseRef. Put the answer in the spec comment; AC-4 cites it. If the values can differ, say where. Thread the resolved base through rather than adding a second resolver (D-2).

    • No full npm test in exec or qa. Up to three phases run in parallel in this wave, and a full-suite run (10–13 min) under that load crosses the 30-minute phase wall and kills the phase. Run the test files you touch or add plus the stack's affected-tests command, in the foreground, with timeout, after a WIP commit. CI's required test check runs the full suite on the PR, and the runner waits for it before any merge.
    • Plugin freeze (graph doc I-1): the diff must not touch plugin/, .claude/skills/ or templates/skills/.
    • CHANGELOG.md [Unreleased]: add your line. Conflicts with sibling PRs are expected, and the runner resolves them.
    • Gate-test ACs need the mutation record in the PR body (CLAUDE.md, Testing). failedTest starts with the test file path.
  4. admarble commented on Oct 10, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (4 ACs, 2 directories)

    AC Quality Check

    Each AC is one line and has an Evidence: clause. None of them are vacuous on main (afc37bd0), because the tests they name don't exist yet. Two tensions:

    • AC-1: the mutation alone does not prove anything if the AC-3 guard also catches it. A guard that keeps the old worktree leaves HEAD..origin/<branch> at 0, so the AC-1 test passes under the mutation. Fix: the AC-1 test must also assert that a recreate happened: existed: false and the "recreating fresh" line. Compute the start ref once and use that same value in the guard and in worktree add (see the plan). Then the mutation fails the AC-1 test and nothing else.
    • AC-2 vs the AC-3 guard: see Open Question 1.

    Scope Assessment

    Non-Goals: present. They cover the threshold, the auto-merge of base, and the plugin freeze.

    Metric Value Status
    Feature count 1 ✅
    AC items 4 ✅
    Directory spread 2 (src/lib/workflow/, docs/adr/) + CHANGELOG ✅

    Verdict: ✅ SCOPE_OK


    OQ-2 answer (graph doc), from main @ afc37bd0

    The value is the same. The ref derived from it can differ.

    1. ResolvedRun.baseBranch (run-orchestrator.ts:721) is never empty. It resolves as init.baseBranch ?? --base ?? settings.run.defaultBase ?? detectDefaultBranch().
    2. Non-chain: ensureWorktrees(…, baseBranch, …) (run-orchestrator.ts:1309) passes it unchanged into ensureWorktree (worktree-manager.ts:1214). The recreate path then uses it in two different ways:
      • Stale check: detectedBase = baseBranch (:890). checkWorktreeFreshness fetches it and counts commits behind origin/<base> (countCommitsBehind, :244).
      • Creation: baseRef = computeWorktreeBaseRef(baseBranch, detectDefaultBranch()) (:1034). This returns origin/<default> for the default branch and origin/x for origin/x. For any other bare name (--base develop, run.defaultBase: "develop") it returns the local branch develop.
      • Where they differ: with a non-default bare base, the stale count measures against origin/develop, but the recreate cuts from local develop, which can lag. Also, when the base is origin/x, checkWorktreeFreshness runs git fetch origin origin/x. That fetch fails silently, so the count uses an un-refreshed ref.
    3. Chain: ensureWorktreesChain (run-orchestrator.ts:1301) passes chainResume?.resumeBase ?? baseBranch for the first link, then each link's predecessor branch. This is deliberately not ResolvedRun.baseBranch. A predecessor that hasn't been pushed has no origin/<pred>, so countCommitsBehind returns null and links 2 and later are never recreated.

    Consequence for #1380 (AC-4): no new resolver is needed (D-2). The recreate path already gets ResolvedRun.baseBranch unchanged. After the fix, when origin/<branch> exists the recreate starts from it, so the base only feeds two things: the stale count and the recorded branch.<b>.sequantBaseRef. The recorded ref must stay computeWorktreeBaseRef(baseBranch, …), not origin/<branch>. Two readers depend on it: the exec guard (phase-executor.ts:884/922) and rebaseBeforePR. Note that git branch -D in removeStaleWorktree deletes that config section, and the record at :1092 rewrites it. The local-vs-origin divergence for non-default bases belongs to the #1234/#1386 class and is not fixed here. See Open Question 3.


    Acceptance Criteria

    AC-1: Recreate starts from origin/<branch> when it exists

    Verification: Integration Test (temp bare remote + clone, same harness as #1234 in worktree-manager.test.ts:782)
    Scenario: Given feature branch F is pushed with -u, its worktree exists, and the remote base is ≥6 commits ahead and fetched → When ensureWorktree runs → Then the output contains "recreating fresh", existed: false, git rev-list --count HEAD..origin/F = 0, and F's file is present.
    Assumptions: The branch was pushed with push -u (createPR, :2340), so @{u} = origin/F and hasUnpushedCommits is false. This is the observed path.

    AC-2: No origin/<branch> means recreate from base, as today

    Verification: Integration Test
    Scenario: Given a local-only branch with no upstream and no commits of its own, ≥6 behind base → When ensureWorktree runs → Then it recreates, and HEAD = origin/main.
    Assumptions: See Open Question 1 for a local-only branch that has commits.

    AC-3: A recreate that would drop origin/<branch>'s commits does not proceed

    Verification: Integration Test
    Scenario: Given F is pushed and its worktree is clean and ≥6 behind. Then refs/remotes/origin/F is deleted and origin's URL is pointed at a missing path, so the branch fetch fails (an offline blip: sequant can't see the remote branch) → When ensureWorktree runs → Then it prints a yellow ! Worktree is N commits behind <base> but … — keeping existing worktree line, returns existed: true, and HEAD is unchanged.
    Assumptions: countCommitsBehind uses the already-fetched local origin/main ref, so the worktree still reads as stale. @{u} errors, so hasUnpushedCommits is false and the code reaches the recreate path.

    AC-4: The base is ResolvedRun.baseBranch; the recorded base ref is unchanged

    Verification: Integration Test, plus the OQ-2 answer above
    Scenario: Given the AC-1 setup → When the recreate runs → Then git config branch.F.sequantBaseRef = origin/main (the base), not origin/F.


    Implementation Plan

    Phase 1: Start ref + guard (src/lib/workflow/worktree-manager.ts, ensureWorktree recreate branch ~:922)

    1. Before removeStaleWorktree, run git fetch origin <branch> (stdio pipe, 30 s timeout, failure tolerated). Then resolve startRef once: origin/<branch> if rev-parse --verify --quiet refs/remotes/origin/<branch> succeeds, else computeWorktreeBaseRef(baseBranch, detectDefaultBranch()). A small exported helper is fine (e.g. resolveRecreateStartRef, @internal).
    2. Guard: if git merge-base --is-ancestor <existing HEAD> <startRef> fails, print the yellow warning (same style as :902/:914) plus an ℹ️ Keeping existing worktree line, and do not remove the worktree. This guard is the AC-3 check.
    3. Otherwise remove it as today, and carry startRef to the creation step (a local variable, e.g. recreateFrom).

    Phase 2: Creation (~:1062-1082)

    1. If recreateFrom is origin/<branch>, create the worktree with git worktree add -B <branch> <path> origin/<branch>. Otherwise keep the existing -b <branch> <baseRef> and branchExists paths unchanged. Never use -b <branch> <baseRef> while recreateFrom names a remote branch.
    2. Keep recordWorktreeBaseRef(worktreePath, branch, baseRef) recording baseRef (AC-4). Do not auto-merge base in (Non-Goal). The pre-PR rebaseBeforePR already merges base into pushed branches (bug(qa): the qa phase rebases an already-pushed branch onto main, forcing a force-push to land it #1069).

    Phase 3: Tests + docs

    1. Add a describe("#1380 …") block in worktree-manager.test.ts that reuses the bug(exec): sequant run worktrees never record sequantBase, so the zero-diff/uncommitted guard compares against origin/main and a --base ahead of main disables it #1234 temp-repo/tsx script harness. Cover AC-1, AC-2, AC-3 and AC-4. Advance base with a second clone that pushes 6 commits, then fetch. Run only this file plus affected tests, foreground, with timeout (runner context: no full npm test).
    2. Add an ADR at docs/adr/0011-… (see Design Review), a CHANGELOG [Unreleased] line, and mutation records for AC-1 (restore -b <branch> <baseRef> in the recreate path), AC-3 (delete the guard) and AC-4 (record startRef as the base). Each failedTest starts with src/lib/workflow/worktree-manager.test.ts.

    Design Review

    1. Where does this logic belong? In ensureWorktree's recreate branch and its creation step. removeStaleWorktree stays a dumb remover. run-compat.ts re-exports it, so don't change its signature.
    2. What's the simplest correct approach? Resolve startRef once from origin/<branch> or the base, guard on containment, then create with -B … origin/<branch>. Rejected alternatives: (a) don't delete the local branch when it's pushed: this reuses a local ref that can lag origin/<branch> (e.g. a runner's merge-main pushed from elsewhere). (b) skip the recreate whenever origin/<branch> exists: simpler, but it fails AC-1 as written and misses remote-only commits. Because the plan picks between designs, the exec PR must include an ADR (docs/adr/0011-*.md, shape per docs/adr/README.md).
    3. What existing pattern does this follow, and how often has it been re-patched? It follows the "stale-and-clean, recreate" pattern from fix: pre-flight state guard and worktree lifecycle management #305 (518e6939, 46580a05), split out in refactor(run): split 3,459-line monolith into focused modules #318 (14b81192). git log -S removeStaleWorktree / -S '@{u}..HEAD' show no fix since then: zero prior fix issues, so this is under the stop threshold. The base-ref class (bug(exec): sequant run worktrees never record sequantBase, so the zero-diff/uncommitted guard compares against origin/main and a --base ahead of main disables it #1234, fix(run): --base creates the worktree from the branch but opens the PR against the repo default branch #1386) is adjacent but separate. fix(run): --base creates the worktree from the branch but opens the PR against the repo default branch #1386 confirmed the base flow, and the issue records ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380 as deliberately local, with the class tracked in fix(run): --base creates the worktree from the branch but opens the PR against the repo default branch #1386.
    4. What would a senior reviewer challenge?
      • "Why recreate at all if the result has the same stale commit?" Because it picks up commits on origin/<branch> that the local branch lacks, and node_modules reinstall. Base gets merged in before the PR anyway.
      • "Why the network fetch?" checkWorktreeFreshness already fetches base. One more fetch with a 30 s cap is consistent with that.
    5. Producers and consumers.
      • Branch-ref producers: removeStaleWorktree (branch -D), worktree add -b (:1079), the new -B path, createPR push -u (:2340), and rebaseBeforePR merge/rebase.
      • Base-ref producers: recordWorktreeBaseRef at :916 (reuse) and :1092 (create). Both use computeWorktreeBaseRef, so there is one resolver.
      • Consumers: readRecordedBaseRef (exec guard phase-executor.ts:922, rebaseBeforePR), ensureWorktrees / ensureWorktreesChain (run-orchestrator.ts:1301/1309), run-compat.ts re-exports, and the MCP qa re-run, which is the observed path.

    Feature Quality Planning

    All standard checks pass. Notable items:


    Open Questions

    1. The AC-3 guard also stops today's destruction of a local-only branch that has commits of its own (the sibling site above). AC-2's literal "behaves as today" covers only a branch with no commits of its own. — Recommendation: keep the guard general (one containment check) and amend AC-2 to "a local-only branch whose HEAD is on base". Impact if wrong: the narrow alternative (guard only when a remote branch is known) leaves the data loss and doesn't catch the offline case in AC-3.
    2. The fresh-machine case has the same -b path: no local branch, but origin/<branch> exists. — Recommendation: out of scope. File a follow-up. Changing first-creation semantics affects abandoned remote branches.
    3. A non-default bare base is counted against origin/x but cut from local x (OQ-2 above). — Recommendation: follow-up in the bug(exec): sequant run worktrees never record sequantBase, so the zero-diff/uncommitted guard compares against origin/main and a --base ahead of main disables it #1234/fix(run): --base creates the worktree from the branch but opens the PR against the repo default branch #1386 class. Not fixed here.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled
    Reasoning: This is a focused fix in one function. The tests are bespoke temp-repo integration scenarios in an existing harness, so testgen stubs add little. The graph runner drives exec and qa.


    Label Review

    Current: graph-2026-10-freeze
    Recommended: + bug, planned
    Reason: a destructive-path correctness bug.
    Quality Loop: won't auto-enable (SCOPE_OK).

  5. added
    planned
    bug
    on Oct 10, 2026
  6. admarble commented on Oct 10, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 4/4 met

    Gaps:

  7. added a commit that references this issue on Oct 10, 2026
  8. admarble commented on Oct 10, 2026

    @admarble
    ContributorAuthor

    Runner note (2026-10-10): AC-2 clarified, no behavior change. The spec's Open Question 1, repeated in QA's pause_for_human finding, said #1380's containment guard newly keeps a local-only branch that has commits of its own. It doesn't. That branch is already kept on main by the existing hasUnpushedCommits check ("Keeping existing worktree with WIP commits"). A new test (1380 AC-2 keeps a local-only branch that has commits of its own) passes against main's worktree-manager.ts and with the guard disabled. AC-2's text now says so; the owner's earlier amendment rested on the same premise and is superseded by this clarification.

  9. added a commit that references this issue on Oct 10, 2026
  10. added 3 commits that reference this issue on Oct 10, 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

    buggraph-2026-10-freezeplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions