Repository navigation
fix(bin): stop claude spawn from overwriting a project's .claude/settings.local.json - #2673
Closed
doitdigital0495 wants to merge 2 commits into
Closed
doitdigital0495 wants to merge 2 commits into
doitdigital0495 wants to merge 2 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. Replacement PR with 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.
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 flag 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 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 "$WT/.claude" and the .git/info/exclude entry; (2) bin/fm-teardown.sh no longer rm -f's /.claude/settings.local.json at any of its four cleanup sites - that rm was unconditional and ran for EVERY harness, not just claude; (3) teardown's dirty check previously filtered '^?? .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 ' M', which never matched '^?? ', 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 Usage: claude [options] [command] [prompt]
Claude Code - starts an interactive session by default, use -p/--print for
non-interactive output
Arguments:
prompt Your prompt
Options:
--add-dir <directories...> Additional directories to allow tool
access to
--agent Agent for the current session. Overrides
the 'agent' setting.
--agents JSON object defining custom agents (e.g.
'{"reviewer": {"description": "Reviews
code", "prompt": "You are a code
reviewer"}}')
--allow-dangerously-skip-permissions Enable bypassing all permission checks
as an option, without it being enabled
by default. Recommended only for
sandboxes with no internet access.
--allowedTools, --allowed-tools <tools...>
Comma or space-separated list of tool names to allow (e.g. "Bash(git *)
Edit")
--append-system-prompt Append a system prompt to the default
system prompt
--autocompact <auto|tokens> Auto-compact window size (auto, or
100k–1M tokens)
--ax-screen-reader Render screen-reader friendly output
(flat text, no decorative borders or
animations).
--bg, --background Start the session as a background agent
and return immediately (manage with
claude agents)--bare Minimal mode: skip hooks, LSP, plugin
sync, attribution, auto-memory,
background prefetches, keychain reads,
and CLAUDE.md auto-discovery. Sets
CLAUDE_CODE_SIMPLE=1. Anthropic auth is
strictly ANTHROPIC_API_KEY or
apiKeyHelper via --settings (OAuth and
keychain are never read). 3P providers
(Bedrock/Vertex/Foundry) use their own
credentials. Skills still resolve via
/skill-name. Explicitly provide context
via: --system-prompt[-file],
--append-system-prompt[-file], --add-dir
(CLAUDE.md dirs), --mcp-config,
--settings, --agents, --plugin-dir.
--betas <betas...> Beta headers to include in API requests
(API key users only)
--brief Enable SendUserMessage tool for
agent-to-user communication
--chrome Enable Claude in Chrome integration
--cloud [description|session_id|url] Create a cloud session with the given
description, or attach to an existing
one by session ID or claude.ai/code URL
-c, --continue Continue the most recent conversation in
the current directory
--dangerously-skip-permissions Bypass all permission checks.
Recommended only for sandboxes with no
internet access.
-d, --debug [filter] Enable debug mode with optional category
filtering (e.g., "api,hooks" or
"!1p,!file")
--debug-file Write debug logs to a specific file path
(implicitly enables debug mode)
--disable-slash-commands Disable all skills
--disallowedTools, --disallowed-tools <tools...>
Comma or space-separated list of tool names to deny (e.g. "Bash(git *)
Edit")
--effort Effort level for the current session
(low, medium, high, xhigh, max)
--environment <environment_id> Create a new cloud session that runs on
the given self-hosted environment
(ccpool_...).
--exclude-dynamic-system-prompt-sections
Move per-machine sections (cwd, env info, memory paths, git status) from
the system prompt into the first user message. Improves cross-user
prompt-cache reuse. Only applies with the default system prompt (ignored
with --system-prompt). (default: false)
--fallback-model Enable automatic fallback to specified
model(s) when the default model is
overloaded or not available. Accepts a
comma-separated list to try each in
order. Re-tries the primary at the start
of each user turn. (only works with
--print)
--file <specs...> File resources to download at startup.
Format: file_id:relative_path (e.g.,
--file file_abc:doc.txt
file_def:img.png)
--fork-session When resuming, create a new session ID
instead of reusing the original (use
with --resume or --continue)
--forward-subagent-text Forward subagent text and thinking
blocks as assistant/user messages with
parent_tool_use_id set (only works with
--print and --output-format=stream-json)
--from-pr [value] Resume a session linked to a PR by PR
number/URL, or open interactive picker
with optional search term
-h, --help Display help for command
--ide Automatically connect to IDE on startup
if exactly one valid IDE is available
--include-hook-events Include all hook lifecycle events in the
output stream (only works with
--output-format=stream-json)
--include-partial-messages Include partial message chunks as they
arrive (only works with --print and
--output-format=stream-json)
--input-format Input format (only works with --print):
"text" (default), or "stream-json"
(realtime streaming input) (choices:
"text", "stream-json")
--json-schema JSON Schema for structured output
validation. Example:
{"type":"object","properties":{"name":{"type":"string"}},"required":["name"]}
--max-budget-usd Maximum dollar amount to spend on API
calls (only works with --print)
--mcp-config <configs...> Load MCP servers from JSON files or
strings (space-separated)
--model Model for the current session. Provide
an alias for the latest model (e.g.
'fable', 'opus', or 'sonnet') or a
model's full name (e.g.
'claude-fable-5').
-n, --name Set a display name for this session
(shown in the prompt box, /resume
picker, and terminal title)
--no-chrome Disable Claude in Chrome integration
--no-session-persistence Disable session persistence - sessions
will not be saved to disk and cannot be
resumed (only works with --print)
--output-format Output format (only works with --print):
"text" (default), "json" (single
result), or "stream-json" (realtime
streaming) (choices: "text", "json",
"stream-json")
--permission-mode Permission mode to use for the session
(choices: "acceptEdits", "auto",
"bypassPermissions", "manual",
"dontAsk", "plan")
--plugin-dir Load a plugin from a directory or .zip
for this session only (repeatable:
--plugin-dir A --plugin-dir B.zip)
(default: [])
--plugin-url Fetch a plugin .zip from a URL for this
session only (repeatable: --plugin-url A
--plugin-url B) (default: [])
-p, --print Print response and exit (useful for
pipes). Note: The workspace trust dialog
is skipped when Claude is run in
non-interactive mode (via -p, or when
stdout is not a TTY, e.g. piped or
redirected output). Only use this in
directories you trust. Settings files
that fail validation are silently
ignored in this mode (no error dialog is
shown).
--prompt-suggestions [value] Enable prompt suggestions. In print/SDK
mode, emits a prompt_suggestion message
after each turn with a predicted next
user prompt (choices: "true", "false",
"1", "0", "yes", "no", "on", "off",
preset: "true")
--remote-control [name] Start an interactive session with Remote
Control enabled (optionally named)
--remote-control-session-name-prefix
Prefix for auto-generated Remote Control session names (default: hostname)
--replay-user-messages Re-emit user messages from stdin back on
stdout for acknowledgment (only works
with --input-format=stream-json and
--output-format=stream-json)
-r, --resume [value] Resume a conversation by session ID, or
open interactive picker with optional
search term
--safe-mode Start with all customizations
(CLAUDE.md, skills, plugins, hooks, MCP
servers, custom commands and agents,
output styles, workflows, custom themes,
keybindings, and more) disabled — useful
for troubleshooting a broken
configuration. Admin-managed (policy)
settings still apply. Auth, model
selection, built-in tools, and
permissions work normally. Sets
CLAUDE_CODE_SAFE_MODE=1.
--session-id Use a specific session ID for the
conversation (must be a valid UUID)
--setting-sources Comma-separated list of setting sources
to load (user, project, local).
--settings Path to a settings JSON file or a JSON
string to load additional settings from
--strict-mcp-config Only use MCP servers from --mcp-config,
ignoring all other MCP configurations
--system-prompt System prompt to use for the session
--teleport [session] Resume a teleport session, optionally
specify session ID
--tmux Create a tmux session for the worktree
(requires --worktree). Uses iTerm2
native panes when available; use
--tmux=classic for traditional tmux.
--tools <tools...> Specify the list of available tools from
the built-in set. Use "" to disable all
tools, "default" to use all tools, or
specify tool names (e.g.
"Bash,Edit,Read").
--verbose Override verbose mode setting from
config
-v, --version Output the version number
-w, --worktree [name] Create a new git worktree for this
session (optionally specify a name)
Commands:
agents [options] Manage background agents
auth Manage authentication
auto-mode Inspect or reset auto mode classifier
configuration
doctor Check the health of your Claude Code
installation. Reads settings files in
the current directory without a trust
prompt. For a full checkup that can also
fix issues, run /doctor in a session.
gateway [options] Run the enterprise auth/telemetry
gateway
import [options] [source] Import config from another AI coding
agent into Claude Code
install [options] [target] Install Claude Code native build. Use
[target] to specify version (stable,
latest, or specific version)
mcp Configure and manage MCP servers
plugin|plugins Manage Claude Code plugins
project Manage Claude Code project state
setup-token Set up a long-lived authentication token
(requires Claude subscription)
ultrareview [options] [target] Run a cloud-hosted multi-agent code
review of the current branch (or a PR
number / base branch) and print the
findings
update|upgrade Check for updates and install if
available probe for --settings 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 $HOME/.kimi-code/config.toml edit is genuinely marker-delimited and atomic. One unrelated observation not fixed here: grok writes ~/.grok/hooks/fm-turn-end.{sh,json} 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.
What Changed
bin/fm-spawn.shnow writes the claude busy-event hooks tostate/<id>.claude-settings.jsonand passes it viaclaude --settings(omitted forkind=secondmate, which arms no busy contract), instead of writing<worktree>/.claude/settings.local.jsonwholesale and adding a.git/info/excludeentry;fm-control-lib.shreports the new state path as the claude wiring path.bin/fm-teardown.shno longerrm -fs<worktree>/.claude/settings.local.jsonat its four cleanup sites, drops the'^?? \.claude/'exclusion from the dirty-worktree check so anything under.claude/can refuse teardown, cleans up the new state file, and addsremove_legacy_claude_settingsto delete a pre-fix leftover only when it is untracked and contains firstmate's ownfm-busy-event.shcommand.tests/fm-claude-settings-live-e2e.test.sh(gated onFM_CLAUDE_SETTINGS_LIVE_E2E=1) wired into thelive-harness-optinfamily forbin/fm-spawn.shchanges;fm-busy-adapter-wiringasserts a tracked project settings file survives a real spawn byte for byte with--settingspointing outside the worktree;fm-teardowncovers survival of a tracked file, refusal on an untracked.claude/file, and legacy-leftover removal; evidence recorded indocs/verification/supervision.mdand the harness-adapters skill.Risk Assessment
✅ Low: Well-bounded fix that removes the worktree write entirely rather than mitigating it, root-caused at all four teardown sites plus the dirty-check filter, with both-direction regression tests and a gated live guard for the one vendor fact it rests on; no reachable path back to the reported failure was found.
Testing
Ran the targeted regression tests for the spawn and teardown halves plus the two other touched suites (all pass), proved both new regressions fail on the base commit and pass on the target, exercised the opt-in live guard against the installed claude 2.1.237 to confirm --settings hooks fire and merge rather than replace, and captured a CLI transcript of a real fm-spawn showing a project's tracked .claude/settings.local.json surviving byte for byte with a clean worktree, contrasted against the same run on the base commit where the file is overwritten and left modified. One failing teardown case (content-landed) reproduces identically on the untouched base commit and is unrelated to this change; no visual artifact applies since the surface is a shell CLI and its on-disk state.
Evidence: fm-spawn transcript after the fix: project settings preserved, worktree clean, hooks outside the worktree
Source: fm-spawn transcript after the fix: project settings preserved, worktree clean, hooks outside the worktree
== worktree .claude/settings.local.json (after spawn) == {"env":{"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS":"1"},"permissions":{"allow":["Bash(npm test)"]},"enabledPlugins":{"context7":true}} == git status --porcelain in the task worktree (after spawn) == (empty above == worktree clean) == claude launch command recorded by the fake tmux == --settings '.../home/state/demo-claude.claude-settings.json' == busy classifier driven by those out-of-worktree hooks == after arm: busy fm-spawn after UserPromptSubmit: busy claude-hook after Stop: idle claude-hookEvidence: Same fm-spawn on the base commit: project settings destroyed, worktree left dirty
Source: Same fm-spawn on the base commit: project settings destroyed, worktree left dirty
== worktree .claude/settings.local.json (after spawn) == {"hooks":{"UserPromptSubmit":[...fm-busy-event.sh...]}} <- project's env/permissions/enabledPlugins gone == git status --porcelain in the task worktree (after spawn) == M .claude/settings.local.jsonEvidence: Live claude 2.1.237 --settings merge guard
Source: Live claude 2.1.237 --settings merge guard
ok - claude 2.1.237 (Claude Code) loads --settings hooks from outside the workspace and merges them with the project's own all fm-claude-settings-live-e2e tests passedPipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-spawn.sh:1125- Busy-state hooks are now bound to the launch invocation (--settings) instead of a file Claude auto-discovers in the worktree. Firstmate's own paths are covered (fm-spawn --relaunch regenerates the launch; there is no auto-resume path that types a bareclaude), but if a worker or operator restarts Claude in the pane by hand (claude,claude --continue), the UserPromptSubmit/Stop/StopFailure/SessionEnd hooks are silently absent, so the busy record can stay stuck at its last value and the watcher gets no wake. Pre-fix the worktree file survived any restart. Worth one line in the harness-adapters skill's claude row.bin/fm-teardown.sh:1168- The new comment states that anything under .claude/ can now refuse teardown like any other dirty file. On any project a pre-fix firstmate ever spawned into, the oldexclude_path '.claude/settings.local.json'line is still in the project's shared .git/info/exclude and outlives teardown, so git status hides that one path repo-wide and it cannot refuse teardown there. The intent explicitly records this as a known caveat deliberately not addressed (no way to prove firstmate rather than the operator wrote a given exclude line), so this is a note on the residual scope, not a request to change the code.tests/fm-teardown.test.sh:885- Pre-existing failure in tests/fm-teardown.test.sh casecontent-landed: teardown should succeed when content is already in the default branch(expected exit 0, got 1). Verified identical on the untouched base commit 1cb900c (run from an extracted base tree), so it is not caused by this change. It matters here only because the suite aborts on first failure, so the three new .claude/ teardown cases never execute in a plain full-file run; I ran them via a trimmed copy of the same script instead.bin/fm-test-run.sh tests/fm-busy-adapter-wiring.test.sh(includes new casea claude spawn arms its hooks without writing anything into the project worktree) - passFail-before check: same new wiring test file run against the base commit tree (git archive 1cb900c) - fails withclaude spawn did not write hook settingsNew teardown casestest_teardown_leaves_the_projects_claude_settings_alone,test_untracked_claude_file_refuses_teardown,test_legacy_firstmate_claude_leftover_is_removedrun via a trimmed copy of tests/fm-teardown.test.sh - all passFail-before check: same three cases against base bin/fm-teardown.sh - fails withteardown deleted the project's own settings fileFM_CLAUDE_SETTINGS_LIVE_E2E=1 bash tests/fm-claude-settings-live-e2e.test.shagainst installed claude 2.1.237 - pass (hooks fire and merge, project file unchanged)Manual evidence demo: realbin/fm-spawn.sh(harness=claude) on a sandbox project tracking .claude/settings.local.json, capturing file before/after,git status --porcelain, the recorded launch command, and the busy classifier transitions; same demo replayed against the base commit for contrastbin/fm-test-run.sh tests/fm-control-relaunch.test.sh tests/fm-spawn-dispatch-profile.test.sh- passbin/fm-test-run.sh --list --family live-harness-optinand--list --changed --base 1cb900c- the new live guard is in the opt-in family and a spawn change re-selects it;--check-coveragereports FM_TEST_COVERAGE okbash tests/fm-teardown.test.shon the base commit tree - reproduces the samecontent-landedfailure, confirming it is pre-existingdocs/configuration.md:243- docs/configuration.md's operator-facing per-harness hook-install paragraph (lines ~243-249) names grok, Kimi, and Pi but has no claude line, so an operator reading it cannot see that claude's crew hooks now ride--settingsfromstate/<id>.claude-settings.json. Not stale (it never described claude), so left unchanged under scope discipline; a follow-up could add one sentence there pointing at the harness-adapters skill.✅ **Push** - passed
✅ No issues found.