Repository navigation
feat(spawn): guard opencode crewmate writes to the assigned worktree - #68
Merged
Merged
Conversation
…ut escapes PC02/opencode crewmate sessions have twice written edits into the primary firstmate checkout instead of their assigned worktree (2026-09-03 token-burn-item10-no-self-resume, 2026-09-06 fm-relaunch-rebinds-pr-poll). Both times the stray primary-checkout copy was only caught by accident via git status. Mirror the existing fm-primary-pretool-check.js seatbelt pattern: fm-spawn.sh now writes a per-task .opencode/plugins/fm-worktree-guard.js plugin that throws in tool.execute.before for any write/edit/patch tool call whose target path resolves outside the task's assigned worktree, and for any bash command that references the primary checkout's own path. Throwing there is a verified way to block the tool call outright (fm-primary-pretool-check.js, verified 2026-07-09 against OpenCode 1.17.15). Add tests/fm-worktree-guard.test.sh: spawns a real opencode task and drives the generated plugin in a plain Node host, proving it refuses a write and a bash command resolving to a stand-in primary checkout while allowing one that stays inside the worktree. Investigated whether opencode's relaunch path could leak an absolute primary-checkout path (meta's project= field, PROJ_ABS) into the model's context around a relaunch; PROJ_ABS is used for tmux window/pane setup ahead of the worktree cd in the launch command. Inconclusive within this task's scope - flagging for a follow-up scout rather than guessing further, since the write-guard now makes any such leak inert regardless of its exact source. Co-Authored-By: Claude Sonnet 5 <[email protected]> Claude-Session: https://claude.ai/code/session_014HioDmqiKo9BmxPvLqyxCg
…th, drop bash arm
…d in architecture
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
Implement a write-guard against a confirmed, reproducible safety gap: a PC02/opencode worker running pc02-llamaswap/qwen3.6-35b-a3b-dispatch has twice independently written its edits to the PRIMARY firstmate checkout (~/firstmate) in addition to its own isolated worktree - once on 2026-09-03 (token-burn-item10-no-self-resume) and again on 2026-09-06 (fm-relaunch-rebinds-pr-poll, right after a relaunch from a wedge). Both times the primary's copy was caught by accident via git status and stashed/discarded; nothing was lost because the task's own worktree always had the legitimate copy too.
What Changed
bin/fm-spawn.shnow writes an.opencode/plugins/fm-worktree-guard.jsplugin into each opencode task worktree; itstool.execute.beforehook canonicalizes thefilePathofwrite/editcalls (resolving symlinks via the nearest existing ancestor) and throws unless the target lands under the task worktree or the task's owndata/<id>/report directory. The plugin path is added toexclude_path, anddocs/architecture.mddocuments the backstop plus its limits (shell writes and outward-pointing symlinks still pass).tests/fm-worktree-guard.test.shcovering the guard's allow/refuse behavior.fm-control-relaunchrendezvous waits move from a 2s budget to a sharedWAIT_TICKS(30s),fm-spawn-worktree-settleasserts onpane_current_pathpoll count instead of wall-clock elapsed time, andfm-tmux-agent-livenessbuilds a local C spinner for its stand-in symlink target — falling back to the system binary only after proving a renamed symlink stays alive, and skipping otherwise — so multi-call coreutils argv[0] dispatch cannot silently kill the panes.Risk Assessment
✅ Low: The change is a self-contained, additive opencode plugin plus a behavioral regression test; the fix-round canonicalization logic traces correctly on concrete in-worktree, outside, symlinked-prefix, and not-yet-existing-path inputs, and it matches the intent's stated containment goal.
Testing
Baseline
bin/fm-test-run.sh --changed --exclude-family real-herdr-gatedhad already passed; I re-ran the four test scripts this change touches (guard regression plus relaunch, worktree-settle, tmux-liveness) and all passed. For product-level evidence I spawned a real opencode task, captured the generated guard plugin, and drove its tool hook with the two confirmed incident paths in the primary firstmate checkout — both were hard-refused with a clear message naming the assigned worktree — while in-worktree writes, a not-yet-existing nested worktree path reached through a symlinked prefix, the brief-mandated$DATA/$ID/report.mdwrite, and a read-only bash command all passed through. No UI surface is involved, so the artifact is a CLI transcript plus the generated plugin.Evidence: Guard transcript: refused primary-checkout writes, allowed legitimate ones
Source: Guard transcript: refused primary-checkout writes, allowed legitimate ones
REFUSED write ~/firstmate/bin/fm-spawn.sh -> fm-worktree-guard: refused write outside the assigned worktree (.../demo/wt): ~/firstmate/bin/fm-spawn.sh REFUSED edit ~/firstmate/data/backlog.md -> fm-worktree-guard: refused edit outside the assigned worktree (.../demo/wt): ~/firstmate/data/backlog.md ALLOWED write .../demo/wt/src/change.md # inside assigned worktree ALLOWED write .../demo/wt/docs/new/notes.md # new nested dir in worktree ALLOWED write .../demo/home/data/demo/report.md # brief-mandated scout report ALLOWED bash cat ~/firstmate/AGENTS.md # read-only bash unaffectedEvidence: Generated guard plugin as written by fm-spawn into the task worktree
Source: Generated guard plugin as written by fm-spawn into the task worktree
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-spawn.sh:2884- The bash guard throws on ANY bash command whose text contains PRIMARY_ROOT, including read-only and execute-only commands. The crewmate brief itself instructs the worker to run absolute primary-checkout commands: bin/fm-brief.sh:632 tells it to run$FM_ROOT/bin/fm-ensure-agents-md.sh ., bin/fm-brief.sh:581 points at$FM_ROOT/bin/fm-context-usage.sh, and bin/fm-brief.sh:503 tells it to read$FM_ROOT/.agents/skills/captain-hold-lifecycle/SKILL.md. Concrete sequence: a PC02/opencode ship crewmate follows its own brief, runs~/firstmate/bin/fm-ensure-agents-md.sh .from inside its worktree, and the guard hard-refuses a command that writes nothing outside the worktree. Two secondary defects in the same predicate: the escape check isPRIMARY_ROOT !== WORKTREE_ROOT(exact equality), so a worktree nested under the primary root would make every legitimate command mentioning its own worktree path blocked; and PRIMARY_ROOT is embedded raw while WORKTREE_ROOT is realpath'd, so a symlinked prefix makes the two comparisons operate on different path forms. Narrowing this to write-intent detection versus dropping the bash arm entirely (the write/edit guard already covers the reproduced incident, which was tool-driven edits) is a behavior decision for the author.bin/fm-spawn.sh:2874- The guard accepts four extra spellings the intent does not require: tool namepatch, plus arg keyspathandfile_pathalongsidefilePath. OpenCode's write/edit tools passfilePath; thepatchtool carries its targets inside the patch payload, not afilePatharg, so thepatchbranch never fires and silently allows any escape through that tool while reading as if it is covered. Combined withinsideWorktreereturning true for a missing/non-string target, an unrecognized arg shape fails open. Smallest honest remedy is to narrow to the exact tool names and single arg key opencode actually uses and droppatchfrom the list, rather than hardening it; makingpatchgenuinely enforced would require parsing patch payloads, which extends the change beyond its stated intent.bin/fm-spawn.sh:2888- If the bash arm is kept, note it matches only the literal absolute primary path:~/firstmate/x,$HOME/firstmate/x,cd ~ && cd firstmate, or a relative../../firstmate/xall pass through unblocked. This is honest best-effort containment layered under the write/edit guard, not a bypass-proof control; recorded so the guard is not later trusted as complete.🔧 Fix: narrow opencode write-guard to write/edit filePath, drop bash arm
2 issues (1 error, 1 info) still open:
bin/fm-spawn.sh:2876- The guard throws on any write/edit whose filePath is outside the worktree, but the crewmate brief explicitly requires exactly one such write. bin/fm-brief.sh:457 states "the only files you may write outside it are the report and the status file below", and bin/fm-brief.sh:497 mandates "Write your findings to$DATA/$ID/report.md" (under the firstmate home's data/ dir, not the worktree), with :498 requiring the agent to verify it landed at that exact path. Concrete sequence: a scout task launched with the opencode exe gets this plugin installed (the opencode arm of fm-spawn.sh installs it unconditionally, independent of task mode); the crewmate finishes, calls thewritetool on ~/firstmate/data/<id>/report.md, and the guard throws — the task can never reach its Definition of done, and the only survivor of a scout run is lost. The status-file append is unaffected (it goes through bashecho >>), but the report does not. Remedy is a policy decision, not a mechanical repair: the guard needs an explicit allowlist for the task's own $DATA/$ID report path (fm-spawn.sh already knows that path and can interpolate it the same way it interpolates $WT), or the plugin must be installed only for ship-mode tasks. Which of those matches the author's containment intent is theirs to choose.bin/fm-spawn.sh:2867- insideWorktree realpaths only the dirname and re-appends the raw basename, so a symlink that lives inside the worktree and points at a file in the primary checkout resolves as inside and is allowed; the write then follows the link out. This is deliberate (realpathing the full target would reject any not-yet-created file), and no reported incident used a symlink — recorded so the guard is not later trusted as a complete boundary rather than best-effort containment layered under it.🔧 Fix: allow task report dir writes in opencode worktree guard
4 issues (3 warnings, 1 info) still open:
bin/fm-spawn.sh:2870- allowedTarget only realpaths the target's immediate dirname; when that dirname does not exist yet it falls back to the raw resolve(target), which is compared against a realpath'd WORKTREE_ROOT. Concrete sequence: fm-spawn records WT as the pane's raw path (bin/fm-spawn.sh:2663 assigns WT="$p", not p_real - the surrounding comment at :2641 explicitly acknowledges symlinked project prefixes on these setups). If any component of that path is a symlink, WORKTREE_ROOT is the canonical form while the agent's write tool passes the raw form. A write to a not-yet-existing nested dir inside its own worktree (e.g. $WT/docs/new/notes.md) then hits the catch branch, yields the raw uncanonical path, fails the startsWith check, and the guard hard-throws on a legitimate in-worktree write. Mechanical remedy inside the existing helper: walk up to the nearest existing ancestor, realpath that, and re-append the remaining segments, instead of realpathing only dirname.bin/fm-spawn.sh:2864- The allowlist admits the whole task data directory ($DATA/$ID), but the only outside-worktree write the intent and the brief require is the report: bin/fm-brief.sh:497 mandates$DATA/$ID/report.md, and the ship brief instead says "modify nothing outside it" (bin/fm-brief.sh:581). The broader root leaves sibling control state writable by the guarded agent - notably $DATA/$ID/brief.md, which fm-spawn reads and validates on relaunch (bin/fm-spawn.sh:1938-1949) - so a stray write-tool call can silently rewrite the task's own brief, exactly the class of accident this guard exists to stop. Strictly narrower form that satisfies the intent: allow the single exact path $DATA/$ID/report.md rather than the directory prefix. Scope of the allowlist is the author's call, hence ask-user.bin/fm-spawn.sh:2840- The opencode arm installs the plugin unconditionally for every KIND, including secondmate launches, where WT is not a disposable task worktree but the secondmate home itself (bin/fm-spawn.sh:1887 sets WT="$PROJ_ABS" for KIND=secondmate). The stated intent is scoped to PC02/opencode crewmate workers writing into the primary checkout instead of their isolated worktree; a persistent secondmate is a supervisor whose legitimate write surface is not bounded by its home directory, and any write/edit it makes outside that home now hard-throws. No intent requirement covers secondmates. Recommend gating the plugin write on the crewmate kinds (ship/scout) rather than hardening it for the secondmate case.bin/fm-spawn.sh:2879- The check only engages when args.filePath is a non-empty string; a missing or differently-shaped arg passes through unguarded. That is the deliberate narrow form the previous round settled on for opencode's actual write/edit tool shape - recorded so the guard is understood as best-effort containment layered under the brief's rules, not a complete boundary.🔧 Fix: canonicalize guard targets via nearest existing ancestor
1 info still open:
bin/fm-spawn.sh:2861- TASK_DATA_ROOT uses realRoot("$DATA/$ID"), which falls back to a raw resolve() when the directory does not exist, while report targets are fully canonicalized by canonicalize(). If $DATA sat behind a symlinked prefix and the task dir were absent, the allowlist entry would be uncanonical and the mandated report write would be refused. Not reachable in practice: fm-spawn validates $DATA/$ID/brief.md before launch, so the directory always exists at plugin-write time. Recorded only so the asymmetry is understood.🔧 **Test** - 1 issue found → auto-fixed ✅
bin/fm-test-run.sh --changed --exclude-family real-herdr-gated🔧 Fix: fix flaky timing and argv0-dispatch assumptions in three tests
✅ Re-checked - no issues remain.
bin/fm-test-run.sh --changed --exclude-family real-herdr-gatedbin/fm-test-run.sh tests/fm-worktree-guard.test.sh tests/fm-control-relaunch.test.sh tests/fm-spawn-worktree-settle.test.sh tests/fm-tmux-agent-liveness.test.sh— 4/4 scripts pass, 0 failuresManual end-to-end evidence: ran a real opencode spawn through the test fixtures, then loaded the generated.opencode/plugins/fm-worktree-guard.jsin a plain Node host and invoked itstool.execute.beforehook with the literal incident paths (~/firstmate/bin/fm-spawn.sh,~/firstmate/data/backlog.md) plus legitimate in-worktree, nested-new-dir, report, and bash cases✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.