Skip to content

feat(locks): checkout-scoped lock for the shared working tree (#901) - #903

Merged
admarble merged 6 commits into
mainfrom
feature/901-feat-locks-per-issue-locks-give-no-mutual-excl
Aug 6, 2026
Merged

admarble merged 6 commits into
mainfrom
feature/901-feat-locks-per-issue-locks-give-no-mutual-excl

Conversation

@admarble

@admarble admarble commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

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 (/spec and /assess by 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 checkout Bash command, not sequant's TypeScript. The incident trace is agent shell activity, and sequant's TS mutates git almost exclusively via git -C <worktree> (see worktree-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 from number to string, which the issue anticipated as "the bulk of the work." Avoided. A sibling CheckoutLock reuses the already-exported pure primitives (classifyStaleness, defaultIsPidAlive, resolveLocksDir, resolveMaxLockAgeMs, isOrchestratorMode) without touching the numeric type, keeping the blast radius off status.ts, merge.ts, resume.ts and run-orchestrator.ts. LockListing turned out to have exactly one consumer, so rendering a non-numeric holder in locks list was localized. Trade-off accepted: the O_CREAT|O_EXCL write (~30 lines) is duplicated rather than generalized.

What landed

  • src/lib/locks/checkout-lock.ts — CheckoutLock + formatCheckoutLockedMessage. .sequant/locks/checkout.lock is deliberately non-numeric so LockManager.list() skips it.
  • sequant locks checkout <acquire|release|check|clear>; locks list renders the checkout holder as its own row.
  • pre-tool.sh guard (all 3 mirrors, byte-identical) — the enforcing half.
  • /fullsolve Phase 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 (.git is 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 -f to parse startedAt. BSD date -j -f parses in local time while startedAt is 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 with TZ=UTC on the BSD branch (date -u -d on the GNU/CI branch), plus a regression test that asserts a 25h-old holder reads as stale in UTC, America/Los_Angeles and Asia/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_MS override" — 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 three classifyStaleness branches in the same order, using the kill -0 builtin (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 and classifyStaleness over the same matrix and assert identical verdicts.

Verification

Suite Result
checkout-lock.test.ts (AC-4, AC-5, atomicity) 20 passed
checkout-lock.integration.test.ts (AC-2/3/4/5/7) 33 passed
fullsolve-checkout-lock-skill.test.ts (AC-6) 18 passed
locks consumers + #899/#904 suites, post-merge 190 passed
build, lint, lint:skill-sync, lint:skill-calls, lint:skill-gates clean

CLI exercised end-to-end against the built dist/: free → acquire #23 → refuse #10 (exit 1, full message) → re-entrant re-acquire → locks list showing both lock kinds → clear refusing 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.

# Mutation Expected Result
1 Delete "not a general concurrency guarantee" from all 3 SKILL.md AC-6 fails 3 failed, 15 passed
2 Revert the TZ=UTC date fix AC-4 staleness fails 3 failed, 18 passed
3 Neuter the block (exit 2 → exit 0) AC-2 enforcement fails 8 failed, 13 passed
4 Drop the SEQUANT_ORCHESTRATOR guard AC-5 fails 1 failed, 20 passed
5 Drop the "how to clear" remedy line AC-3 fails 1 failed, 20 passed
6 Remove the same-host dead-PID branch parity case fails 1 failed, 27 passed
7 Revert cwd resolution to CLAUDE_PROJECT_DIR worktree cases fail 2 failed, 28 passed
8 openSync wx → w (break atomicity) atomicity fails first attempt: 33/33 still green — see below; after adding deterministic tests: 2 failed, 18 passed

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_EXCL window 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 drive writeAtomic directly 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_id was an unverified assumption — now verified, and it exposed a bug. Captured a live PreToolUse payload by briefly instrumenting the hook. The envelope carries session_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 to HEAD.

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?" from CLAUDE_PROJECT_DIR. That names the project directory and stays pinned to the main checkout even while the agent's shell is in a worktree — so git checkout running 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 set CLAUDE_PROJECT_DIR to the worktree, so project dir and cwd never diverged. Fixtures are now real git init repos with real git worktree add children, and three cases pin the divergence (in-worktree allows, in-main blocks so the fix cannot degrade to always-allow, and cd <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; spawnSync inside Promise.all would have run the children sequentially and made the race theatre. Scope limitation documented above under mutation 8.

4. The buildLockedResult flake — diagnosed, not tolerated. It sits in the unit project, 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 date branch. Already covered: CI is ubuntu-latest running npm 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.ts and CHANGELOG.md were additive and both sides were kept.

Risk assessment

  • Likely failure mode: a false positive blocking legitimate work. Mitigated by the narrow pattern set and 6 explicit allow-path tests, but the segment matcher is not a full shell parser — an unusual quoting form could in principle evade or trip it. The blast radius is a recoverable refusal that names its own escape hatch (git -C <worktree>, locks checkout clear).
  • Not tested: two humans in two real terminals. Concurrency is covered by racing real CLI processes and by driving the real hook binary, which is as close as an automated suite gets.
  • Residual: session_id is now empirically confirmed present in the PreToolUse envelope, with a SEQUANT_ISSUE fallback and a test for its absence.

🤖 Generated with Claude Code

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.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(locks): per-issue locks give no mutual exclusion on the shared working tree — checkout-scoped protection

1 participant