Skip to content

fix(worktree): first creation on a fresh machine ignores origin/<branch>, and a recreated PR worktree is recreated again on every run (#1380 follow-up) #1405

Closed

Description

@admarble

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

Follow-up from #1380 (PR #1403; spec Open Question 2 and a QA document finding).

Problem

#1380 makes a stale-worktree recreate start from origin/<branch>. Two neighbouring paths still lose or repeat work:

  1. Fresh machine, first creation. With no local branch but an existing origin/<branch> (a PR opened from another machine, or a cloud session), ensureWorktree still checks the branch with the local-only show-ref refs/heads/<branch> (worktree-manager.ts:1078). It falls through to git worktree add <path> -b <branch> <baseRef>, a new branch cut from the base. A qa re-run there reviews the base, and a later push diverges from the PR. That's ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380's bug, on the first-creation path.
  2. A recreated worktree stays stale. Recreating from origin/<branch> keeps the PR's commits, but the branch is still more than 5 commits behind the base. So every later ensureWorktree call recreates it again (delete, re-add, dependency reinstall) until the pre-PR rebase or a merge of the base lands.

Design constraint (graph doc §6, OQ-2)

AC-3's "abandoned branch" check must not add a network call to every ensureWorktree. #1322's root cause was real git worktree list + gh calls per worktree, which made run time scale with load. The spec answers where the check runs (first-creation and recreate paths only) and whether a local git check is enough (for example, origin/<branch> already contained in origin/<base>).

Acceptance Criteria

  • AC-1: With no local <branch> and an existing origin/<branch>, ensureWorktree creates the worktree from origin/<branch> with upstream tracking, so HEAD contains every commit of origin/<branch>. Evidence: a temp-repo test in worktree-manager.test.ts (the ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380 harness), mutation-verified by restoring the -b <branch> <baseRef> path.
  • AC-2: A worktree recreated from origin/<branch> is not recreated again by the next ensureWorktree call when nothing changed on origin/<branch>. Either the base is merged in at recreate time, or the staleness check skips a branch whose HEAD equals origin/<branch>. Evidence: a test calling ensureWorktree twice, asserting the second call reuses the worktree.
  • AC-3: A remote branch already merged into the base is not resurrected as the new work's base, and the check adds no gh call on the reuse path. Evidence: a test covering a branch already merged into origin/<base>, plus a test asserting the reuse path makes no gh call.

Prior fixes / producers

May touch

src/lib/workflow/worktree-manager.ts (ensureWorktree, branch-existence check), its tests, CHANGELOG.md. Serialize before #1406 (graph doc D-5).

Non-Goals

Related: #1380, ADR-0013.

Activity

  1. added
    bug
    graph-2026-10-freeze-b
    on Oct 10, 2026
  2. admarble commented on Oct 16, 2026

    @admarble
    ContributorAuthor

    Runner context (graph-2026-10-freeze-b, tracker #1452), for the exec and qa phases:

  3. admarble commented on Oct 16, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (3 ACs, 2 directories: src/lib/workflow/, docs/adr/)

    AC Quality Check

    All 3 ACs parse with declared Evidence:. Lint is clean. Checked against base:

    • AC-1 and AC-2 fail on main today. First creation cuts -b <branch> origin/main. A second ensureWorktree after a ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380 recreate recreates again. Neither evidence passes vacuously.
    • ⚠️ AC-3's second evidence passes vacuously on main. The reuse path makes no gh call today. Keep it as a regression guard, and mutation-verify it by injecting a gh spawn on the reuse path.
    • ⚠️ AC-3 "already merged into the base" does not say which merge strategy. This repo squash-merges, and a squash merge never makes origin/<branch> an ancestor of origin/<base>. A test that uses only git merge would pass a check that misses every real merge on this repo. Recommend amending the AC-3 line to "merged (merge commit or squash) into the base", and testing both.

    Scope Assessment

    Non-Goals: present (threshold value; PRs closed unmerged; computeWorktreeBaseRef/countCommitsBehind → #1406; plugin freeze).

    Metric Value Status
    Feature count 1 (start ref of a worktree) ✅
    AC items 3 ✅
    Directory spread 2 ✅

    Verdict: ✅ SCOPE_OK

    In-flight: no open PR touches worktree-manager.ts. The 5 local worktrees with diffs in it (#1199, #1217, #1222, #1223, #1247) are all for closed issues. A feature/1405-… worktree already exists at 8de858a13 with no commits; exec may reuse it, but it is behind main. #1406 waits for this to merge (D-5).

    Acceptance Criteria

    AC-1: First creation starts from origin/<branch>

    Verification: Integration Test (temp-repo, #1380 harness)
    Scenario: Given clone A pushed feature/20-… with a commit, and clone B has no local branch → When B calls ensureWorktree(20) → Then HEAD..origin/<branch> is empty, the PR commit is in the log, and branch.<b>.remote/merge track origin.
    Assumptions: sequantBaseRef still records the run's base, not origin/<branch> (same as #1380 AC-4).

    AC-2: A recreated PR worktree is not recreated again

    Verification: Integration Test
    Scenario: Given a pushed branch and main advanced by 6 → When ensure runs twice → Then the 1st call prints recreating fresh. The 2nd call returns existed: true, does not print recreating fresh, and has the same path and HEAD.
    Assumptions: "Nothing changed on origin/<branch>" means HEAD == origin/<branch> after the fetch.

    AC-3: A merged remote branch is not resurrected; no gh call on reuse

    Verification: Integration Test
    Scenario: (a) Given origin/<branch> was squash-merged into origin/main, with no local branch → When ensure runs → Then HEAD == origin/main. (b) The same with a merge-commit merge. (c) Given a stale local refs/remotes/origin/<branch> whose remote branch was deleted after the merge → Then the start is origin/main. (d) Given a fake gh first on PATH that writes a marker file → When the reuse path runs → Then no marker file exists.
    Assumptions: Answer to OQ-2 below: the check is local git only, so no gh call is needed.

    Implementation Plan

    Phase 1: One start-ref resolver (the class fix)

    1. Generalize resolveRecreateStartRef (worktree-manager.ts:844) into resolveBranchStartRef(cwd, branch, baseRef). It returns origin/<branch> only when all three hold:

      • (i) git fetch origin <branch> did not report couldn't find remote ref. A branch that was deleted after its merge leaves a stale tracking ref, so ignore that ref. Any other fetch failure (offline) still falls back to the ref that is present, as in ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380.
      • (ii) the ref exists.
      • (iii) it is not merged into baseRef. Merged means merge-base --is-ancestor origin/<branch> <baseRef>, or git merge-tree --write-tree <baseRef> origin/<branch> gives a tree equal to <baseRef>^{tree}. The second test catches squash merges (git ≥ 2.38; if merge-tree errors, use only the ancestor result).

      Otherwise it returns baseRef.

    2. Recreate path (:959): call the new resolver. The containment guard is unchanged.

    Phase 2: First-creation path (AC-1, AC-3)

    1. At :1076, when refs/heads/<branch> is absent and !chainMode, call resolveBranchStartRef(gitRoot, branch, baseRef). If it returns origin/<branch>, use the existing recreateFrom branch (worktree add -B <branch> <path> origin/<branch>, :1130). -B from a remote-tracking ref sets upstream through branch.autoSetupMerge, and the ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380 AC-1 test already asserts that. Chain mode keeps cutting from the predecessor.

    Phase 3: Stop the repeat recreate (AC-2)

    1. In the stale branch (:955), after the start ref resolves: if startRef === origin/<branch> and rev-parse HEAD == rev-parse startRef, keep the worktree with a gray verbose note ("already at origin/; recreate would not change it"). The pre-PR rebaseBeforePR (bug(qa): the qa phase rebases an already-pushed branch onto main, forcing a force-push to land it #1069) still brings in the base.

    Phase 4: Tests, ADR, CHANGELOG

    1. Add a #1405 describe block next to the ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380 one. Reuse ensure/advanceMain, and add a second clone and a PATH gh shim. Run only this file, under timeout 600, after a WIP commit (runner comment).
    2. Add ADR-0014 (next number). It records the AC-2 choice and supersedes ADR-0013's two "Not changed" and "still behind" consequences. Add a CHANGELOG Fixed entry.

    Design Review

    1. Where does this logic belong? ensureWorktree plus the resolver it already owns. No new module.
    2. What's the simplest correct approach? For AC-2, choose the HEAD == origin/<branch> skip over merging the base at recreate time. A merge at provisioning time writes an unasked-for commit that must be pushed, adds conflict handling to provisioning, and duplicates rebaseBeforePR. Rejected: removing branch -D (ADR-0013 Option B).
    3. What existing pattern does this follow, and how often has it been re-patched? Pattern: ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380's start-ref resolver plus the containment guard. Prior fixes on this path: 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 (PR fix(#1234): sequant run worktrees record their exact base ref; the exec guard and pre-PR rebase read it #1242) and ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1380 (PR feat(#1380): ensureWorktree "recreating fresh" rebuilds a PR branch from base and drops its commits; qa re-run reviews the wrong tree #1403). That is ≥2, so stop: fix the class. The class is that a worktree's starting commit is resolved separately on each path. Step 1 makes the resolver the only one, used by both paths. Not a divergence.
    4. What would a senior reviewer challenge?
    5. Every producer and consumer of the artifact this changes (whole-repo grep). Producers of the starting commit: the first-creation path (:1147) and the recreate path (:1130), which collapse onto one resolver. countCommitsBehind has consumers in run-orchestrator.ts:1351 and checkWorktreeFreshness (run-compat.ts); fix(worktree): a non-default bare --base is cut from local <base> but counted against origin/<base> (#1380 follow-up, #1234/#1386 class) #1406 owns them and they are not touched here. recordWorktreeBaseRef is unchanged.

    OQ-2 answer: the check runs only on the first-creation and recreate paths, never on reuse. It is local git: one fetch origin <branch>, which the recreate path already does and which is new on first creation, plus a local merge-tree. It needs no gh.

    Feature Quality Planning

    Open Questions

    1. Amend AC-3 to name squash merges? Recommendation: yes, the owner edits the AC line. Impact if not: an ancestor-only check passes the AC and misses every merge on this repo.
    2. Chain mode on first creation: should origin/<branch> win over the chain predecessor? Recommendation: no; the predecessor keeps winning. Impact if wrong: a chained fresh-machine run cuts from the predecessor, as it does today.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled
    Reasoning: This is a bug fix in one file with integration-style temp-repo tests, so testgen is skipped. The tests need the #1380 harness, not stubs.

    Label Review

    Current: bug, graph-2026-10-freeze-b. Recommended: no change, plus planned.

  4. added
    planned
    on Oct 16, 2026
  5. admarble commented on Oct 16, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 3/3 met

    Gaps:

  6. added 2 commits that reference this issue on Oct 16, 2026
  7. added 2 commits that reference this issue on Oct 16, 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-freeze-bplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions