Skip to content

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

Closed

Description

@admarble

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, an npx sequant run, or another /fullsolve in 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:

  • /spec and /assess run in the main repo by contract.
  • /merger, sequant merge, and /fullsolve's post-PR cleanup-worktree.sh mutate 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_MS override — 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 under SEQUANT_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

Activity

  1. added
    enhancement
    on Aug 6, 2026
  2. admarble commented on Aug 6, 2026

    @admarble
    ContributorAuthor

    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:

    1. Outright refusal is factually wrong for this repo. The issue's own scope section lists legitimate main-checkout mutators: /spec and /assess run in the main repo by contract; /merger, sequant merge, and cleanup-worktree.sh mutate 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.
    2. AC-2 mandates holder identity. It requires the loser be "refused with a message naming the holding session and its issue." Naming a holder requires a holder record — i.e. a lock, or something isomorphic to one. Detection alone cannot satisfy AC-2 as written.

    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 checkout Bash calls, not sequant TypeScript. The incident trace is agent shell activity:

    12:49:53 checkout: feature/10-distribution-measurement -> fix/issue-023-cloud-egress
    

    Sequant's own TS does branch-mutating git almost exclusively inside worktrees (git -C <worktree> rebase|branch -D in worktree-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.sh is 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 and git reset --hard), and it already receives per-session identity on stdin.

    Rejected sub-alternative: widening LockManager to string keys

    The issue's design sketch anticipates widening lockPathFor, acquire, release, list and held from number to string, and calls that "the bulk of the work." It is avoidable. A sibling CheckoutLock in the same module reuses the already-exported pure primitives (classifyStaleness, defaultIsPidAlive, resolveLocksDir, resolveMaxLockAgeMs, isOrchestratorMode) without touching the numeric type. That keeps the blast radius off status.ts, merge.ts, resume.ts and run-orchestrator.ts, which all pass real issue numbers to check().

    LockListing turns out to have exactly one consumer (src/commands/locks.ts:92), so rendering a non-numeric holder in locks list is 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

    AC Note
    AC-1 Meta-AC (record a decision). Satisfied by this comment.
    AC-2 Measurable. "Branch-mutating" needs an enumerated set — pinned below.
    AC-3 Measurable (message content assertion).
    AC-4 Precise — names the three existing mechanisms.
    AC-5 Precise.
    AC-6 Measurable (text assertion across 3 mirrors).
    AC-7 Precise, and names the mutation-result requirement from CLAUDE.md.

    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.

    Metric Value Status
    Feature count 2 (lock primitive + hook guard) ⚠️
    AC items 7 ⚠️
    Directory spread 4 real + 2 mirror sets ⚠️

    Verdict: ⚠️ SCOPE_WARNING — quality loop enabled. Spread is inflated by mandatory 3-way mirroring of pre-tool.sh and fullsolve/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.lock with issue: 23 → When session B (issue 10) runs git checkout feature/10-x with 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 to pid+hostname if 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.lock past SEQUANT_MAX_LOCK_AGE_MS (or same-host dead PID) → When acquired → Then cleared and re-acquired.
    Assumptions: Reuses classifyStaleness rather 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.md in 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

    1. src/lib/locks/types.ts: add CheckoutLockFileSchema (LockFileSchema fields + issue: number, sessionId: string optional), CHECKOUT_LOCK_FILENAME = "checkout.lock".
    2. src/lib/locks/checkout-lock.ts: CheckoutLock class — acquire, release, check, clear. Reuses classifyStaleness, resolveLocksDir, resolveMaxLockAgeMs, isOrchestratorMode. Same O_CREAT|O_EXCL atomicity. Export formatCheckoutLockedMessage() producing the AC-3 actionable text.
    3. src/lib/locks/index.ts: export the new surface.

    Phase 2 — CLI

    1. src/commands/locks.ts: locksCheckoutCommand with acquire|release|check|clear subactions, --json, --issue, --session-id. Extend locksListCommand to render the checkout holder as a distinct row (list() currently drops non-numeric filenames — leave that filter alone, query the checkout lock separately).
    2. bin/cli.ts: wire sequant locks checkout <action>.

    Phase 3 — Hook enforcement (3 mirrors, byte-identical)

    1. .claude/hooks/pre-tool.sh (+ hooks/, templates/hooks/): extract session_id from INPUT_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-session checkout.lock is fresh.

    Phase 4 — Docs + AC-6 text

    1. Rewrite Phase 0.3 in fullsolve/SKILL.md × 3 dirs.
    2. CHANGELOG entry.

    Phase 5 — Tests

    1. 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 tests need the .integration. infix or they land in the unit project's 5s timeout.
      • Every gate test mutation-verified, result recorded in the PR body.

    Rule Touchpoints

    AC Touchpoint Note
    AC-2/3 .claude/hooks/pre-tool.sh + hooks/ + templates/hooks/ byte-identical today (35415 b) — must stay so
    AC-6 {.claude,templates,}/skills/fullsolve/SKILL.md:255 identical line in all 3

    Design Review

    1. Where does this logic belong? Lock state in src/lib/locks/ beside its per-issue sibling; enforcement in pre-tool.sh, the only layer that observes every session's git commands.
    2. Simplest correct approach? A second lock file + one hook guard. Rejected: widening LockManager's key type (5 consumers, no payoff), and a sentinel numeric key (parseIssue rejects <= 0; opaque on disk).
    3. Existing pattern followed? LockManager for the lock; the force-push / git reset --hard guards for the hook block; the OrchestratorRenderer no-op convention for AC-5.
    4. What would a senior reviewer challenge? "Why not one lock class?" — answered above (blast radius). "Isn't shell staleness a drift hazard (PM_CONFIG.yarn.ciInstall uses Yarn 2+ --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

    1. Does PreToolUse stdin carry session_id? Recommendation: assume yes, verify in exec, fall back to pid+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."
    2. Should /spec and /assess acquire 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 /spec that 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; /verify after exec to exercise the CLI and hook for real.


    Label Review

    Current: enhancement
    Recommended: add no-browser-test
    Reason: no UI surface; makes the /test skip explicit rather than incidental.

  3. added
    planned
    no-browser-test
    on Aug 6, 2026
  4. admarble commented on Aug 6, 2026

    @admarble
    ContributorAuthor

    /fullsolve Complete

    Issue: #901
    PR: #903
    Status: READY_FOR_MERGE

    AC Coverage

    AC Verdict Evidence
    AC-1 — design decision recorded with rationale MET The plan comment above; PR description restates it
    AC-2 — second session refused, message names holder + issue MET pre-tool.sh guard; 12 integration assertions; live CLI demo
    AC-3 — refusal says how to proceed MET Names the worktree, the git -C escape, and locks checkout clear
    AC-4 — stale recovery matches existing semantics MET CheckoutLock delegates to classifyStaleness; hook mirrors all 3 branches; 7 parity cases
    AC-5 — orchestrator/MCP no-op MET Class, CLI, and hook all stand down under SEQUANT_ORCHESTRATOR
    AC-6 — Phase 0.3 text precise MET Rewritten in all 3 skill dirs; 18 region-scoped gate assertions
    AC-7 — integration test + recorded mutation result MET 28 integration tests; 6 mutations recorded in the PR body

    Progress

    Phase Iterations Status
    Spec 1/1 Complete
    Exec 1/1 Complete (+1 follow-up commit, see below)
    Test — Skipped (no-browser-test; no UI surface)
    QA 1/2 Complete

    Quality metrics

    • Tests: 18 unit + 28 integration + 18 gate = 64 new, all passing; 151 locks-consumer tests passing
    • Build, lint, lint:skill-sync (44/44), lint:skill-calls (0 violations): clean
    • Type issues: none

    Two findings worth recording

    A real bug, caught during exec. The first staleness implementation parsed startedAt with BSD date -j -f, which parses in local time while startedAt is 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 with TZ=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 and classifyStaleness to identical verdicts.

    Risk assessment

    • Likely failure mode: a false positive blocking legitimate work. Mitigated by a narrow pattern set and 6 explicit allow-path tests, but the segment matcher is not a full shell parser. Blast radius is a recoverable refusal that names its own escape hatch.
    • Not tested: real two-terminal concurrency (simulated via crafted lock files driving the real hook binary); the GNU date branch runs only in CI.
    • Residual: session identity comes from session_id in the hook envelope (the field capture-tokens.sh:24 already reads). A SEQUANT_ISSUE fallback 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 /fullsolve did not create a worktree on this run either — it was created explicitly — so #899 reproduces.


    Ready for human review and merge.

  5. added a commit that references this issue on Aug 6, 2026
  6. admarble commented on Aug 6, 2026

    @admarble
    ContributorAuthor

    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 bug

    The previous comment listed "does the PreToolUse envelope actually carry session_id?" as an unverified assumption. Captured a live payload by briefly instrumenting the hook:

    keys: ["cwd","effort","hook_event_name","permission_mode","prompt_id",
           "session_id","tool_input","tool_name","tool_use_id","transcript_path"]
    

    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?" from CLAUDE_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 a git checkout running 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_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 still blocks (so the fix cannot degrade to always-allow), and cd <worktree> && git checkout allows.

    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 (openSync wx → 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 — the O_CREAT|O_EXCL window 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 writeAtomic directly from the state both acquirers reach after passing the read check. Those kill the mutation.

    4. The buildLockedResult flake — diagnosed, not tolerated

    It 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. 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 date branch — already covered

    CI is ubuntu-latest running npm 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.sh failure — 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.ts and CHANGELOG.md were 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

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

    8 mutations recorded, each killing exactly its target. AC coverage remains 7/7 MET. Full detail in #903.

  7. added 4 commits that reference this issue on Aug 7, 2026
  8. added a commit that references this issue on Aug 25, 2026
  9. added a commit that references this issue on Sep 9, 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

    enhancementno-browser-testplanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions