Skip to content

fix(run): a failed git worktree add must fail the issue, not run its phases in the main checkout (two CLIs race on .git/config) #1469

Closed

Description

@admarble

Tier: judgment Execution: sequant_run

Problem

When git worktree add exits non-zero, ensureWorktree logs "Failed to create worktree" and returns null (src/lib/workflow/worktree-manager.ts:1153-1158); ensureWorktrees drops the null and prints "N created, M reused" (:1296-1298); the issue's worktree is undefined in the orchestrator (run-orchestrator.ts:1896-1908); and phase-executor.ts:1636 falls back to cwd = process.cwd(). The issue's spec, exec and QA phases then run in the main checkout, on whatever branch is checked out there, while a half-created worktree and branch sit on disk.

Seen: 2026-10-15, accretion-audit repo, two sequant run CLIs started 3 s apart. The loser logged error: could not lock config file .git/config: File exists / error: unable to write upstream branch configuration then ❌ Failed to create worktree: Preparing worktree (new branch ...), and continued. The exec committed and pushed to the feature branch because the prompt named the worktree path; the exec guard then ran classifyExecChanges(main checkout) (phase-executor.ts:999), whose resolveBaseRef found no recorded base for main and compared origin/main..HEAD = 0, so the run failed with "exec produced no changes (no commits, no uncommitted work)" against a branch that had the work. Recovery was sequant run <n> --phases qa on the reused worktree.

Reproduced: in a throwaway repo, 40 concurrent git worktree add <path> -b <branch> origin/main lost the .git/config lock 11 times (exit 255, branch created, no directory, not in worktree list, no upstream config). Each worktree add -b writes branch.<name>.remote/merge into the shared .git/config, so two CLIs in one repo race whenever their provisioning overlaps.

Acceptance Criteria

  • AC-1: Under worktree isolation, an issue whose worktree could not be created fails before any phase runs, with the captured git stderr in the issue result's abortReason and the run log, and no phase for that issue has cwd equal to the main checkout; IssueExecutionContext carries an explicit worktreeRequired flag so that neither producer (executeOneIssue, executeBatch) can start such an issue. Evidence: npx vitest run src/lib/workflow/run-orchestrator.worktree-failure.test.ts → ≥ 2 passed, 0 failed (new file: a stubbed ensureWorktrees that omits one issue and records its stderr yields a failed issue result naming the stderr; executePhase is never called for it; the other issue runs; executeBatch fed the same context yields the same failed result); mutation-verified: deleting the worktreeRequired && !worktree guard in runIssueWithLogging makes src/lib/workflow/run-orchestrator.worktree-failure.test.ts > worktree provisioning > a missing worktree fails the issue before any phase fail.
  • AC-2: A could not lock config file failure from git worktree add is retried with short backoff, re-checking whether the branch now exists so the retry uses worktree add <path> <branch> instead of -b. Evidence: npx vitest run src/lib/workflow/worktree-manager.integration.test.ts -t "config.lock" → ≥ 2 passed, 0 failed (new file in the integration project, which has the 30 s timeout; real clone, a pre-created .git/config.lock released after the first attempt: the worktree is created on the retry; a lock never released ends in the AC-1 failure, not a hang).
  • AC-3: recordWorktreeBaseRef (phase-executor.ts:828) uses the same retry and reports, rather than swallows, a final failure. Evidence: npx vitest run src/lib/workflow/phase-executor.test.ts -t "recordWorktreeBaseRef" → ≥ 2 passed, 0 failed.
  • AC-4: Two concurrent runs in one repo both end with their worktrees created. Evidence: npx vitest run src/lib/workflow/worktree-manager.integration.test.ts -t "concurrent" → ≥ 1 passed, 0 failed (same new file; two child processes, each calling ensureWorktree for a different issue against one real clone and released together by a barrier, both exit 0 and both worktrees appear in git worktree list; an in-process Promise.all does not count, spawnSync serializes it).

Prior fixes / producers

May touch

src/lib/workflow/worktree-manager.ts (ensureWorktree, ensureWorktrees, ensureWorktreesChain), src/lib/workflow/run-orchestrator.ts (issue result when the worktree is missing), src/lib/workflow/phase-executor.ts (recordWorktreeBaseRef), their tests, the changelog entry.

