Shared-checkout safety
Several agent sessions work in one git checkout at once, and a checkout has one HEAD and one index. A stack of hooks and two small tools keeps one session's branch switch, broad commit or push from landing on another session's work.
- What it is
- Five layers, each placed where a different tool can reach it: a start-up notice that offers a private worktree, a
PreToolUseguard on shell commands,commit-ownfor commits,push-mainfor the default branch, and a gitreference-transactionhook that no tool can skip. Rules in the global prompt cover what none of them can see. - What it isn't
- Not isolation. Sessions still share files on disk, and nothing stops two of them editing the same file. Not a lock manager either: apart from the push lock, every layer reacts to a command at the moment it runs.
- Why it exists
- Running five chats in one checkout is normal here. Each guard traces to a real loss: a
reset --hardthat wiped two sessions' uncommitted work, an--amendthat rewrote a peer's commit, and "twin pushes" that split local and remote history 96 commits to 50.
How it works
Any command that changes HEAD or the index changes them for every session in the checkout. If chat A switches branch, chat B's next edit lands on the wrong branch. If chat A runs git add ., chat B's half-finished files get staged with it. Each layer covers a different way in:
reset --hard has already rewritten the index and working tree.| Layer | Where it runs | What it does | On failure |
|---|---|---|---|
peer-session-notice | SessionStart | Says when another session has been active in this checkout in the last 15 minutes, and has the agent offer the operator a worktree with a suggested name, before any code work. It offers and never acts: moving a session's working directory unasked would be its own surprise. | Fails open; silent when alone |
peer-session-guard | PreToolUse on shell calls | Heartbeats this session's marker (at most once a minute). While a peer is live, denies 5 command shapes and asks before 11 more. Path-limited git, edits and tests are never gated. | Fails open |
commit-own | Called by the agent | Commits exactly the named paths from a private index and moves the branch with a compare-and-swap. --why writes the CAM intent note in the same call. | Exit 3 if a peer committed onto the same paths |
push-main | Called at wrap-up | The only sanctioned push of the default branch: lock, fetch, strictly-ahead check, scrub every outgoing commit, push by refspec, journal. | Exit 2 precondition, exit 3 gate refused |
Ref guard (githooks/reference-transaction) | Inside git, for every tool | Refuses a non-fast-forward move, or a deletion, of the default branch. Installed into other repos as a copy by bin/install-ref-guard. | Fails open unless it has positively seen a sideways move |
worktree-owner | PostToolUse, SubagentStop, SessionEnd | Records which sessions and subagents use each linked worktree, so the cleanup sweep removes a worktree when every user has ended instead of trusting an idle clock. | Never prints, never blocks |
What the guard denies and asks
The guard splits commands by whether git can undo them. Five shapes destroy a peer's uncommitted files, or switch off a protection, and no reflog brings that back, so they are denied outright while a peer is live:
git reset --hard,git clean(unless it is a dry run), and a whole-treecheckoutorrestoreof.or:/.- Setting
ALLOW_REF_REWRITE, the ref guard's override. An agent the ref guard refused could otherwise retry with the override, so setting it is left to the operator. git symbolic-ref refs/heads/<b> <other>. On git 2.43 that write is not a ref transaction, so the ref guard never sees it.
The other 11 are recoverable but reach across the whole checkout, so the guard asks first: branch switch, any reset, stash, clean, rebase/merge, forced branch moves and deletes, add -A/add ., commit -a, commit --amend, a manual ai-sync (which commits every dirty harness file), and a raw git push. Each reason names the safe alternative, for example "make a new commit with commit-own" for an amend.
The patterns are anchored to the start of a command segment and read quoted strings whole, so -m "never use --amend here" is a message rather than an amend, and grep push is not a push. Getting that right took fix rounds. One early pattern backtracked exponentially on long lines, and since this hook runs before every shell call, a slow regex costs every session.
commit-own
Plain git add plus git commit goes through the one index every session shares. commit-own never reads or writes that index to build a commit:
read-treeof HEAD into a private index file, add the named paths,write-tree,commit-tree.- Move the branch with a compare-and-swap
update-ref. If a peer committed in between and touched the same paths, it exits 3 and the agent rebuilds. A held ref lock is retried up to 3 times. - Sync the shared index only for entries that still equal the parent commit's, so a peer's staged hunk survives.
- Journal a
commitline to CAM, plus anoteline when--whywas given.
It also refuses a whole-path commit of a shared ledger (LESSONS.md, docs/plans/INDEX.md, the lessons status file) whose diff has more than one hunk, because peers' uncommitted rows would go in with yours. --content <path>=<file> commits a prepared version of just your rows instead. The working tree is never written, no remote is touched, and commit hooks do not run, so the pre-push hook lints those files later.
push-main
push-main exists because of twin pushes. Between 2026-09-27 and 2026-09-29, chats committed locally with commit-own, then built a copy of the same change on top of the remote and pushed the copy by sha. The local branch never learned about the copies. At the worst point the two histories read 96 50, and 37 of the remote's 50 commits were patch-identical to local ones. A single merge fixed it, with no force-push. push-main makes the bad shape impossible to type:
- A lock in the git common directory, so two chats cannot push at once. A lock older than 10 minutes counts as stale.
- Fetch, then push only when local is strictly ahead. A diverged branch exits with the merge recipe: never rebase, never force.
- Scrub every file version in every outgoing commit, not just the tip, for blocked names. A hit names the file, line, commit and the chat that wrote it, never the matched text. A fix commit does not clear a hit, because the push would still send the commit that introduced the name.
- Push only
refs/heads/<b>:refs/heads/<b>, then confirm origin holds exactly the scrubbed tip.
--preview lists the outgoing commits with the chat that wrote each, and ends with an offer: line (yes at 10 or more commits, or when origin last moved 30 or more minutes ago). The wrap-up workflow asks the operator only when the offer says yes, because a full pre-push run takes about two and a half minutes.
The ref guard
The ref guard exists because the hooks above are tool-specific. On 2026-09-22, in a product repo's shared checkout, an orchestration lane dispatched from Cursor ran git reset --hard and moved main onto another run's integration branch. For about 15 minutes main pointed at unreviewed work, and uncommitted state from other sessions was lost. The Claude Code guards were registered for Cursor too, and never fired: Cursor sends its hook payload in a different shape, so every guard read an empty command and stood down.
Two fixes followed. A shared payload reader (hooks/hook_io.py) now gives every guard both shapes. And a git reference-transaction hook refuses, in its prepared phase, any update that moves the default branch to a commit that does not contain the current tip. Git runs that hook whichever program issued the command. The protected branch is read from origin/HEAD, never hardcoded. The hook is live in a checkout every session shares, and a non-zero exit there would abort every commit for all of them, so it fails open on anything it has not positively identified as a sideways move. The SessionStart environment snapshot reports the guard as missing or stale in any repo where the installed copy has drifted.
Worktrees, the real exit
A linked worktree has its own HEAD and index, which removes most of the problem. Orchestration lanes get one automatically, and the start-up notice offers one to an interactive chat. Worktrees bring their own traps, each recorded after it cost a session:
- This repo uses
extensions.worktreeConfig, so each worktree needs its owncore.bareandcore.worktree. New worktrees get the first automatically but not the second, and the fix belongs in that worktree's config, never the shared one. Without it, a worktree's git commands act on the wrong tree. - Landing back on a busy
mainneeds the rebase and the fast-forward merge in one command. Run separately, another chat lands in between and--ff-onlyrefuses. - The task board is local-only and git-excluded, so it does not travel into a worktree. Anything that allocates an id there reads a stale counter. Board writes happen in the main checkout only.
The prose rules
The global instruction file has a "Shared checkouts" section with seven rules for what no hook can see. Three examples: commit only your own paths while a peer is live; after a failed commit, unstage your paths in the same turn, because they now sit in an index every peer shares; and set a private index per command (GIT_INDEX_FILE=$I git …), never with export. That last one graduated: guard-shell-status now denies an exported private index that outlives its command (see Hooks and guards).
AI engineering practices it demonstrates
- Defence in depth across tool boundaries. Prompt rule, agent hook, purpose-built CLI and VCS hook. Each sits at a layer the one above it cannot cover, and the lowest layer binds every tool, including a human at a terminal.
- Graduated responses. Deny what no reflog can recover, ask before what is recoverable but checkout-wide, stay silent on path-limited work. Every response carries a reason that names the safe command.
- Guards gate only while a peer is live. A lone session pays nothing but a heartbeat.
- Optimistic concurrency for agents.
commit-ownandpush-mainuse compare-and-swap and a lock instead of trusting that nobody moved the branch. - An agent may not switch off a guard that refused it. The override variable is itself a denied command shape.
- Testing against each tool's real payload. The Cursor incident came from a guard that had only ever been fed Claude Code's shape.
- Offer, don't act. The notice proposes a worktree; the operator decides.
Capabilities
| Capability | Detail |
|---|---|
| Peer liveness | Per-worktree session markers written at start and heartbeated on every shell call. A marker older than 15 minutes counts as dead. |
| Command gating | 5 deny rows and 11 ask rows, anchored to command segments, with linear prechecks to keep the regexes off commands that cannot match. |
| Own-path commits | Private index, CAS ref update, partial shared-index sync, shared-ledger hunk check, CAM journal line. |
| Default-branch push | Lock, strictly-ahead check, full-range scrub, refspec-only push, post-push verification, preview with an offer line. |
| VCS-level protection | Non-fast-forward and delete refusal on the default branch; a pre-push hook that refuses any push deleting a remote ref. |
| Worktree lifecycle | Owner records per worktree, read by the sweep that removes finished ones. |
| Cross-tool reach | Notice and guard are registered for Claude Code and Cursor. The ref guard covers every tool. |
Benefits
- Parallel chats in one checkout became routine rather than a gamble. The guide that documents this was written on a day five ran at once.
- Each guard closes the exact shape of a recorded loss, and each has its own regression test file. I have not measured recurrence since, so read it as "the known paths are shut" and nothing stronger.
- Agents get the safe command in the refusal itself, so a deny costs one round trip rather than operator attention.
- The ref guard needs no agent cooperation and works the same from Claude Code, Cursor or a plain terminal.
Limits
Every layer above git pattern-matches command text and fails open. A crash, a malformed marker or a wrapper the regex does not expect lets a command through silently, and a silent guard does not prove you are alone. Two sessions editing the same file without committing collide, and nothing here sees it.
- Known regex misses. The push row only understands
-Cand-cbetweengitand the subcommand.git --no-pager push,/usr/bin/git pushandenv git pushget through, as does a dry-run flag placed after--. - One bad marker disables the guard for everyone. A marker with a timestamp missing its zone, or JSON that is not an object, raises inside the liveness check. The hook fails open, so the guard goes quiet for every session in the checkout.
- Liveness is a 15-minute window. A chat idle for longer reads as gone, and the end-of-session sync of a closing peer can then commit that chat's in-progress harness files.
- The ref guard fires late.
reset --hardrewrites the index and working tree before the ref transaction, so the refusal saves the branch and not the uncommitted files. The message says so. commit-ownhas a documented race: its shared-index sync reads and then writes, and git has no compare-and-swap for index entries.- Copilot is not covered. The notice and guard are registered for Claude Code and Cursor only.
Roadmap
| Item | Why it matters | Status |
|---|---|---|
| End-of-session sync must never commit | Today it can sweep an idle peer's in-progress files into an unexplained sync commit | correctness |
| Harden the liveness check against malformed markers | One bad file currently switches the guard off for the whole checkout | correctness |
| Lane worktrees and the live board | A lane worktree has no board of its own, so the task tool walks up to the main checkout's and writes there | correctness |
| Wrapper forms in the push and deny rows | --no-pager, absolute paths, env/exec prefixes | backlog |
commit-own --content leaves a phantom deletion | The path can show as deleted in the shared tree, and a later broad commit records it | backlog |
Stale-lock race in push-main | Two pushers replacing the same stale lock can delete each other's | backlog |
| Sweep keeps lane worktrees after a landing | The lane's throwaway commit is never an ancestor of main, so the sweep refuses to remove it | backlog |
| Peer and CAM hooks on Copilot, Windows-safe | Extends the notice and guard beyond Claude Code and Cursor | planned |
Sources
hooks/peer-session-notice.py,hooks/peer-session-guard.py(PEER_LIVE_SECONDS = 15 * 60,HEARTBEAT_SECONDS = 60,DENY_WHILE_PEER5 rows,GLOBAL_STATE11 rows, counted by import).bin/commit-ownandbin/push-main, linked fromhooks/(ATTEMPTS = 3,STALE_AFTER = 600,OFFER_AT_COMMITS = 10,OFFER_AFTER_MIN = 30).hooks/worktree-owner.py,hooks/hook_io.py,hooks/env-snapshot.py(ref-guard state).githooks/reference-transaction,githooks/pre-push,githooks/refuse-delete-push.py,bin/install-ref-guard.docs/workflow/git-workflows.md: one checkout, committing safely, worktrees, the twin-push split and its fix.docs/plans/shared-checkout-guard/plan.md: the 2026-09-22 incident and the ref-guard design.global/CLAUDE.md, section "Shared checkouts";LESSONS.md(L55, the amend rule).- Tests:
hooks/tests/test_peer_session_guard.py,test_peer_session_notice.py,test_worktree_owner.py;bin/tests/test_commit_own.py,test_push_main.py,test_ref_guard.py,test_install_ref_guard.py. - Task board: open items for the sync commit, marker parsing, lane worktrees, regex wrappers,
commit-own, the push lock and Copilot support.