Skip to content

fix(spawn): pre-trust Claude workspaces before launch - #2343

Closed
karotkriss wants to merge 8 commits into
kunchenguid:mainfrom
karotkriss:fm/fm-spawn-claude-trust-preaccept
Closed

karotkriss wants to merge 8 commits into
kunchenguid:mainfrom
karotkriss:fm/fm-spawn-claude-trust-preaccept

Conversation

@karotkriss

Copy link
Copy Markdown
Contributor

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

  • Pre-trust each resolved Claude worktree before both initial launches and relaunches, preventing workers from hanging on the folder-trust dialog.
  • Add an atomic, fail-closed Claude trust-store updater that preserves unrelated configuration, serializes Firstmate writers, retries detected external changes, and rejects unsafe files or paths.
  • Make jq a 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
BEFORE: config_dir_exists=no trust_file_exists=no
SPAWN: warning: /tmp/fm-spawn-evidence.4b7x1X/evidence-claude-fresh/home/data/evidence-claude-fresh/brief.md records no delivery contract line (scaffolded before ship briefs recorded one); launching on the explicit --mode no-mistakes - confirm its definition of done matches
spawned evidence-claude-fresh harness=claude kind=ship mode=no-mistakes yolo=off window=firstmate:fm-evidence-claude-fresh worktree=/tmp/fm-spawn-evidence.4b7x1X/evidence-claude-fresh/wt
RESOLVED_WORKTREE: /tmp/fm-spawn-evidence.4b7x1X/evidence-claude-fresh/wt
{"trusted":true,"project_entry":{"allowedTools":[],"mcpContextUris":[],"mcpServers":{},"enabledMcpjsonServers":[],"disabledMcpjsonServers":[],"hasTrustDialogAccepted":true,"projectOnboardingSeenCount":0,"hasClaudeMdExternalIncludesApproved":false,"hasClaudeMdExternalIncludesWarningShown":false}}
LAUNCH_COMMAND: CLAUDE_CONFIG_DIR='/tmp/fm-spawn-evidence.4b7x1X/evidence-claude-fresh/claude-config-never-seen' env -u CURSOR_AGENT -u CURSOR_INVOKED_AS CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false claude --dangerously-skip-permissions "$('/home/cmckay/.no-mistakes/worktrees/80aee654c94f/01KZYJ1C6H547P0Y826R2P0NS8/bin/fm-operational-input.sh' encode launch-brief < '/tmp/fm-spawn-evidence.4b7x1X/evidence-claude-fresh/home/data/evidence-claude-fresh/brief.md')"
Evidence: Claude relaunch trust transcript
BEFORE: trust_file_exists=no recorded_harness=claude
RELAUNCH: warning: /tmp/fm-control-relaunch.WMOgOf/relaunch-evidence-3869/home/data/evidence-relaunch/brief.md records no delivery contract line (scaffolded before ship briefs recorded one); launching on the explicit --mode no-mistakes - confirm its definition of done matches
spawned evidence-relaunch harness=claude kind=ship mode=no-mistakes yolo=off window=fmses:fm-evidence-relaunch worktree=/tmp/fm-control-relaunch.WMOgOf/relaunch-evidence-3869/wt
RESOLVED_WORKTREE: /tmp/fm-control-relaunch.WMOgOf/relaunch-evidence-3869/wt
{"trusted":true}
PANE_LITERALS:
unset TRACEPARENT; env -u CURSOR_AGENT -u CURSOR_INVOKED_AS CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION=false claude --dangerously-skip-permissions "$('/home/cmckay/.no-mistakes/worktrees/80aee654c94f/01KZYJ1C6H547P0Y826R2P0NS8/bin/fm-operational-input.sh' encode launch-brief < '/tmp/fm-control-relaunch.WMOgOf/relaunch-evidence-3869/home/data/evidence-relaunch/brief.md')"
Evidence: Malformed Claude config refusal transcript
EXIT_STATUS: 1
SPAWN_OUTPUT:
warning: /tmp/fm-spawn-malformed-evidence.Rga75i/evidence-claude-malformed/home/data/evidence-claude-malformed/brief.md records no delivery contract line (scaffolded before ship briefs recorded one); launching on the explicit --mode no-mistakes - confirm its definition of done matches
fm-claude-trust: /tmp/fm-spawn-malformed-evidence.Rga75i/evidence-claude-malformed/claude-config/.claude.json is not valid JSON; refusing to touch it
error: could not pre-trust '/tmp/fm-spawn-malformed-evidence.Rga75i/evidence-claude-malformed/wt' for claude; refusing to spawn a worker that would hang on the folder-trust dialog
LAUNCH_COMMAND_COUNT: 0
CONFIG_AFTER_REFUSAL: { malformed
Evidence: Missing jq bootstrap diagnostic
BOOTSTRAP_WITH_JQ_REMOVED_FROM_TOOLCHAIN:
MISSING: jq (install: brew install jq  # or the platform's package manager)
Evidence: Claude trust library tests
ok - fm_claude_pretrust_worktree: creates .claude.json and trusts a brand-new worktree
ok - fm_claude_pretrust_worktree: uses private unique files and preserves stricter permissions
ok - claude trust setup: unusable config and lock paths fail in bounded time
ok - fm_claude_trust_ensure_dir: a not-yet-existing CLAUDE_CONFIG_DIR is created before locking, not after (no hang)
ok - fm_claude_pretrust_worktree: idempotent, flips only the target entry's trust flag, and never touches unrelated content
fm-claude-trust: /tmp/fm-claude-trust-lib.G25NPb/malformed/.claude.json is not valid JSON; refusing to touch it
ok - fm_claude_pretrust_worktree: refuses malformed JSON and leaves it byte-for-byte untouched
fm-claude-trust: /tmp/fm-claude-trust-lib.G25NPb/symlink/config/.claude.json is a symlink; refusing to replace it
fm-claude-trust: /tmp/fm-claude-trust-lib.G25NPb/symlink/config/.claude.json is a symlink; refusing to replace it
ok - fm_claude_pretrust_worktree: refuses valid and broken symlinks without touching them
ok - fm_claude_pretrust_worktree: retries external changes and fails closed after five races
ok - fm_claude_pretrust_worktree: 12 concurrent writers under the shared lock all land, with no corruption or lost update
ok - fm_claude_pretrust_worktree: refuses loudly when jq is unavailable instead of silently skipping
# all fm-claude-trust-lib tests passed

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.json after 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_wait retries forever when the lock cannot be created. Because fm_claude_trust_ensure_dir succeeds 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.json mode 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.json after 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.json symlink is followed by jq but then replaced by mv, 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.json after 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.

  • Inspected git diff 88d0f2e2f8474334ed5ba85913d1295ea5fa6251..b0cb79f1dc16c5f182f14ce6f59ac84fe041ecbc for the trust writer, spawn integration, bootstrap dependency, tests, and documentation.
  • bash tests/fm-claude-trust-lib.test.sh
  • bash tests/fm-spawn-dispatch-profile.test.sh
  • bash tests/fm-control-relaunch.test.sh
  • bash tests/fm-bootstrap.test.sh
  • Focused isolated normal spawn through real bin/fm-spawn.sh with a never-seen CLAUDE_CONFIG_DIR and fake tmux transport; captured the resulting JSON and launch command.
  • Focused isolated bin/fm-spawn.sh --relaunch with an absent trust file and recorded Claude harness; captured the resulting JSON and pane command.
  • Focused malformed .claude.json spawn 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 actionable MISSING: jq diagnostic.
  • Verified git status --short remained empty and HEAD was target commit b0cb79f1dc16c5f182f14ce6f59ac84fe041ecbc.
✅ **Document** - passed

✅ No issues found.

🔧 **Lint** - 1 issue found → auto-fixed ✅
  • ⚠️ linter found issues (exit code 1)

🔧 Fix: Suppress intentional ShellCheck false positives in trust tests
✅ Re-checked - no issues remain.

✅ **Push** - passed

✅ No issues found.

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.
@karotkriss

Copy link
Copy Markdown
Contributor Author

@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

@karotkriss

Copy link
Copy Markdown
Contributor Author

@greptile review

@greptile-apps

greptile-apps Bot commented Aug 23, 2026

Copy link
Copy Markdown

Confidence Score: 3/5

This 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

Security Review

The automatic trust grant bypasses an explicit security decision for every Claude worktree without the captain opt-in required by the repository vision.

Reviews (1): Last reviewed commit: "no-mistakes: apply CI fixes" | Re-trigger Greptile

Comment thread bin/fm-spawn.sh
freshen_spawn_worktree_base "$WT" || exit 1
fi

# Deterministically pre-accept Claude Code's per-folder workspace-trust dialog

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 security 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)

@karotkriss

Copy link
Copy Markdown
Contributor Author

Closing as superseded: main now pre-registers Claude workspace trust at spawn through bin/fm-claude-trust.sh (#3944, #3663), which covers this change.

@karotkriss karotkriss closed this Sep 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant