Repository navigation
fix(bin): keep claude busy hooks out of the project worktree - #2681
Closed
doitdigital0495 wants to merge 4 commits into
Closed
doitdigital0495 wants to merge 4 commits into
doitdigital0495 wants to merge 4 commits into
Conversation
The claude branch wrote its per-task busy-state hooks wholesale into <worktree>/.claude/settings.local.json. On a project that tracks that path, the spawn destroyed the project's committed settings for the life of the task and left the tracked file permanently modified, which then blocked teardown and re-escalated the finished task on every watcher pass. Follow the grok/kimi/pi precedent and keep the hooks out of the worktree entirely: they now live in state/<id>.claude-settings.json and reach the worker through claude's own --settings flag. Verified live on Claude Code 2.1.237 that --settings hooks fire and MERGE with the project's own settings rather than replacing them, so a project's committed hooks keep working. Teardown no longer rm -f's that project-owned path, and its dirty check no longer ignores everything untracked under .claude/ - firstmate writes nothing there, so anything present belongs to the project or the worker and must be able to refuse teardown. A narrow, provably-firstmate-only removal cleans up leftovers from tasks already under way. Regression tests cover both directions: the project's tracked settings survive a spawn with the worktree clean and the hooks armed, and teardown leaves .claude/ exactly as it found it.
Author
|
Closing: firstmate fixes are being landed on the fork instead of upstream. This PR was opened automatically by the validation pipeline, which is still registered with this repository as its PR base. Replacement carrying the same branch and commits: doitdigital0495#2 |
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.
Intent
Stop firstmate from destroying a project's tracked .claude/settings.local.json.
The defect, observed 2026-08-20: spawning a Claude crewmate writes the busy-event hooks into /.claude/settings.local.json, and it writes the file WHOLESALE. On the cosmic-show-hub project that file is TRACKED and had real content: a CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS env entry, a permissions.allow list, and an enabledPlugins entry for context7. The spawn replaced all of it with just the hooks block. Two consequences, both real: (1) the project's committed settings are silently destroyed in that worktree for the life of the task; (2) because the file is tracked, every spawn leaves the worktree permanently dirty, which then blocks fm-teardown.sh after the work has merged, producing an endless stale-wake loop where the watcher re-escalated the finished task every few minutes until it was cleared by hand.
What to build: firstmate must be able to install its hooks without destroying content it does not own. Two acceptable designs were named: (a) merge firstmate's hooks into the existing file, preserving every key firstmate does not own, and restore the original on teardown, safe when the file is absent, present-and-empty, malformed, or read-only; or (b) follow the existing Grok/Kimi precedent and keep the hooks outside the worktree entirely so no project file is touched at all, which removes the whole class of bug rather than mitigating it. The choice had to be argued from what Claude Code actually supports, not from preference. Whatever was built, teardown must leave the worktree exactly as it found it, because the pooled-worktree contract depends on it. The task also required checking whether the same wholesale-write pattern exists anywhere else in the spawn path for any harness, and reporting what was found. Definition of done: the no-mistakes pipeline through a green PR, regression tests for both the preservation and the clean teardown, and a note on whether any other harness had the same flaw.
Decisions made while doing the work, which a reviewer reading only the diff would not know:
Design chosen: option (b), hooks outside the worktree, argued from a live probe rather than preference. Claude Code's documented --settings flag (documented as "Path to a settings JSON file or a JSON string to load additional settings from") loads additional settings from an arbitrary path. Verified live on Claude Code 2.1.237 in a throwaway workspace that had its own .claude/settings.local.json with a Stop hook: running claude --dangerously-skip-permissions --settings <external.json> -p "say hi" created all three marker files - the project's own Stop hook, plus the Stop and UserPromptSubmit hooks supplied only through --settings. So --settings MERGES with the project's settings rather than replacing them. That makes the merge-into-the-file design strictly worse: it would still touch a project file, still need restore-on-teardown, still need absent/empty/malformed/read-only handling, and would still leave a tracked file dirty mid-task. Firstmate now writes zero files into the worktree for claude, matching what grok, kimi and pi already do.
Root cause was deliberately fixed in all three places it manifested, not just the reported one: (1) bin/fm-spawn.sh's claude branch now writes state/.claude-settings.json and passes it via --settings, dropping the mkdir -p of $WT/.claude and the .git/info/exclude entry; (2) bin/fm-teardown.sh no longer removes /.claude/settings.local.json at any of its four cleanup sites - that removal was unconditional and ran for EVERY harness, not just claude; (3) teardown's dirty check previously filtered untracked paths under .claude/, which silently discarded any untracked file a worker wrote anywhere under .claude/. That exclusion is now removed entirely, so anything under .claude/ belongs to the project or the worker and can refuse teardown like any other dirty file. The reported symptom came from the tracked case: git status shows a modified marker, which never matched the untracked-only filter, so teardown refused and the watcher re-escalated forever.
Deliberate scope decisions: a one-time migration helper remove_legacy_claude_settings was added to teardown, because a task already under way at update time still has firstmate's pre-fix file sitting in its worktree, hidden from git status by the exclude entry the old spawn also wrote, and its stale hooks would then fire for the next task in a pooled worktree. It removes the file ONLY when it is untracked AND contains firstmate's own fm-busy-event.sh command, so a tracked or project-authored file is provably never touched. A per-spawn probe of claude --help for the --settings flag was written and then deliberately REMOVED: an unsupported flag makes claude refuse to start, so the spawn readiness gate already fails loudly, and the probe would have added a subprocess per spawn plus a second place to keep in sync. Secondmates arm no busy contract, so the launch template omits --settings for kind=secondmate rather than pointing it at a file that does not exist.
Verification, following firstmate's own harness-dependent-check rule that a vendor-emitted fact must be proven end to end against the real harness and not against a stub: a new opt-in live guard tests/fm-claude-settings-live-e2e.test.sh (gated on FM_CLAUDE_SETTINGS_LIVE_E2E=1, self-skipping) exercises the installed binary and fails naming its version, and bin/fm-spawn.sh was added to the live-harness-optin family in bin/fm-test-run.sh so a spawn change re-selects it. The dated evidence and the refresh command are recorded in docs/verification/supervision.md.
Regression tests cover both directions as required: in tests/fm-busy-adapter-wiring.test.sh a project that tracks .claude/settings.local.json with real content (landed on the default branch so the spawn's base refresh brings it in) survives a real fm-spawn byte for byte with git status empty, the launch command carries --settings pointing outside the worktree, and the hooks still drive the busy classifier. In tests/fm-teardown.test.sh: the tracked file survives teardown unchanged; an untracked file under .claude/ now refuses teardown instead of being silently discarded; and a pre-fix firstmate leftover is removed while a neighbouring project file under .claude/ is not.
Audit result for the "does this exist elsewhere" requirement: no other harness has this flaw. opencode, grok, kimi, muse, cursor and pi all write either firstmate-named files (.fm-grok-turnend, .fm-kimi-turnend, fm-busy-state.js) or nothing inside the worktree at all; kimi's config.toml edit under the user's home is genuinely marker-delimited and atomic. One unrelated observation not fixed here: grok writes its global turn-end hook files non-atomically on every spawn without the validation guard kimi has.
Known caveat deliberately not addressed: the old exclude_path call appended .claude/settings.local.json to each project's SHARED .git/info/exclude, which outlives teardown and hides a project's own untracked settings file from git status repo-wide. It is not auto-removed because there is no way to prove firstmate wrote a given exclude line rather than the operator.
Pre-existing test failures on this machine, present on the untouched base commit and unrelated to this change, deliberately left alone rather than reaching into firstmate's herdr/secondmate safety code: fm-teardown's herdr-child-preflight case (herdr 0.8.0 installed), fm-secondmate-harness's crew-harness sweep case, and fm-test-run's ruby-missing YAML check. bin/fm-lint.sh passes; actionlint is not installed locally so workflow lint was skipped there.
Firstmate repo conventions that were followed and should not be flagged as omissions: knowledge was routed per the firstmate-coding-guidelines placement tree, so exact mechanics live in bin/fm-spawn.sh's own header rather than in AGENTS.md, situational adapter facts live in the harness-adapters skill, and dated empirical evidence lives in docs/verification/supervision.md; AGENTS.md was deliberately left unchanged because this change adds no always-loaded contract. bin/fm-doc-audience-check.sh passes.
DELIVERY NOTE (2026-08-20): the captain decided firstmate fixes land on his fork doitdigital0495/firstmate, not upstream kunchenguid/firstmate. The first run of this work opened upstream PR 2673, which was closed with a pointer to the replacement; a hand-created fork PR (doitdigital0495#2) cannot pass the repo required check "PR must be raised via no-mistakes", which demands the deterministic ## Pipeline signature section only the pipeline writes. This run must therefore raise the PR itself against the fork main branch, which is now synced to upstream main 1cb900c. Do not hand-write that signature.
What Changed
bin/fm-spawn.shnow writes the claude busy-state hooks tostate/<id>.claude-settings.jsonand hands them to the launch via--settings(new__CLAUDESETTINGS__placeholder), instead of overwriting<worktree>/.claude/settings.local.jsonand adding a.git/info/excludeentry; the hook set is generated from the sharedFM_BUSY_CLAUDE_HOOK_EVENTSlist added inbin/fm-busy-lib.sh, the flag is omitted forkind=secondmate, and a raw launch command no longer arms the busy contract at all since nothing guarantees it carries--settings.bin/fm-teardown.shstops unconditionally deleting<worktree>/.claude/settings.local.jsonat all four cleanup sites, drops the^?? \.claude/exclusion from the dirty-worktree check so any untracked file under.claude/can refuse teardown, addsremove_legacy_claude_settingsto clear only a pre-fix leftover that is untracked and matches firstmate's full hook shape, and removesstate/<id>.claude-settings.jsonalongside the other per-task state files..claude/settings.local.jsonsurviving spawn and teardown byte for byte (tests/fm-busy-adapter-wiring.test.sh,tests/fm-teardown.test.sh), plus an opt-in live guardtests/fm-claude-settings-live-e2e.test.sh(gated onFM_CLAUDE_SETTINGS_LIVE_E2E=1) wired into the live-harness opt-in family inbin/fm-test-run.sh; documents the--settingsmerge evidence indocs/verification/supervision.mdand the harness-adapters skill.Risk Assessment
✅ Low: The change is well-bounded and removes an entire class of data loss by keeping firstmate's claude hooks outside the worktree, with regression tests covering both preservation and clean teardown; the remaining items are a narrow gap in the migration's ownership proof and one stale doc sentence, neither of which blocks merge.
Testing
Exercised the real fm-spawn and fm-teardown scripts against a sandbox project that tracks .claude/settings.local.json, on both the target and the base commit. On the target the tracked file survives a spawn byte for byte, the worktree stays clean, the hooks are loaded from a firstmate-owned file outside the worktree via --settings and still drive the busy classifier, and teardown leaves the file untouched, refuses on a worker-written untracked .claude/ file, and removes only firstmate's own pre-fix leftover. The same checks fail on base 1cb900c, reproducing the reported defect exactly. The opt-in live guard confirmed against the installed claude 2.1.237 that --settings merges with the project's own settings. Two fm-teardown content-fallback cases fail on this machine, but they fail identically on the untouched base commit and are unrelated; because the harness aborts on first failure, the new claude cases were run from an out-of-worktree copy with those two skipped. No visual artifact applies - this change is CLI/filesystem behavior with no rendered surface - so evidence is captured as CLI transcripts.
Evidence: Target commit: real spawn leaves the project's tracked settings and the worktree untouched
Source: Target commit: real spawn leaves the project's tracked settings and the worktree untouched
--- project's committed .claude/settings.local.json (before spawn) --- {"env":{"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS":"1"},"permissions":{"allow":["Bash(npm test)"]},"enabledPlugins":{"context7":true}} --- worktree .claude/settings.local.json (AFTER spawn) --- {"env":{"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS":"1"},"permissions":{"allow":["Bash(npm test)"]},"enabledPlugins":{"context7":true}} --- git -C <worktree> status --porcelain (AFTER spawn) --- (empty above = worktree clean) --- claude launch command captured from the tmux spawn --- --settings '<state>/busy-cl-3.claude-settings.json'Evidence: Base commit 1cb900c: same spawn destroys the tracked settings and dirties the worktree (reported defect)
Source: Base commit 1cb900c: same spawn destroys the tracked settings and dirties the worktree (reported defect)
--- worktree .claude/settings.local.json (AFTER spawn) --- {"hooks":{"UserPromptSubmit":[...fm-busy-event.sh...]},"Stop":[...],"StopFailure":[...],"SessionEnd":[...]}} --- git -C <worktree> status --porcelain (AFTER spawn) --- M .claude/settings.local.jsonEvidence: Teardown leaves the worktree exactly as it found it
Source: Teardown leaves the worktree exactly as it found it
EVIDENCE 1 tracked settings: teardown exit 0, file identical before/after EVIDENCE 2 untracked .claude/agents/reviewer.md: teardown exit 1, "REFUSED: worktree ... has uncommitted changes.", file still present EVIDENCE 3 pre-fix firstmate leftover: teardown exit 0, .claude/ now contains only project-note.mdEvidence: Live vendor-fact guard against installed claude
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-spawn.sh:2374- Raw-launch-command spawns whose command basename isclaude(the documented unverified-adapter escape hatch at fm-spawn.sh:1200-1206) no longer get busy hooks. Thecase "$HARNESS" in claude*)wiring block still writes state/<id>.claude-settings.json and the arm block at line 2336 still mints a busy generation seeding busy/fm-spawn, but the operator-supplied LAUNCH is used verbatim and contains no--settings, so nothing ever loads those hooks: the turn never closes to idle and state/<id>.turn-ended is never touched, leaving the task permanently busy to the watcher. Previously the file lived at <worktree>/.claude/settings.local.json, which Claude auto-loads regardless of launch flags, so this path worked.pihas the same shape pre-existing (its extension rides-e __PIEXT__in the template only), so this may be an accepted class rather than an oversight - decide whether to append--settingsto a raw claude command, skip arming when the launch lacks the placeholder, or warn at spawn time.🔧 Fix: stop arming claude busy contract on raw launch commands
2 infos still open:
bin/fm-teardown.sh:2445- remove_legacy_claude_settings runs at 2445/2459/2248, but validate_worktree_teardown_safety already ran at 2385 and the .claude/ untracked filter was removed at 1165. The migration therefore only reaches a pre-fix leftover that git status cannot see. That holds for the normal case (the old spawn wrote the info/exclude entry in the same block, and info/exclude resolves to the shared common dir for a linked worktree, which is exactly what tests/fm-teardown.test.sh:990 models). If that exclude line is ever absent - the old exclude_path silently returned 0 whenevergit rev-parse --git-path info/excludeproduced nothing - the leftover shows as?? .claude/settings.local.json, teardown refuses, and the migration it needs never runs, which is the same endless stale-wake loop this branch is fixing. Running remove_legacy_claude_settings before the safety gate would close it; its untracked-AND-contains-fm-busy-event.sh gate already makes it safe to run early.bin/fm-teardown.sh:1148- The migration's ownership proof isgrep -q 'fm-busy-event.sh', which matches any untracked .claude/settings.local.json that merely mentions that command - e.g. a captain's own local settings in a firstmate checkout that wires an fm-busy-event.sh hook by hand. Such a file would be deleted rather than preserved. Reachability is narrow (it must also be hidden from the dirty gate above, or teardown refuses first) and the alternative gates are no stronger, so this is worth knowing rather than changing; a tighter proof would be matching the exact hook shape fm-spawn wrote (the four-event UserPromptSubmit/Stop/StopFailure/SessionEnd object) instead of a bare command substring.🔧 Fix: tighten legacy claude settings ownership proof in teardown
3 infos still open:
bin/fm-teardown.sh:1169- remove_legacy_claude_settings now proves ownership with four whole-file greps, but it never proves the file contains ONLY firstmate's hooks. A pre-fix spawn wrote exactly {"hooks":{...4 entries...}} and nothing else, so an untracked settings file that carries the four firstmate busy hooks AND additional project keys (permissions.allow, env, enabledPlugins) is still deleted wholesale. Two secondary looseness points in the same loop: the greps are whole-file, so key and command are never correlated to the same hook entry, and--event stopis a prefix of--event stop-failure, so the Stop-event proof is satisfied by the StopFailure entry alone. A dependency-free tightening that matches what the spawn actually emits: require the file to be a single{"hooks":{...}}object with exactly the four keys and no other top-level key, and anchor the event match (--event stop "/--event stop 2>) so it cannot be satisfied by a sibling event.docs/verification/supervision.md:214- The doc still describes the pre-tightening gate: "removes a leftover pre-fix file only when it is untracked AND carries firstmate's ownfm-busy-event.shcommand". Commit 6e74e5c changed the proof to require firstmate's busy-event command bound to ALL FOUR events of FM_BUSY_CLAUDE_HOOK_EVENTS; a bare fm-busy-event.sh substring is now explicitly not sufficient. Anyone reading supervision.md to decide whether their hand-written settings file is at risk gets the wrong (more alarming) answer. Update the sentence to name the four-event shape and FM_BUSY_CLAUDE_HOOK_EVENTS as the shared source of truth.bin/fm-teardown.sh:1190- Dropping\.claude/from the dirty-check filter is deliberate and stated in the intent, so this is a note rather than an objection. Operational consequence worth knowing: any untracked file a worker leaves under .claude/ (Claude Code writing settings.local.json on a permission/plugin change, a worker creating .claude/agents/*.md, scratch notes) now refuses teardown, which is the same refuse-then-watcher-re-escalates loop this branch exists to end - only now triggered by worker output instead of firstmate's own. It fails in the safe direction (refuse, never delete) and tests/fm-teardown.test.sh:test_untracked_claude_file_refuses_teardown pins it, so no change is requested; flagging only so the escalation path is expected rather than diagnosed as a regression later.✅ **Test** - passed
✅ No issues found.
bin/fm-test-run.sh tests/fm-busy-adapter-wiring.test.sh(all cases pass, including the newa claude spawn arms its hooks without writing anything into the project worktree)bin/fm-test-run.sh tests/fm-teardown.test.sh- stopped at the pre-existingcontent-landedfailure, so the four new claude cases were re-run from an out-of-worktree copy of HEAD with only the two pre-existing failing invocations skipped:teardown leaves a project's tracked .claude/settings.local.json exactly as it found it,an untracked file under .claude/ refuses teardown instead of being silently discarded,teardown removes only the pre-fix hook file firstmate itself wrote under .claude/,teardown preserves a hand-written settings file that merely wires an fm-busy-event.sh hook- all passFail-before-fix check: ran the newtest_claude_spawn_never_touches_the_projects_settingsandtest_teardown_leaves_the_projects_claude_settings_aloneagainst a scratch checkout of base1cb900c- both fail (spawn replaced the tracked file with the hooks blob and leftM .claude/settings.local.json)Pre-existing-failure baseline:bash tests/fm-teardown.test.shon a scratch checkout of base1cb900creproduces bothcontent-landedandcontent-stale-reffailures unchangedFM_CLAUDE_SETTINGS_LIVE_E2E=1 bash tests/fm-claude-settings-live-e2e.test.sh- live guard against installed claude 2.1.237, passesbin/fm-test-run.sh tests/fm-control-relaunch.test.sh tests/fm-spawn-dispatch-profile.test.sh- pass (cover the relocated harness wiring path in fm-control-lib.sh)Evidence capture: instrumented out-of-worktree copies of the spawn and teardown tests to dump the actual settings file content,git status --porcelain, worktree.claude/listing and the captured claude launch command before/after a realbin/fm-spawn.shandbin/fm-teardown.shrundocs/configuration.md:243- The leftover .git/info/exclude residue from the pre-fix spawn (a project's own untracked .claude/settings.local.json stays hidden from git status repo-wide) is recorded only in docs/verification/supervision.md, an evidence surface. Operators reading docs/configuration.md's per-harness hook-install section get no pointer to it. Out of scope for this change; a one-line pointer from configuration.md to the supervision.md section would close it without duplicating the fact.✅ **Push** - passed
✅ No issues found.