Repository navigation
feat(locks): checkout-scoped lock for the shared working tree (#901) - #903
Merged
admarble merged 6 commits intoAug 6, 2026
Merged
Conversation
The #625 lock is keyed on issue number, so two sessions working different issues take different lock files and never contend -- yet git checkout, switch, reset, rebase, merge and cherry-pick are global to a working tree. The contended resource is the checkout, not the issue. Adds .sequant/locks/checkout.lock plus `sequant locks checkout <acquire|release|check|clear>`, and enforces it in pre-tool.sh. The hook is the load-bearing half: the racing actor is an agent's own `git checkout` Bash command, since sequant's TypeScript mutates git almost exclusively via `git -C <worktree>`. A CLI-only lock would have left the incident path unguarded. Design notes: - Staleness delegates to the exported classifyStaleness, so dead-PID, the 24h ceiling and SEQUANT_MAX_LOCK_AGE_MS match the per-issue lock by construction rather than by duplication. - The shell guard implements a deliberately weaker subset (existence + age ceiling, failing open past it) instead of transcribing classifyStaleness into sed/grep, which would drift (#871). It can only under-block. - LockManager's numeric key is untouched. checkout.lock is non-numeric so list() skips it; `locks list` queries it separately. - Guard is narrow: `git -C <path>`, path-restore `git checkout [<ref>] -- <path>`, non-mutating git, and linked worktrees all pass through. Fixes #901
The first pass implemented only the absolute age ceiling in the hook and documented the gap as a deliberately weaker subset. That reads fine until you check AC-4 literally: it enumerates "same-host dead PID, age ceiling, and SEQUANT_MAX_LOCK_AGE_MS override". Under the subset, a holder whose PID was already dead still blocked the tree for up to 24h -- the per-issue lock clears that case immediately. That is the wedge AC-4 forbids, just with a bound on it. The hook now mirrors all three classifyStaleness branches in the same order: absolute ceiling first (#856), then the same-host PID probe via the `kill -0` builtin (skipped when the holder set skipPidCheck), then the age fallback with the 6h skill TTL vs the 2h cross-host TTL. Both env overrides are honored. Mirroring shell against TypeScript is exactly the #871 drift hazard, and the repo's drift guard only compares literal strings, so it cannot see a semantic divergence here. Seven parity cases now drive the real hook and classifyStaleness over the same matrix and assert both reach the same verdict, so a future edit to either side fails loudly.
7 tasks
The guard decided "is this the main checkout?" from PARALLEL_MARKER_PROJECT_ROOT, which resolves to CLAUDE_PROJECT_DIR. That names the *project* directory, and Claude Code keeps it pinned to the main checkout even while the agent's shell is inside a worktree. So a `git checkout` running legitimately in a worktree was blocked -- the guard's worst failure mode, since the entire point of the lock is to push sessions into worktrees. The guard now reads `.cwd` from the PreToolUse envelope (verified against a live payload, alongside session_id), honors a leading `cd <dir> &&` the way the commit guard already does, and resolves that directory's toplevel with `git -C <cwd> rev-parse --show-toplevel`. Only a toplevel whose `.git` is a directory -- a main checkout, not a linked worktree -- is protected. The old tests could not catch this: they set CLAUDE_PROJECT_DIR to the worktree, so project dir and cwd never diverged, which is not how a real session behaves. Fixtures are now real `git init` repos with real `git worktree add` children, and three cases pin the divergence explicitly: in-worktree allows, in-main blocks (so the fix cannot degrade to always-allow), and `cd <worktree> && git checkout` allows.
Closes the two verification gaps flagged on the PR. Real concurrency: every existing test simulated the second session by writing a lock file, which exercises the guard but never the claim itself -- that two genuinely concurrent processes cannot both come away holding the tree. Three new cases spawn the built CLI for real: six sessions race and exactly one wins (asserted against the winner recorded on disk, not merely "some lock exists"), the loser's refusal names the actual winner, and a release hands the tree to the next session. These use async `spawn`, not `spawnSync`. `spawnSync` blocks the event loop, so `Promise.all` over it runs the children strictly one after another -- the processes never overlap and the race is theatre. With `spawn` they are in flight together and the kernel arbitrates the O_CREAT|O_EXCL create. buildLockedResult flake: diagnosed rather than tolerated. The test lives in the `unit` project, which deliberately keeps vitest's 5s default because "a slow test is a real signal" there, but it lazily imports the whole workflow package -- a cold transform cost that lands right on the 5s line. Measured failing at 5.06s and passing at 1.38s on the *same* commit, purely with machine load. Fixed with the local per-test override the config documents as the escape hatch, not by widening the project default (which would blunt the signal for every other unit test) and not by loosening an assertion.
The six-process CLI race could not pin this: node startup dominates, so each child's read of the existing holder serializes it long before the create and the exclusive-create window is never reached. Mutation proved it -- flipping `wx` to `w` left all 33 integration tests green. Two unit tests now drive `writeAtomic` directly, from the state both acquirers reach after passing the read check, and assert the loser neither wins nor truncates the winner's payload. The integration test is relabelled to claim only what it actually demonstrates.
Both conflicts were additive -- each side appended a new block at the same location -- so both sides are kept: - bin/cli.ts: the `locks checkout` group (#901) alongside the new `worktree` group (#899). - CHANGELOG.md: both Unreleased entries. The merge also surfaced a real regression, caught by this branch's own AC-6 gate rather than by review: #899 added two abort paths in its new Phase 1.5 (worktree-resolve failure, new-feature.sh failure) that release the per-issue lock but not the checkout lock. Unpaired, those would leak the working tree until the 6h skill TTL expired. Both now release both locks, restoring the invariant the gate asserts -- every per-issue release site has a checkout release beside it.
admarble
deleted the
feature/901-feat-locks-per-issue-locks-give-no-mutual-excl
branch
August 6, 2026 23:36
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #901.
Design decision (AC-1)
Build the checkout-scoped lock, and enforce it in
pre-tool.sh. Full rationale is recorded on the issue; the short version:The issue suggested its third alternative — refuse branch-mutating operations in the main checkout outright — might be the better end state. Evaluated and rejected as a standalone, because (a) the issue's own scope section lists legitimate main-checkout mutators (
/specand/assessby contract,/merger,sequant merge,cleanup-worktree.sh), so a blanket ban breaks them, and (b) AC-2 requires the loser be "refused with a message naming the holding session and its issue" — naming a holder requires a holder record, which detection alone has no notion of.What set the enforcement layer: the racing actor is an agent's own
git checkoutBash command, not sequant's TypeScript. The incident trace is agent shell activity, and sequant's TS mutates git almost exclusively viagit -C <worktree>(seeworktree-manager.ts). A lock only the CLI and skills consulted would be cooperative-only — leaving AC-2's "cannot" unenforced against precisely the actor that caused the incident.Rejected sub-alternative: widening
LockManager's key fromnumbertostring, which the issue anticipated as "the bulk of the work." Avoided. A siblingCheckoutLockreuses the already-exported pure primitives (classifyStaleness,defaultIsPidAlive,resolveLocksDir,resolveMaxLockAgeMs,isOrchestratorMode) without touching the numeric type, keeping the blast radius offstatus.ts,merge.ts,resume.tsandrun-orchestrator.ts.LockListingturned out to have exactly one consumer, so rendering a non-numeric holder inlocks listwas localized. Trade-off accepted: theO_CREAT|O_EXCLwrite (~30 lines) is duplicated rather than generalized.What landed
src/lib/locks/checkout-lock.ts—CheckoutLock+formatCheckoutLockedMessage..sequant/locks/checkout.lockis deliberately non-numeric soLockManager.list()skips it.sequant locks checkout <acquire|release|check|clear>;locks listrenders the checkout holder as its own row.pre-tool.shguard (all 3 mirrors, byte-identical) — the enforcing half./fullsolvePhase 0.3 rewritten (AC-6), all abort paths release both locks.The guard is deliberately narrow. These pass through untouched:
git -C <path>forms, path-restore (git checkout [<ref>] -- <path>), non-mutating git, linked worktrees (.gitis a file there, not a directory), and orchestrator mode.Findings during implementation (all fixed)
1. A real bug found and fixed during implementation. The first staleness implementation used
date -j -fto parsestartedAt. BSDdate -j -fparses in local time whilestartedAtis UTC, so west of UTC the computed age is negative — a stale lock would have read as fresh forever and wedged the tree permanently, the exact failure AC-4 forbids. Measured: −17,217,000 ms for a lock written 12 minutes earlier. Fixed withTZ=UTCon the BSD branch (date -u -don the GNU/CI branch), plus a regression test that asserts a 25h-old holder reads as stale inUTC,America/Los_AngelesandAsia/Tokyo.2. The hook's staleness started as a subset, and that was wrong. The first pass implemented only the age ceiling in shell and documented the gap as "a deliberately weaker subset" to dodge the #871 TS↔shell drift trap. Checked against AC-4 literally — it enumerates "same-host dead PID, age ceiling, and
SEQUANT_MAX_LOCK_AGE_MSoverride" — the subset let a holder whose PID was already dead block the tree for up to 24h, where the per-issue lock clears it immediately. Bounded, but still the wedge AC-4 forbids. The second commit gives the hook all threeclassifyStalenessbranches in the same order, using thekill -0builtin (no subprocess). Since that is the drift hazard, and the repo's drift guard compares literal strings only and cannot see a semantic divergence, 7 parity cases drive the real hook andclassifyStalenessover the same matrix and assert identical verdicts.Verification
checkout-lock.test.ts(AC-4, AC-5, atomicity)checkout-lock.integration.test.ts(AC-2/3/4/5/7)fullsolve-checkout-lock-skill.test.ts(AC-6)build,lint,lint:skill-sync,lint:skill-calls,lint:skill-gatesCLI exercised end-to-end against the built
dist/: free → acquire #23 → refuse #10 (exit 1, full message) → re-entrant re-acquire →locks listshowing both lock kinds →clearrefusing a fresh holder → orchestrator no-op → release → free.Mutation results (per CLAUDE.md)
Each mutation killed exactly its target and nothing else; tree clean after each revert.
TZ=UTCdate fixexit 2→exit 0)SEQUANT_ORCHESTRATORguardCLAUDE_PROJECT_DIRopenSyncwx→w(break atomicity)Mutation 8 is worth reading. The six-process CLI race did not kill it. Node startup dominates, so each child's read of the existing holder serializes it long before the create — the
O_CREAT|O_EXCLwindow is never reached, and the test passes with a non-atomic write. Rather than leave a test claiming more than it proves, the integration test is relabelled to claim only end-to-end mutual exclusion, and two unit tests now drivewriteAtomicdirectly from the state both acquirers reach after passing the read check. Those kill the mutation.The AC-6 gate reads a region-scoped extract of §0.3 (not the whole file) and throws if the extract comes back under 200 chars, so a broken extractor fails loudly instead of making every assertion vacuous.
Second round: gaps closed after initial review
Each item below was flagged as an open gap on the first pass and has since been closed.
1.
session_idwas an unverified assumption — now verified, and it exposed a bug. Captured a livePreToolUsepayload by briefly instrumenting the hook. The envelope carriessession_id(confirmed), and the capture happened to record two distinct sessions in one checkout — this session and a concurrent/fullsolve 899— a live instance of the very scenario this issue addresses. The instrumentation was reverted; the main checkout's hook is byte-identical toHEAD.2. A false positive that would have blocked legitimate work (found via that payload). The payload also carries
cwd, which revealed the guard was deciding "is this the main checkout?" fromCLAUDE_PROJECT_DIR. That names the project directory and stays pinned to the main checkout even while the agent's shell is in a worktree — sogit checkoutrunning legitimately inside a worktree was blocked. The guard's worst failure mode, and the whole point of the lock is to push sessions into worktrees. The old tests could not catch it: they setCLAUDE_PROJECT_DIRto the worktree, so project dir and cwd never diverged. Fixtures are now realgit initrepos with realgit worktree addchildren, and three cases pin the divergence (in-worktree allows, in-main blocks so the fix cannot degrade to always-allow, andcd <worktree> &&allows).3. Real-process concurrency. Three tests now spawn the built CLI concurrently — six sessions race and exactly one wins, the loser's refusal names the actual winner, and release hands the tree onward. These use async
spawn;spawnSyncinsidePromise.allwould have run the children sequentially and made the race theatre. Scope limitation documented above under mutation 8.4. The
buildLockedResultflake — diagnosed, not tolerated. It sits in theunitproject, which deliberately keeps vitest's 5s default because "a slow test is a real signal" there, but lazily imports the whole workflow package. Measured failing at 5.06s and passing at 1.38s on the same commit, purely with machine load. 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 covered: CI isubuntu-latestrunningnpm test, so the integration tests exercise the GNU fallback on every run.6. Merge regression caught by this branch's own gate. #899 and #904 landed on main mid-review. Merging them in surfaced two new abort paths in #899's Phase 1.5 that release the per-issue lock but not the checkout lock — unpaired, they would leak the working tree until the 6h TTL. The AC-6 release-contract assertion failed on exactly those, and both now release both locks. Conflicts in
bin/cli.tsandCHANGELOG.mdwere additive and both sides were kept.Risk assessment
git -C <worktree>,locks checkout clear).session_idis now empirically confirmed present in thePreToolUseenvelope, with aSEQUANT_ISSUEfallback and a test for its absence.🤖 Generated with Claude Code