Repository navigation
fix(spawn): pre-trust Claude workspaces before launch - #2343
karotkriss wants to merge 8 commits into
Conversation
Claude Code gates a first-time directory behind a per-folder workspace-trust dialog, and --dangerously-skip-permissions does not suppress it (verified live). fm-spawn.sh now pre-accepts that trust for the resolved worktree before every claude launch, covering both a fresh spawn and --relaunch, by writing hasTrustDialogAccepted=true into the exact <CLAUDE_CONFIG_DIR:-$HOME>/.claude.json the launched process reads. The write is lock-serialized against firstmate's own concurrent spawners and always goes through a read-modify-write-then- atomic-rename so a spawn can never corrupt the file or touch unrelated keys, including keys added by real claude processes writing the file concurrently. jq becomes a required tool for a claude-harness spawn, so it now joins firstmate's universal bootstrap toolchain (previously only required when Relay was opted in). Several existing spawn-driving tests inherited the developer's real $HOME or a PATH too narrow to see jq; both are fixed so the suite never touches the developer's real ~/.claude.json and jq is genuinely reachable where a claude-harness spawn now depends on it.
SC2016 for deliberate single-quoted nested bash -c scripts and SC2181 for a $? check that a direct if-condition replaces.
|
@kunchenguid Original Problem was simple, agents spawned on a new project could be stuck asking if he workspace is trusted and they can lose you time just sittings there. this would be catch by firstmate eventually but still not ideal. This should have firstmate be more autonamous |
|
@greptile review |
Confidence Score: 3/5This PR should not merge until Claude workspace trust requires an explicit captain opt-in rather than being granted automatically on every spawn. The changed spawn path writes Claude's trust acceptance flag for newly created or unreviewed worktrees without any authorization check, crossing the repository's explicit security-authority boundary. Files Needing Attention: bin/fm-spawn.sh, bin/fm-claude-trust-lib.sh, docs/configuration.md
|
| freshen_spawn_worktree_base "$WT" || exit 1 | ||
| fi | ||
|
|
||
| # Deterministically pre-accept Claude Code's per-folder workspace-trust dialog |
There was a problem hiding this comment.
Automatic workspace trust bypass
Every Claude spawn automatically records the resolved worktree as trusted without checking for a captain opt-in, bypassing Claude's workspace-trust decision and allowing newly created or otherwise unreviewed worktree content to launch in a trusted state.
Context Used: If there is a VISION.md file at the root of the re... (source)
Intent
Make bin/fm-spawn.sh pre-trust a claude worker's workspace so a crewmate/scout NEVER hangs on Claude Code's folder-trust dialog on a fresh worktree. Confirmed root cause: a claude worker spawned into a brand-new worktree sat frozen with an empty status log because Claude Code gates a first-time directory behind a workspace-trust dialog ('Is this a project you created or one you trust?'), and --dangerously-skip-permissions (used by the claude launch template) bypasses TOOL permissions only, not this folder-trust dialog - verified live. Claude Code stores per-folder trust in ~/.claude.json at projects[].hasTrustDialogAccepted = true.
Fix implemented: before launching a claude worker, fm-spawn.sh deterministically ensures its resolved worktree absolute path is already trusted, so no dialog can appear. New bin/fm-claude-trust-lib.sh pre-registers the worktree path into <CLAUDE_CONFIG_DIR:-$HOME>/.claude.json with hasTrustDialogAccepted=true (matching the minimal schema of a real untrusted-but-onboarded Claude Code project entry, verified against real ~/.claude.json). Done atomically and concurrency-safe: takes a lock (reusing bin/fm-wake-lib.sh's existing lock primitive, matching the CONFIG_INHERIT_LOCK convention already in fm-spawn.sh), does read-modify-write to a temp file plus atomic rename, and only ADDS/ensures the one project entry's trust - it never clobbers unrelated keys or other project entries. Handles the file being absent (creates a minimal entry) or malformed (refuses loudly rather than guessing how to repair, since rewriting content it cannot parse risks losing data a structural merge cannot see). Covers both the normal spawn path and the --relaunch path (the pre-trust call sits after WT is finalized for every KIND and RELAUNCH state). Applied ONLY when HARNESS=claude (exact string match, mirroring the existing CLAUDE_CONFIG_DIR-forwarding gate at the launch site) - muse, codex, opencode, pi, pi-signed, grok, kimi, cursor are explicitly out of scope and untouched.
Deliberate scope decisions from investigation: (1) I attempted to live-reproduce the trust dialog on the currently-installed Claude Code version (2.1.231) in fresh directories and could not - the dialog did not appear, likely because this specific version/account combination behaves differently than the originally-captured incident evidence (possibly captured on an earlier version like 2.1.223, referenced in a related open issue about a second 'Bypass Permissions mode' dialog). I decided to still ship the pre-trust fix as defense-in-depth since it is cheap, idempotent, and directly closes the documented failure mode regardless of version drift across machines/secondmates. I updated the harness-adapters skill doc to be honest about this and to clearly separate the folder-trust dialog (now pre-accepted, this fix's scope) from the separate bypass-permissions warning dialog (a different, later dialog tracked in a separate open issue, explicitly out of scope here - I did not touch it). (2) jq is now a hard, required dependency for any claude-harness spawn (used for safe JSON read-modify-write). I deliberately chose fail-closed: if jq is missing, the spawn is refused with a clear error rather than silently skipping the pre-trust step and reintroducing the exact hang this fix exists to prevent. Since jq was previously only required when Relay/FMX was opted in, I added jq to bin/fm-bootstrap.sh's universal COMMON_TOOLS list (and docs/configuration.md) so a captain missing it gets a loud, actionable diagnostic at every session start instead of a surprise spawn failure the first time they use claude. (3) While validating, I discovered and fixed a real ordering bug: acquiring the trust lock before the CLAUDE_CONFIG_DIR exists loops forever (the lock's owner-dir machinery cd's into the lock's parent to resolve it), so bin/fm-claude-trust-lib.sh now exposes fm_claude_trust_ensure_dir, which fm-spawn.sh calls to mkdir -p the config directory BEFORE acquiring the lock - mirroring the existing CONFIG_INHERIT_LOCK pattern already in the file (mkdir -p the target dir, then lock). (4) Making jq required, plus the new claude-trust write itself, exposed pre-existing test-isolation gaps: several existing tests that drive fm-spawn.sh with the claude harness never isolated the real /home/cmckay (so they were about to leak synthetic worktree paths into the developer's actual ~/.claude.json) or used a PATH too narrow to see jq. I fixed these test files (added HOME= pinning to the relevant spawn-driving helpers, extended narrowed BASE_PATH to include jq's real location, added jq to fake toolchains that assert bootstrap silence) rather than leaving the new dependency to silently break or pollute developer state - this is the smallest set of downstream test fixes needed to keep already-passing test behavior correct now that the dependency is real. I verified this cleanup thoroughly: I found and cleaned up actual pollution my own test runs left in the real ~/.claude.json during investigation, and confirmed a full run of the affected suites leaves it byte-identical afterward (module unrelated background telemetry keys Claude Code itself updates during a live session).
Proof delivered per the task's requirements: (1) cited the captured production incident evidence plus documented my own inconclusive live-reproduction attempt on the current version, being explicit about the discrepancy rather than fabricating a reproduction. (2) Live end-to-end proof: pre-trusted a brand-new git worktree path never present in the real ~/.claude.json using the exact library function fm-spawn.sh calls, then launched a real claude --dangerously-skip-permissions process into that directory via tmux and captured the pane - no trust dialog appeared, and the worker started processing its prompt immediately (captured transcript showing it answer and reach idle). Cleaned up the real ~/.claude.json afterward. (3) New tests/fm-claude-trust-lib.test.sh (7 cases, colocated per repo convention): creates the file and trusts a fresh worktree, proves the not-yet-existing-config-dir ordering fix prevents the lock-acquire hang, idempotency plus preservation of unrelated top-level keys and other project entries' own extra fields, refuses malformed JSON without touching it or leaving a temp file, 12 concurrent writers under the shared lock all land with no corruption or lost update and the file stays valid JSON, and refuses loudly (does not silently skip) when jq is unavailable. Also updated the .agents/skills/harness-adapters/SKILL.md claude section to reflect the new pre-accepted-by-default behavior and correctly separate it from the still-open bypass-permissions-dialog issue. Registered the new test file's family in bin/fm-test-run.sh (pure-contract-unit) rather than leaving it unclassified. bin/fm-lint.sh (shellcheck, pinned version) is clean across the whole repo, including two shellcheck findings (SC2016, SC2181) I fixed in the new test file after an earlier lint pass falsely read as clean due to truncated output on my end - not a real prior gap, just my own review diligence catching up. This is a firstmate shared-tracked-material change (bin/fm-spawn.sh, bin/fm-bootstrap.sh, bin/fm-test-run.sh, docs/, .agents/skills/); I followed the firstmate-coding-guidelines skill's decision tree, one-owner rule, and repo style rules (one sentence per line in tracked Markdown reflow, plain dash, no agent co-author, colocated tests named .test.sh).
What Changed
jqa universal bootstrap dependency and add documentation plus regression coverage for trust updates, concurrency, failure handling, spawn integration, and test isolation.Risk Assessment
✅ Low: The bounded compare-and-retry now detects intervening content changes, retries from fresh state, fails closed after five races, and honestly documents the unavoidable final check-to-rename window.
Testing
Validated target commit b0cb79f with focused trust-library, spawn-profile, relaunch, and bootstrap suites plus direct CLI transcripts. Fresh normal and relaunch paths pre-trusted their resolved worktrees before Claude launch, concurrent and external-writer cases preserved valid JSON, malformed configuration failed closed without launching, missing jq produced an actionable bootstrap diagnostic, and the worktree remained clean.
Evidence: Fresh Claude worktree spawn transcript
Evidence: Claude relaunch trust transcript
Evidence: Malformed Claude config refusal transcript
Evidence: Missing jq bootstrap diagnostic
Evidence: Claude trust library tests
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
🔧 **Review** - 3 issues found → auto-fixed (3) ✅
bin/fm-claude-trust-lib.sh:112- The required guarantee says the update is concurrency-safe and “never clobbers unrelated keys,” but this lock covers only Firstmate writers. A running Claude process can update.claude.jsonafter jq reads it and before this unconditional rename, causing either Claude's unrelated update or the new trust entry to be lost. Decide whether to narrow the guarantee to Firstmate-only concurrency or require coordination with Claude's own writes before merging.bin/fm-spawn.sh:2293-fm_lock_acquire_waitretries forever when the lock cannot be created. Becausefm_claude_trust_ensure_dirsucceeds for an existing but unwritable config directory, a permission error or unusable lock path hangs the spawn instead of producing the intended fail-closed error. Add a writable-path preflight or a bounded acquisition failure for this lock.bin/fm-claude-trust-lib.sh:70- The config directory and predictable temporary file are created using the ambient umask, and the rename replaces any existing.claude.jsonmode with the temporary file's mode. This can weaken a restrictive configuration file and, with a group-writable directory, permits pre-creation of the predictable temp path. Create the directory and a unique temp file with restrictive permissions, preserving an existing file's stricter mode.🔧 Fix: Harden Claude trust locking and file replacement
2 errors still open:
bin/fm-claude-trust-lib.sh:147- The required guarantee says the update is concurrency-safe and “never clobbers unrelated keys,” but the lock still covers only Firstmate writers. A running Claude process can update.claude.jsonafter jq reads it and before this rename, losing either Claude's unrelated update or the trust entry. Decide whether to narrow the guarantee to Firstmate-only concurrency or require coordination with Claude's writes.bin/fm-claude-trust-lib.sh:147- An existing.claude.jsonsymlink is followed by jq but then replaced bymv, destroying the symlink and leaving its target unchanged. Resolve and atomically update the target while preserving the link, or fail closed on symlinks.🔧 Fix: Refuse symlinked Claude trust configuration
1 error still open:
bin/fm-claude-trust-lib.sh:151- The required guarantee says the update is concurrency-safe and “never clobbers unrelated keys,” but the lock still covers only Firstmate writers. A running Claude process can update.claude.jsonafter jq reads it and before this rename, losing either Claude's unrelated update or the trust entry. Decide whether to narrow the guarantee to Firstmate-only concurrency or require coordination with Claude's writes.🔧 Fix: Retry raced Claude trust updates safely
✅ Re-checked - no issues remain.
✅ **Test** - passed
✅ No issues found.
Inspectedgit diff 88d0f2e2f8474334ed5ba85913d1295ea5fa6251..b0cb79f1dc16c5f182f14ce6f59ac84fe041ecbcfor the trust writer, spawn integration, bootstrap dependency, tests, and documentation.bash tests/fm-claude-trust-lib.test.shbash tests/fm-spawn-dispatch-profile.test.shbash tests/fm-control-relaunch.test.shbash tests/fm-bootstrap.test.shFocused isolated normal spawn through realbin/fm-spawn.shwith a never-seenCLAUDE_CONFIG_DIRand fake tmux transport; captured the resulting JSON and launch command.Focused isolatedbin/fm-spawn.sh --relaunchwith an absent trust file and recorded Claude harness; captured the resulting JSON and pane command.Focused malformed.claude.jsonspawn check; confirmed exit status 1, zero launch commands, explicit refusal, and byte-identical malformed content.Focused bootstrap run with jq removed from the isolated toolchain; confirmed the actionableMISSING: jqdiagnostic.Verifiedgit status --shortremained empty andHEADwas target commitb0cb79f1dc16c5f182f14ce6f59ac84fe041ecbc.✅ **Document** - passed
✅ No issues found.
🔧 **Lint** - 1 issue found → auto-fixed ✅
🔧 Fix: Suppress intentional ShellCheck false positives in trust tests
✅ Re-checked - no issues remain.
✅ **Push** - passed
✅ No issues found.