Repository navigation
Description
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
abortReasonand the run log, and no phase for that issue hascwdequal to the main checkout;IssueExecutionContextcarries an explicitworktreeRequiredflag 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 stubbedensureWorktreesthat omits one issue and records its stderr yields a failed issue result naming the stderr;executePhaseis never called for it; the other issue runs;executeBatchfed the same context yields the same failed result); mutation-verified: deleting theworktreeRequired && !worktreeguard inrunIssueWithLoggingmakessrc/lib/workflow/run-orchestrator.worktree-failure.test.ts > worktree provisioning > a missing worktree fails the issue before any phasefail. - AC-2: A
could not lock config filefailure fromgit worktree addis retried with short backoff, re-checking whether the branch now exists so the retry usesworktree 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.lockreleased 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 callingensureWorktreefor a different issue against one real clone and released together by a barrier, both exit 0 and both worktrees appear ingit worktree list; an in-processPromise.alldoes not count,spawnSyncserializes it).
Prior fixes / producers
- Prior fixes on this class: none for the lock race (
git log -S "could not lock" -- srcis empty; issue searches for "worktree add lock", "config file", "produced no changes" return nothing). 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, 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 is the same class on the skill side (worktree created by the wrong party). Two fixes there, so this is a class: the ACs state the outcome (an issue never runs outside its worktree under isolation) rather than one call site. - Producers of
.git/configwrites during provisioning: two,git worktree add -b(upstream config) andrecordWorktreeBaseRef(branch.<name>.sequantBase), both racing across CLIs; the latter also swallows failure, which makes--base <other>runs silently compare againstorigin/main. No lock covers them:LockManageris per issue,CheckoutLockis used only bysequant locks, and both are no-ops underSEQUANT_ORCHESTRATOR.
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
- A cross-CLI lock for provisioning (retry is enough at the observed rate; revisit if AC-4 flakes).
- The exec guard's base-ref resolution (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) beyond AC-3.
- Any edit under
plugin/,.claude/skills/ortemplates/skills/(plugin freeze).
Activity
docs(#1470): graph-2026-10-consolidation founding doc, issue graph an…
admarble commentedon Oct 17, 2026
Runner context before launch (2026-10-17,
mainat aaff4e8). Line numbers in the body were taken at ad71b34 and have shifted; the anchors are unchanged:ensureWorktreelogs❌ Failed to create worktreeand returnsnull:src/lib/workflow/worktree-manager.ts:1270(was :1153–1158).ensureWorktreesprintsWorktrees: N created, M reusedand drops the null:worktree-manager.ts:1415–1419(was :1296–1298).worktree: worktreeInfo ? {...} : undefined:run-orchestrator.ts:1896–1910(unchanged).const cwd = shouldUseWorktree ? worktreePath : process.cwd();atphase-executor.ts:1643(was :1636). "Restoring theworktree?.pathfallback" 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 acould not lock config filefailure is retried. If the real owner of the fallback turns out to be theIssueExecutionContext.worktreecontract rather than the executor, stop and surface rather than patch locally.admarble commentedon Oct 17, 2026
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.worktreecontract 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 === undefinedis 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.IssueExecutionContext.worktree?(types.ts:928, "when worktree isolation is enabled") usesundefinedfor two different states: isolation is off, and provisioning failed. Two places build that context fromworktreeMap.get(n):run-orchestrator.ts:1906(executeOneIssue) andbatch-executor.ts:621(executeBatch). Both pass the ambiguousundefineddown.worktree?.pathfallback", 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-2 to AC-4 can stay as written, with the AC-4 caveat below.
AC Quality Check
phase-executor.test.tshas norecordWorktreeBaseRefcases today, so-t "recordWorktreeBaseRef"matches 0 tests.ensureWorktreeis allspawnSync. 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. twonpx tsxscripts that callensureWorktreeagainst 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 callingensureWorktree…".worktree-manager.integration.test.tsandrun-orchestrator.worktree-failure.test.tsdo 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).
src/lib/workflow, rootCHANGELOG.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
ensureWorktreesandexecutePhase)Scenario: Given isolation is on and provisioning omits #B, with its stderr recorded → When
RunOrchestrator.run([A, B])runs → Then #B's result issuccess:falsewithabortReasoncontaining the stderr,executePhaseis never called for #B, and #A runs normally.Assumptions: dry-run and
worktreeIsolation: falsekeep the current behavior, because the flag is only set whenuseWorktreeIsolation && !config.dryRun.AC-2: A
could not lock config filefailure is retried, switching from-bto an existing branchVerification: Integration Test (real clone,
*.integration.test.ts, 30 s timeout)Scenario: Given a pre-created
.git/config.lock→ WhenensureWorktreeruns and the lock is released in the injected sleep after attempt 1 → Then the retry seesrefs/heads/<branch>(created by the failed-battempt), runsworktree 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
-battempt leaves the branch ref but no directory and noworktree listentry (matches the repro). If a partial.git/worktrees/<name>entry appears, rungit worktree prunebefore the retry.AC-3:
recordWorktreeBaseRefretries and reportsVerification: Unit Test (⚠️ the mocks are ordered, so the new retry calls shift the queue)
phase-executor.test.ts, which already mockschild_process;Scenario: Given
git configfails once with "could not lock config file" → Then the second attempt succeeds and returnstrue. Given every attempt fails → Then it returnsfalse/ a warning naming the stderr instead of swallowing it. Both callers (worktree-manager.ts:1106and: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
ensureWorktreefor different issues at the same moment → Then both exit 0 with their worktree ingit worktree list.Implementation Plan
Phase 1: Retry primitive (AC-2, AC-3)
worktree-manager.ts: add a smallretryOnConfigLock(run, {attempts, sleep})helper. It retries only when stderr matches/could not lock config file/.ensureWorktree(:1243–1271): wrap theworktree addcall. Before each retry, re-runshow-ref refs/heads/<branch>. If the branch now exists and this was the-bpath, switch toworktree add <path> <branch>(the-B/recreateFrompath is idempotent as is). On final failure, return null and record the stderr.phase-executor.ts:831recordWorktreeBaseRef: use the same retry. Returnboolean, 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.tsalready imports fromphase-executor.ts, so the helper should go inphase-executor.tsor a new tinygit-retry.ts; the second is preferred.Phase 2: Carry the failure to the orchestrator (AC-1)
ensureWorktrees/ensureWorktreesChain: add an optional trailingfailures?: Map<number, string>that gets filled with the stderr. An optional parameter keeps existingvi.mockstubs valid. Change the summary line toN created, M reused, K failed. In chain mode, record each successor dropped by thebreakaschain broken: #<pred> has no worktree.types.tsIssueExecutionContext: addworktreeRequired?: booleanandworktreeError?: string. AddworktreeRequiredandworktreeFailurestoOrchestratorConfig.run()sets them fromuseWorktreeIsolation && !config.dryRunand passes the map. Both context producers (executeOneIssue,executeBatch) copy them into the context.batch-executor.tsrunIssueWithLogging: one guard at the top. IfworktreeRequired && !worktree, return a failedIssueResult(phaseResults: [],abortReason: worktree provisioning failed: <stderr>) afterlogWriterhas recorded it. Follow thebuildLockedResult/skillsPreflightAbortshape. This single site at the consumer of the contract covers both producers.Phase 3: Tests + changelog
run-orchestrator.worktree-failure.test.ts(AC-1), newworktree-manager.integration.test.ts(AC-2config.lock, AC-4concurrent), andrecordWorktreeBaseRefcases inphase-executor.test.ts. Mutation-verify AC-1. Add aCHANGELOG.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
gitcalls inworktree-manager.tsandphase-executor.ts. Failing the issue: in theIssueExecutionContextcontract, enforced inrunIssueWithLogging, the one consumer both producers feed. The executor's cwd fallback does not change.worktreeRequiredflag plus one guard. Rejected: (a) guarding atphase-executor.ts:1643, which breaks isolation-off and the spec phase; (b) partitioning issues inrun()the waylockedResultsdoes, which leavesexecuteBatchand directnew RunOrchestrator().execute()callers unprotected; (c) a cross-CLI lock (listed as a Non-Goal).buildLockedResultfeat(state): prevent concurrent sequant sessions from targeting the same issue #625,skillsPreflightAbortfeat(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" -- srcis empty, so this is the first fix for the lock race.ensureWorktreesthrow?" 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.IssueExecutionContext.worktree: two producers,run-orchestrator.ts:1906andbatch-executor.ts:621. Both must setworktreeRequired. Add a parity assertion in the AC-1 test: driveexecuteBatchwith the same context and expect the same failed result. Consumer:runIssueWithLogging(batch-executor.ts:1124), which then passesworktreePathtoexecutePhase. Producers of.git/configwrites:worktree add -bandrecordWorktreeBaseRef; 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:
stateManager.initializeIssuemust not record aworktreepath that doesn't exist. The guard returns before state init, or records the failure.branchExistsand reuses it (the existing branch path). Note this in the abort message.Open Questions
npx tsxscripts 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).
plannedis withheld until AC-1 is edited.Quality Loop: won't auto-enable (SCOPE_OK).
admarble commentedon Oct 17, 2026
Runner decision on the SPEC_DIVERGENCE (2026-10-17): the spec's reading is correct and matches the pre-filing research.
worktreePath === undefinedatphase-executor.ts:1643is also the legitimate isolation-off and spec-phase case, so the executor cannot own the guard; the owner is theIssueExecutionContext.worktreecontract, consumed once inrunIssueWithLoggingand 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.mdis the as-filed snapshot):worktreeRequired && !worktreeguard inrunIssueWithLogging); the context carries an explicitworktreeRequired; the test also drivesexecuteBatchfor producer parity.Promise.allis vacuous becauseensureWorktreeisspawnSync.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 → qaper the recorded spec.admarble commentedon Oct 17, 2026
QA Verdict: AC_MET_BUT_NOT_A_PLUS
AC coverage: 4/4 met
Gaps:
[branch "feature/20x-…"]and calls that "kept the upstream". That section is also written byrecordWorktreeBaseRef(sequantBaseRef), so the assertion passes even when a retry added the branch without an upstream. That does happen: the-battempt that lost the lock never writesbranch.X.remote/merge. In practice nothing breaks, because the PR push usespush -u origin <branch>(worktree-manager.ts:2609). But the comment or the assertion should be corrected.test(#1469): the concurrency test asserts the recorded base ref, not …
admarble commentedon Oct 17, 2026
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
runIssueWithLoggingmade never-true → exactlyworktree provisioning > a missing worktree fails the issue before any phasefails; 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 byrecordWorktreeBaseRef, 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).fix(#1487): an ambiguous issue records its candidate branches as the …