Non-Goals

Activity

  1. added
    bug
    on Oct 16, 2026
  2. added a commit that references this issue on Oct 16, 2026
  3. admarble commented on Oct 17, 2026

    @admarble
    ContributorAuthor

    Runner context before launch (2026-10-17, main at aaff4e8). Line numbers in the body were taken at ad71b34 and have shifted; the anchors are unchanged:

    • ensureWorktree logs ❌ Failed to create worktree and returns null: src/lib/workflow/worktree-manager.ts:1270 (was :1153–1158).
    • ensureWorktrees prints Worktrees: N created, M reused and drops the null: worktree-manager.ts:1415–1419 (was :1296–1298).
    • Orchestrator passes worktree: worktreeInfo ? {...} : undefined: run-orchestrator.ts:1896–1910 (unchanged).
    • The fallback AC-1 names: const cwd = shouldUseWorktree ? worktreePath : process.cwd(); at phase-executor.ts:1643 (was :1636). "Restoring the worktree?.path fallback" in the mutation record means this expression.
    • recordWorktreeBaseRef: phase-executor.ts:831 (was :828). classifyExecChanges: :1006 (was :999).

    Prior-fix check re-run today: no earlier fix touches the lock race; #1405 (PR #1468, merged 2026-10-16) changed ensureWorktree's start-ref resolution in the same function, so read the current code, not the quoted lines. The outcome the ACs state stands: under isolation an issue never runs a phase outside its worktree, and a could not lock config file failure is retried. If the real owner of the fallback turns out to be the IssueExecutionContext.worktree contract rather than the executor, stop and surface rather than patch locally.

  4. admarble commented on Oct 17, 2026

    @admarble
    ContributorAuthor

    Complexity: Standard (4 ACs, 2 directories)

    ⛔ Spec halted: SPEC_DIVERGENCE on AC-1

    The runner comment says: "If the real owner of the fallback turns out to be the IssueExecutionContext.worktree contract rather than the executor, stop and surface rather than patch locally." That is the case here.

    • phase-executor.ts:1643 (const cwd = shouldUseWorktree ? worktreePath : process.cwd();) cannot tell the failure apart from correct behavior. worktreePath === undefined is also what it gets when isolation is off (worktreeIsolation: false), and spec runs in the main checkout by design (requiresWorktree: false). If the executor guarded this line, it would break both of those cases.
    • The ambiguity is in the contract. IssueExecutionContext.worktree? (types.ts:928, "when worktree isolation is enabled") uses undefined for two different states: isolation is off, and provisioning failed. Two places build that context from worktreeMap.get(n): run-orchestrator.ts:1906 (executeOneIssue) and batch-executor.ts:621 (executeBatch). Both pass the ambiguous undefined down.
    • AC-1's mutation record ("restoring the worktree?.path fallback", i.e. the phase-executor expression) names a site the correct fix does not change. QA would have nothing to restore, so §6i could not resolve the record as worded.

    Proposed AC-1 text (owner edits the AC line, then re-runs):

    • AC-1: Under worktree isolation, an issue whose worktree could not be created fails before any phase runs, with the captured git stderr in the issue result's abortReason and the run log, and no phase for that issue has cwd equal to the main checkout; IssueExecutionContext carries an explicit worktreeRequired flag so that neither producer (executeOneIssue, executeBatch) can start such an issue. Evidence: npx vitest run src/lib/workflow/run-orchestrator.worktree-failure.test.ts → ≥ 2 passed, 0 failed (new file: a stubbed ensureWorktrees that omits one issue and records its stderr yields a failed issue result naming the stderr; executePhase is never called for it; the other issue runs); mutation-verified: deleting the worktreeRequired && !worktree guard in runIssueWithLogging makes src/lib/workflow/run-orchestrator.worktree-failure.test.ts > worktree provisioning > a missing worktree fails the issue before any phase fail.

    AC-2 to AC-4 can stay as written, with the AC-4 caveat below.


    AC Quality Check

    • AC-1: see above. The outcome is sound, but the mutation site cannot be satisfied.
    • AC-2: OK. "short backoff" has no number. Recommend 5 attempts with 100/200/400/800 ms backoff and an injectable sleep. The injectable sleep also lets the test release the lock deterministically "after the first attempt".
    • AC-3: OK. Not vacuous: phase-executor.test.ts has no recordWorktreeBaseRef cases today, so -t "recordWorktreeBaseRef" matches 0 tests.
    • AC-4: ⚠️ vacuous as worded. ensureWorktree is all spawnSync. Two calls "started together" in one process (Promise.all) run one after the other, so they never race and the test passes on unchanged code. The test must start two child processes (e.g. two npx tsx scripts that call ensureWorktree against the same clone) and release them together, e.g. both waiting on a barrier file. Suggested clarification for the evidence clause: "two child processes, each calling ensureWorktree …".
    • All evidence files are new (worktree-manager.integration.test.ts and run-orchestrator.worktree-failure.test.ts do not exist), so every evidence command fails on the base branch. ✅

    Scope Assessment

    Non-Goals: present (no cross-CLI lock; #1234 only as far as AC-3 goes; no plugin/skill edits, which keeps clear of the plugin freeze).

    Metric Value Status
    Feature count 1 (provisioning failure handling) ✅
    AC items 4 ✅
    Directory spread 2 (src/lib/workflow, root CHANGELOG.md) ✅

    Verdict: ✅ SCOPE_OK


    Acceptance Criteria

    AC-1: A missing worktree fails the issue before any phase (proposed text above)

    Verification: Unit Test (orchestrator with stubbed ensureWorktrees and executePhase)
    Scenario: Given isolation is on and provisioning omits #B, with its stderr recorded → When RunOrchestrator.run([A, B]) runs → Then #B's result is success:false with abortReason containing the stderr, executePhase is never called for #B, and #A runs normally.
    Assumptions: dry-run and worktreeIsolation: false keep the current behavior, because the flag is only set when useWorktreeIsolation && !config.dryRun.

    AC-2: A could not lock config file failure is retried, switching from -b to an existing branch

    Verification: Integration Test (real clone, *.integration.test.ts, 30 s timeout)
    Scenario: Given a pre-created .git/config.lock → When ensureWorktree runs and the lock is released in the injected sleep after attempt 1 → Then the retry sees refs/heads/<branch> (created by the failed -b attempt), runs worktree add <path> <branch>, and returns non-null. With the lock never released → bounded attempts, then null with the stderr recorded, which feeds AC-1.
    Assumptions: a failed -b attempt leaves the branch ref but no directory and no worktree list entry (matches the repro). If a partial .git/worktrees/<name> entry appears, run git worktree prune before the retry.

    AC-3: recordWorktreeBaseRef retries and reports

    Verification: Unit Test (phase-executor.test.ts, which already mocks child_process; ⚠️ the mocks are ordered, so the new retry calls shift the queue)
    Scenario: Given git config fails once with "could not lock config file" → Then the second attempt succeeds and returns true. Given every attempt fails → Then it returns false / a warning naming the stderr instead of swallowing it. Both callers (worktree-manager.ts:1106 and :1276) surface the warning.

    AC-4: Two concurrent runs both get their worktrees

    Verification: Integration Test, two child processes (see the vacuity note above)
    Scenario: Given one real clone → When two processes call ensureWorktree for different issues at the same moment → Then both exit 0 with their worktree in git worktree list.


    Implementation Plan

    Phase 1: Retry primitive (AC-2, AC-3)

    1. worktree-manager.ts: add a small retryOnConfigLock(run, {attempts, sleep}) helper. It retries only when stderr matches /could not lock config file/.
    2. ensureWorktree (:1243–1271): wrap the worktree add call. Before each retry, re-run show-ref refs/heads/<branch>. If the branch now exists and this was the -b path, switch to worktree add <path> <branch> (the -B/recreateFrom path is idempotent as is). On final failure, return null and record the stderr.
    3. phase-executor.ts:831 recordWorktreeBaseRef: use the same retry. Return boolean, or {ok, error}, instead of swallowing. Both callers log a yellow warning on failure. Retry placement: put the helper somewhere both modules can import without a cycle. worktree-manager.ts already imports from phase-executor.ts, so the helper should go in phase-executor.ts or a new tiny git-retry.ts; the second is preferred.

    Phase 2: Carry the failure to the orchestrator (AC-1)

    1. ensureWorktrees / ensureWorktreesChain: add an optional trailing failures?: Map<number, string> that gets filled with the stderr. An optional parameter keeps existing vi.mock stubs valid. Change the summary line to N created, M reused, K failed. In chain mode, record each successor dropped by the break as chain broken: #<pred> has no worktree.
    2. types.ts IssueExecutionContext: add worktreeRequired?: boolean and worktreeError?: string. Add worktreeRequired and worktreeFailures to OrchestratorConfig. run() sets them from useWorktreeIsolation && !config.dryRun and passes the map. Both context producers (executeOneIssue, executeBatch) copy them into the context.
    3. batch-executor.ts runIssueWithLogging: one guard at the top. If worktreeRequired && !worktree, return a failed IssueResult (phaseResults: [], abortReason: worktree provisioning failed: <stderr>) after logWriter has recorded it. Follow the buildLockedResult / skillsPreflightAbort shape. This single site at the consumer of the contract covers both producers.

    Phase 3: Tests + changelog

    1. New run-orchestrator.worktree-failure.test.ts (AC-1), new worktree-manager.integration.test.ts (AC-2 config.lock, AC-4 concurrent), and recordWorktreeBaseRef cases in phase-executor.test.ts. Mutation-verify AC-1. Add a CHANGELOG.md [Unreleased] entry; if feat(#1351): improve(release): changelog fragments instead of a shared [Unreleased] block — 121/192 main commits touch CHANGELOG.md #1370's fragments land first, use its format.

    Design Review

    1. Where does this logic belong? Retry: next to the git calls in worktree-manager.ts and phase-executor.ts. Failing the issue: in the IssueExecutionContext contract, enforced in runIssueWithLogging, the one consumer both producers feed. The executor's cwd fallback does not change.
    2. Simplest correct approach? An explicit worktreeRequired flag plus one guard. Rejected: (a) guarding at phase-executor.ts:1643, which breaks isolation-off and the spec phase; (b) partitioning issues in run() the way lockedResults does, which leaves executeBatch and direct new RunOrchestrator().execute() callers unprotected; (c) a cross-CLI lock (listed as a Non-Goal).
    3. Existing pattern / recurrence: synthesized failed results (buildLockedResult feat(state): prevent concurrent sequant sessions from targeting the same issue #625, skillsPreflightAbort feat(run): pre-flight the skills install — missing .claude/skills/ should fail fast, not flail for 30 minutes as a spec retry #813). The class "issue runs outside its intended worktree" has two prior fixes, bug(fullsolve/exec): the worktree is never created and never verified — skill-driven runs execute in the main checkout, or in another repo's worktree #899→fix(#899): create the worktree in /fullsolve, verify it in /exec #902 and feat(exec/qa): explicit in-place checkout mode — run a phase on a branch in the current clone without creating or resolving a worktree #1136. Per the rule (≥2 fixes means fix the class), the plan fixes it at the contract (an explicit required flag) rather than at one call site. git log -S "could not lock" -- src is empty, so this is the first fix for the lock race.
    4. What would a senior reviewer challenge? "Why not have ensureWorktrees throw?" Because that would abort every issue in a batch when only one failed; isolating the failure to one issue matches the per-issue lock behavior. "Why retry rather than lock?" At the observed rate (11/40 in a deliberately extreme repro) a bounded retry is enough, and the Non-Goals say to revisit if AC-4 flakes.
    5. Producers / consumers of IssueExecutionContext.worktree: two producers, run-orchestrator.ts:1906 and batch-executor.ts:621. Both must set worktreeRequired. Add a parity assertion in the AC-1 test: drive executeBatch with the same context and expect the same failed result. Consumer: runIssueWithLogging (batch-executor.ts:1124), which then passes worktreePath to executePhase. Producers of .git/config writes: worktree add -b and recordWorktreeBaseRef; both get the retry.

    ADR: the plan picks a contract change over guarding in the executor, with alternatives rejected. Exec PR should add docs/adr/NNNN-worktree-required-contract.md.


    Feature Quality Planning

    All standard checks pass. Notable items:

    • Stale state: on failure, stateManager.initializeIssue must not record a worktree path that doesn't exist. The guard returns before state init, or records the failure.
    • The half-created branch is left on disk. That is fine: a later run sees branchExists and reuses it (the existing branch path). Note this in the abort message.
    • Integration tests must use a hermetic git identity and no gpg (memory: test-suite gpg / CI GECOS).

    Open Questions

    1. Retry budget: recommend 5 attempts with 100→800 ms backoff (~1.5 s worst case). If too small, AC-4 flakes under heavy contention.
    2. AC-4 child-process harness: recommend npx tsx scripts plus a barrier file. If it is done in-process instead, the test passes without exercising the race.

    Recommended Workflow

    Phases: exec → qa
    Quality Loop: disabled
    Reasoning: bug-labeled, 4 ACs, one directory. testgen is skipped for bug-only issues. Halted here pending the owner's edit to AC-1.

    Label Review

    Current: bug
    Recommended: bug (no change). planned is withheld until AC-1 is edited.
    Quality Loop: won't auto-enable (SCOPE_OK).

  5. admarble commented on Oct 17, 2026

    @admarble
    ContributorAuthor

    Runner decision on the SPEC_DIVERGENCE (2026-10-17): the spec's reading is correct and matches the pre-filing research. worktreePath === undefined at phase-executor.ts:1643 is also the legitimate isolation-off and spec-phase case, so the executor cannot own the guard; the owner is the IssueExecutionContext.worktree contract, consumed once in runIssueWithLogging and fed by two producers.

    The outcome of AC-1 is unchanged. Edited in the body (the body is canonical, docs/internal/graph-2026-10-consolidation/issues/1469.md is the as-filed snapshot):

    • AC-1: mutation record now names the real site (worktreeRequired && !worktree guard in runIssueWithLogging); the context carries an explicit worktreeRequired; the test also drives executeBatch for producer parity.
    • AC-4: two child processes released by a barrier; an in-process Promise.all is vacuous because ensureWorktree is spawnSync.
    • AC-2 and AC-3 unchanged. Retry budget: the spec's 5 attempts, 100→800 ms, injectable sleep, is accepted as the default; the exec may pick another bound if it records why.

    Edits made under the owner's "proceed if ready and ACs met" for this freeze-safe fix; they change prescriptions (mutation site, test harness), not requirements. Re-running exec → qa per the recorded spec.

  6. admarble commented on Oct 17, 2026

    @admarble
    ContributorAuthor

    QA Verdict: AC_MET_BUT_NOT_A_PLUS

    AC coverage: 4/4 met

    Gaps:

    • AC-1 mutation record missing from PR body (QA re-ran the mutation: named test fails, restored)
    • Concurrency test's 'kept the upstream' assertion is satisfied by sequantBaseRef and would pass with no upstream
    • Spec-recommended ADR for the worktreeRequired contract not added
    • The concurrency test claims more than it checks. It asserts [branch "feature/20x-…"] and calls that "kept the upstream". That section is also written by recordWorktreeBaseRef (sequantBaseRef), so the assertion passes even when a retry added the branch without an upstream. That does happen: the -b attempt that lost the lock never writes branch.X.remote/merge. In practice nothing breaks, because the PR push uses push -u origin <branch> (worktree-manager.ts:2609). But the comment or the assertion should be corrected.
  7. added a commit that references this issue on Oct 17, 2026
  8. admarble commented on Oct 17, 2026

    @admarble
    ContributorAuthor

    Runner verification (2026-10-17, worktree at 5b70f93 on PR #1493): all four Evidence commands re-run verbatim — AC-1 3 passed; AC-2 2 passed; AC-3 3 passed; AC-4 1 passed (two child processes). AC-1 mutation run by the runner: the guard in runIssueWithLogging made never-true → exactly worktree provisioning > a missing worktree fails the issue before any phase fails; restored, 3 passed; record in the PR body.

    QA's three findings resolved in the PR: mutation record added; the concurrency test now asserts branch.<name>.sequantBaseRef (what provisioning guarantees after a lost lock; the [branch] header was also written by recordWorktreeBaseRef, and the upstream is legitimately absent when the retry adds the branch without -b); ADR-0017 added with its index row. The PR touches no frozen path. Awaiting the owner's merge decision (stop-at-PR).

  9. added a commit that references this issue on Oct 17, 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

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions