Repository navigation
Description
Summary
The concurrency lock added by #625 is keyed on issue number (src/lib/locks/lock-manager.ts:232):
lockPathFor(issue: number): string {
return join(this.locksDir, `${issue}.lock`);
}Two sessions working different issues take different lock files and never contend — but when both operate in the same working tree, the contended resource is the checkout, not the issue. git checkout, reset, rebase and merge are global to a working tree; there is currently no lock that represents it.
/fullsolve's Phase 0.3 rationale (fullsolve/SKILL.md:255) reads as broader coverage than exists:
This prevents a second session (another
/fullsolve, annpx sequant run, or another/fullsolvein a different window) from racing on the same issue and producing zero-diff exec failures.
Accurate as written. But a reader reasonably takes "another /fullsolve in a different window" as the general concurrency guarantee, and for different issues in one checkout there is none.
Evidence
Two /fullsolve sessions in ai-devtools-weekly on 2026-08-05, issues #10 and #23, each holding its own lock file, interleaving in one working tree:
12:49:36 commit: chore(#10): drop stray #23 line committed to this branch by mistake
12:49:53 checkout: feature/10-distribution-measurement -> fix/issue-023-cloud-egress
12:50:25 commit (cherry-pick): chore(#23) ...
12:58:05 checkout: fix/issue-023-egress-clean -> feature/10-distribution-measurement
Both locks behaved exactly as designed. Neither had anything to say about the shared tree.
Scope after the companion fixes
This is defense in depth, not the incident's cause. The proximate cause is that /fullsolve never creates a worktree at all, so both sessions fell back to the main checkout — filed as #899. Once that lands, agent work happens in per-issue worktrees and the main checkout is touched far less.
It is not touched never, which is why this is still worth building:
/specand/assessrun in the main repo by contract./merger,sequant merge, and/fullsolve's post-PRcleanup-worktree.shmutate the main checkout.- A human session in the same repo is unaccounted for entirely.
The value is turning a silent race into a legible refusal: "the checkout is held by the session working #23." Today the loser of the race gets no signal at all until commits land on the wrong branch.
Design sketch (open to alternatives)
A checkout-scoped lock alongside the per-issue lock — .sequant/locks/checkout.lock, holding {pid, hostname, issue, startedAt, command} — acquired by any session about to run branch-mutating git operations in the main working tree, and released on completion.
This requires LockManager to accept a string key. lockPathFor, acquire, release, list and the <issue>.lock filename convention all assume number today; locks list output and the CLI surface would need to render a non-numeric holder. That widening is the bulk of the work and is worth designing before implementing.
Alternatives worth weighing before committing:
- Advisory-only (warn, don't block) — cheaper, but a warning an agent can proceed past is close to no lock.
- Reuse the existing per-issue lock directory with a reserved sentinel key rather than widening the type.
- Detect rather than lock: refuse branch-mutating operations in the main checkout outright once worktrees are guaranteed, making the lock unnecessary.
The third is arguably the better end state and should be evaluated first.
Acceptance Criteria
- AC-1: A design decision is recorded on this issue choosing between a checkout-scoped lock and outright refusal of branch-mutating operations in the main checkout, with the rationale.
- AC-2: Two concurrent sessions working different issues in one checkout cannot both perform branch-mutating git operations there; the second is refused with a message naming the holding session and its issue.
- AC-3: The refusal path tells the user how to proceed (which worktree to use, or how to clear a stale holder), rather than only reporting the block.
- AC-4: Stale recovery matches the existing lock semantics — same-host dead PID, age ceiling, and
SEQUANT_MAX_LOCK_AGE_MSoverride — so an abandoned holder cannot wedge a checkout permanently (see Nested phase claude that hangs after its turn is killed at ~106s, taking down the parent sequant run #856). - AC-5: Orchestrator/MCP mode remains a no-op, consistent with
LockManager's existing behavior underSEQUANT_ORCHESTRATOR. - AC-6:
/fullsolve's Phase 0.3 text states precisely what the per-issue lock does and does not cover, so it no longer reads as a general concurrency guarantee. - AC-7: An integration test runs two sessions against one checkout on different issues and asserts the second is refused, with a recorded mutation result per CLAUDE.md.
Non-Goals
- Not replacing the per-issue lock from feat(state): prevent concurrent sequant sessions from targeting the same issue #625, which is correct for what it covers.
- Not coordinating across hosts — same-machine mutual exclusion only, matching existing lock semantics.
Activity
admarble commentedon Aug 6, 2026
Plan (/spec)
Complexity: Standard (7 ACs, 4 source directories + 2 mirror sets)
AC-1 — Design Decision (recorded here)
Decision: build the checkout-scoped lock, and enforce it in
pre-tool.sh.What changed the framing
The issue offers three alternatives and suggests the third — "refuse branch-mutating operations in the main checkout outright" — is "arguably the better end state and should be evaluated first." Evaluated, and rejected as a standalone, for two reasons:
/specand/assessrun in the main repo by contract;/merger,sequant merge, andcleanup-worktree.shmutate it. A blanket ban breaks all of them. Refusal has no notion of who holds the tree, so it cannot distinguish the one legitimate merger session from the second racing session.Option 2 (advisory-only warn) is rejected on the issue's own reasoning: a warning an agent can proceed past is close to no lock.
The finding that sets the enforcement layer
The racing actor is the agent's own
git checkoutBash calls, not sequant TypeScript. The incident trace is agent shell activity:Sequant's own TS does branch-mutating git almost exclusively inside worktrees (
git -C <worktree> rebase|branch -Dinworktree-manager.ts); the main checkout is mutated by agents and by shell scripts. So a lock that only the CLI and skills call is cooperative-only — it would leave AC-2's "cannot" unenforced against precisely the actor that caused the incident.pre-tool.shis therefore the enforcement layer. It already has the exact shape needed (seg_match '<pattern>'→log_block→HOOK_BLOCKED→exit 2, as used for force-push andgit reset --hard), and it already receives per-session identity on stdin.Rejected sub-alternative: widening
LockManagerto string keysThe issue's design sketch anticipates widening
lockPathFor,acquire,release,listandheldfromnumbertostring, and calls that "the bulk of the work." It is avoidable. A siblingCheckoutLockin the same module reuses the already-exported pure primitives (classifyStaleness,defaultIsPidAlive,resolveLocksDir,resolveMaxLockAgeMs,isOrchestratorMode) without touching the numeric type. That keeps the blast radius offstatus.ts,merge.ts,resume.tsandrun-orchestrator.ts, which all pass real issue numbers tocheck().LockListingturns out to have exactly one consumer (src/commands/locks.ts:92), so rendering a non-numeric holder inlocks listis a localized change rather than a type-system ripple.Trade-off accepted: the atomic-write path (~40 lines of
openSync(…, "wx")) is duplicated rather than generalized. Chosen deliberately over widening a type consumed by five call sites for one new key.AC Quality Check
Pinning AC-2's "branch-mutating":
git checkout <ref>,git switch,git reset,git rebase,git merge,git cherry-pick. Excluded:git checkout -- <path>/git checkout <ref> -- <path>(path restore, does not move HEAD), and anything carrying-C <path>or run with cwd inside a worktree.Scope Assessment
Non-Goals (from issue): not replacing the per-issue lock; not coordinating across hosts.
Verdict:⚠️ SCOPE_WARNING — quality loop enabled. Spread is inflated by mandatory 3-way mirroring of
pre-tool.shandfullsolve/SKILL.md, which is mechanical, not conceptual.Acceptance Criteria
AC-1: Design decision recorded
Verification: Manual Test — this comment.
AC-2: Second session refused, message names holder + issue
Verification: Integration Test
Scenario: Given session A holds
checkout.lockwithissue: 23→ When session B (issue 10) runsgit checkout feature/10-xwith cwd at the repo root → Then exit 2 and stderr names PID, issue #23, and age.Assumptions: Claude Code's PreToolUse stdin payload carries
session_id. Verify empirically in exec; fall back topid+hostnameif absent.AC-3: Refusal is actionable
Verification: Integration Test
Scenario: Given the block above → Then stderr also states which worktree to use and
sequant locks checkout clear.AC-4: Stale recovery matches existing semantics
Verification: Unit Test
Scenario: Given a
checkout.lockpastSEQUANT_MAX_LOCK_AGE_MS(or same-host dead PID) → When acquired → Then cleared and re-acquired.Assumptions: Reuses
classifyStalenessrather than reimplementing it, so parity is structural.AC-5: Orchestrator mode is a no-op
Verification: Unit Test
Scenario: Given
SEQUANT_ORCHESTRATOR=1→ When acquire/release/check/hook-guard run → Then no fs touch, no block, exit 0.AC-6: Phase 0.3 text is precise
Verification: Unit Test (text assertion, region-scoped)
Scenario: Given
fullsolve/SKILL.mdin all 3 dirs → Then the Phase 0.3 block states the per-issue lock covers the same issue only, and points at the checkout lock for shared-tree contention.AC-7: Integration test, two sessions, one checkout
Verification: Integration Test + recorded mutation result per CLAUDE.md.
Implementation Plan
Phase 1 — Lock primitive
src/lib/locks/types.ts: addCheckoutLockFileSchema(LockFileSchemafields +issue: number,sessionId: string optional),CHECKOUT_LOCK_FILENAME = "checkout.lock".src/lib/locks/checkout-lock.ts:CheckoutLockclass —acquire,release,check,clear. ReusesclassifyStaleness,resolveLocksDir,resolveMaxLockAgeMs,isOrchestratorMode. SameO_CREAT|O_EXCLatomicity. ExportformatCheckoutLockedMessage()producing the AC-3 actionable text.src/lib/locks/index.ts: export the new surface.Phase 2 — CLI
src/commands/locks.ts:locksCheckoutCommandwithacquire|release|check|clearsubactions,--json,--issue,--session-id. ExtendlocksListCommandto render the checkout holder as a distinct row (list()currently drops non-numeric filenames — leave that filter alone, query the checkout lock separately).bin/cli.ts: wiresequant locks checkout <action>.Phase 3 — Hook enforcement (3 mirrors, byte-identical)
.claude/hooks/pre-tool.sh(+hooks/,templates/hooks/): extractsession_idfromINPUT_JSON; add the branch-mutation guard using the pinned pattern set. Guard fires only when cwd is the main checkout (not a worktree) and a foreign-sessioncheckout.lockis fresh.startedAtvs the age ceiling — not a mirror ofclassifyStaleness. Per PM_CONFIG.yarn.ciInstall uses Yarn 2+--immutable, which Yarn 1 rejects — no berry detection exists #871, a shell transcription of TS logic drifts; a strictly-weaker guard that fails open is honest and documented as such in a comment.Phase 4 — Docs + AC-6 text
fullsolve/SKILL.md× 3 dirs.Phase 5 — Tests
checkout-lock.test.ts(AC-4, AC-5),checkout-lock.integration.test.ts(AC-2, AC-3, AC-7 — two sessions, one checkout), region-scoped SKILL.md gate test (AC-6)..integration.infix or they land in theunitproject's 5s timeout.Rule Touchpoints
.claude/hooks/pre-tool.sh+hooks/+templates/hooks/{.claude,templates,}/skills/fullsolve/SKILL.md:255Design Review
src/lib/locks/beside its per-issue sibling; enforcement inpre-tool.sh, the only layer that observes every session's git commands.LockManager's key type (5 consumers, no payoff), and a sentinel numeric key (parseIssuerejects<= 0; opaque on disk).LockManagerfor the lock; the force-push /git reset --hardguards for the hook block; theOrchestratorRendererno-op convention for AC-5.--immutable, which Yarn 1 rejects — no berry detection exists #871)?" — yes, which is why the hook implements a strictly weaker predicate that fails open, rather than a transcription.Open Questions
session_id? Recommendation: assume yes, verify in exec, fall back topid+hostname. Impact if wrong: identity degrades to PID, which is unreliable for skill shells — the guard would over-block. Blocking for AC-2's "naming the holding session."/specand/assessacquire the checkout lock? Recommendation: no — they are read-mostly and holding the tree across a whole spec phase would wedge normal work. Only branch-mutating operations contend. Impact: a/specthat does mutate is unprotected; acceptable, and the hook still blocks it if someone else holds.Recommended Workflow
Phases: spec → exec → qa
Quality Loop: enabled (SCOPE_WARNING)
Reasoning: No UI surface — skipping
/test. Shell + TS changes;/verifyafter exec to exercise the CLI and hook for real.Label Review
Current:
enhancementRecommended: add
no-browser-testReason: no UI surface; makes the
/testskip explicit rather than incidental.admarble commentedon Aug 6, 2026
/fullsolve Complete
Issue: #901
PR: #903
Status: READY_FOR_MERGE
AC Coverage
pre-tool.shguard; 12 integration assertions; live CLI demogit -Cescape, andlocks checkout clearCheckoutLockdelegates toclassifyStaleness; hook mirrors all 3 branches; 7 parity casesSEQUANT_ORCHESTRATORProgress
no-browser-test; no UI surface)Quality metrics
lint,lint:skill-sync(44/44),lint:skill-calls(0 violations): cleanTwo findings worth recording
A real bug, caught during exec. The first staleness implementation parsed
startedAtwith BSDdate -j -f, which parses in local time whilestartedAtis UTC. West of UTC that yields a negative age (measured −17,217,000 ms for a 12-minute-old lock), so a stale lock would have read as fresh forever and wedged the checkout permanently — the exact failure AC-4 forbids. Fixed withTZ=UTC, with a regression test across three timezones.A self-corrected AC gap. The hook's staleness began as a deliberately weaker subset (age ceiling only) to dodge the #871 TS↔shell drift trap. Read against AC-4 literally — it enumerates "same-host dead PID, age ceiling, and
SEQUANT_MAX_LOCK_AGE_MS" — that subset let an already-dead holder block the tree for up to 24h. Bounded, but still a wedge. The second commit gives the hook full parity, and because that is the drift hazard (and the repo's drift guard compares literal strings only, so it cannot see semantic divergence), 7 parity cases now pin hook andclassifyStalenessto identical verdicts.Risk assessment
datebranch runs only in CI.session_idin the hook envelope (the fieldcapture-tokens.sh:24already reads). ASEQUANT_ISSUEfallback plus a test covers its absence.Relationship to #899
Unchanged from the issue's framing: this is defense in depth, not the incident's proximate cause. #899 (worktree never created) is still open. Worth noting that
/fullsolvedid not create a worktree on this run either — it was created explicitly — so #899 reproduces.Ready for human review and merge.
Merge origin/main (#899, #904) into feature/901
admarble commentedon Aug 6, 2026
Gap-closure round
All gaps flagged in the previous comment are now closed. Two of them turned out to be defects rather than documentation debt.
1.
session_id— verified, and it found a bugThe previous comment listed "does the
PreToolUseenvelope actually carrysession_id?" as an unverified assumption. Captured a live payload by briefly instrumenting the hook:Confirmed. The instrumentation was reverted and the main checkout's hook verified byte-identical to
HEAD.Incidentally, the capture recorded two distinct sessions operating in this one checkout — this one and a concurrent
/fullsolve 899. A live instance of exactly the scenario this issue exists to prevent.2. A false positive that would have blocked legitimate worktree work
The payload also carries
cwd— which exposed a real defect. The guard decided "is this the main checkout?" fromCLAUDE_PROJECT_DIR, which names the project directory and stays pinned to the main checkout even while the agent's shell is inside a worktree. So agit checkoutrunning legitimately in a worktree was blocked.That is the guard's worst failure mode, and it is self-defeating: the entire purpose of the lock is to push sessions into worktrees.
The original tests could not have caught it — they set
CLAUDE_PROJECT_DIRto the worktree, so project dir and cwd never diverged, which is not how a real session behaves. Fixtures are now realgit initrepos with realgit worktree addchildren, and three cases pin the divergence explicitly: in-worktree allows, in-main still blocks (so the fix cannot degrade to always-allow), andcd <worktree> && git checkoutallows.3. Real-process concurrency — and a test that was lying
Three tests now race the built CLI for real. Writing them surfaced a problem with my own test design, via mutation 8 (
openSyncwx→w, breaking atomicity): all 33 integration tests stayed green. Node startup dominates, so each child's read of the existing holder serializes it long before the create — theO_CREAT|O_EXCLwindow is never reached.So the race test could not substantiate the atomicity claim. Rather than leave it overclaiming, it is relabelled to assert only end-to-end mutual exclusion, and two unit tests now drive
writeAtomicdirectly from the state both acquirers reach after passing the read check. Those kill the mutation.4. The
buildLockedResultflake — diagnosed, not toleratedIt lives in the
unitproject, which deliberately keeps vitest's 5s default because "a slow test is a real signal" there, but it lazily imports the whole workflow package. Measured failing at 5.06s and passing at 1.38s on the same commit, purely under machine load — a cold-import cost, not a behavioral one. Fixed with the per-test override the config documents as its escape hatch, not by widening the project default (which would blunt the signal for every other unit test) and not by loosening an assertion.5. GNU
datebranch — already coveredCI is
ubuntu-latestrunningnpm test, so the integration tests exercise the GNU fallback on every run.6. #899/#904 merged mid-review — and this branch's own gate caught the regression
#899 (PR #902) and #904 landed on main. Merging them in surfaced two new abort paths in #899's Phase 1.5 — worktree-resolve failure and
new-feature.shfailure — that release the per-issue lock but not the checkout lock. Unpaired, those leak the working tree until the 6h TTL expires.The AC-6 release-contract assertion failed on exactly those two sites. Both now release both locks. Conflicts in
bin/cli.tsandCHANGELOG.mdwere purely additive; both sides kept.Worth noting the previous comment's observation that "#899 reproduces" is now moot — #902 fixed it, and this branch merges that fix.
Current state
checkout-lock.test.tscheckout-lock.integration.test.tsfullsolve-checkout-lock-skill.test.ts(AC-6)8 mutations recorded, each killing exactly its target. AC coverage remains 7/7 MET. Full detail in #903.
fix(#906): checkout release must prove holder identity (#907)
fix(#910): cleanup-worktree.sh sibling — update main without switchin…
fix(#911): /merger and /release participate in the checkout lock (#917)
fix(#910): new-feature.sh must not mutate the main checkout (#912)
fix(#963): pre-tool.sh No-Changes Guard resolves cd targets instead o…
fix(#911): /merger and /release participate in the checkout lock