Skip to content

feat(spawn): guard opencode crewmate writes to the assigned worktree - #68

Merged
sKeLe100 merged 6 commits into
mainfrom
fm/pc02-writeguard-worktree-isolation
Sep 6, 2026
Merged

sKeLe100 merged 6 commits into
mainfrom
fm/pc02-writeguard-worktree-isolation

Conversation

@sKeLe100

@sKeLe100 sKeLe100 commented Sep 6, 2026

Copy link
Copy Markdown
Owner

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.sh now writes an .opencode/plugins/fm-worktree-guard.js plugin into each opencode task worktree; its tool.execute.before hook canonicalizes the filePath of write/edit calls (resolving symlinks via the nearest existing ancestor) and throws unless the target lands under the task worktree or the task's own data/<id>/ report directory. The plugin path is added to exclude_path, and docs/architecture.md documents the backstop plus its limits (shell writes and outward-pointing symlinks still pass).
  • Adds tests/fm-worktree-guard.test.sh covering the guard's allow/refuse behavior.
  • Stabilizes three existing tests: fm-control-relaunch rendezvous waits move from a 2s budget to a shared WAIT_TICKS (30s), fm-spawn-worktree-settle asserts on pane_current_path poll count instead of wall-clock elapsed time, and fm-tmux-agent-liveness builds 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-gated had 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.md write, 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 unaffected

REFUSED  write ~/firstmate/bin/fm-spawn.sh
         -> fm-worktree-guard: refused write outside the assigned worktree (/tmp/fm-guard-evidence.z2TCGj/demo/wt): ~/firstmate/bin/fm-spawn.sh
REFUSED  edit  ~/firstmate/data/backlog.md
         -> fm-worktree-guard: refused edit outside the assigned worktree (/tmp/fm-guard-evidence.z2TCGj/demo/wt): ~/firstmate/data/backlog.md
ALLOWED  write /tmp/fm-guard-evidence.z2TCGj/demo/wt/src/change.md   # legitimate: inside assigned worktree
ALLOWED  write /tmp/fm-guard-evidence.z2TCGj/demo/wt/docs/new/notes.md   # legitimate: new nested dir in worktree
ALLOWED  write /tmp/fm-guard-evidence.z2TCGj/demo/home/data/demo/report.md   # legitimate: brief-mandated scout report
ALLOWED  bash  cat ~/firstmate/AGENTS.md   # read-only bash unaffected
Evidence: 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

// Write-guard for PC02/opencode crewmate sessions: refuses any edit or write
// tool call that would escape this task's assigned worktree or its own
// report directory. Reproduced twice
// in production (2026-09-03
// token-burn-item10-no-self-resume, 2026-09-06 fm-relaunch-rebinds-pr-poll)
// when a tool call resolved a path against the primary checkout instead of
// $WT; both times the primary checkout's stray copy was only caught by
// accident via git status. tool.execute.before can block by throwing
// (verified against fm-primary-pretool-check.js, 2026-07-09 against OpenCode
// 1.17.15).
import { realpathSync } from "node:fs";
import { resolve, dirname, basename } from "node:path";

const realRoot = (p) => {
  try {
    return realpathSync(p);
  } catch {
    return resolve(p);
  }
};
const WORKTREE_ROOT = realRoot("/tmp/fm-guard-evidence.z2TCGj/demo/wt");
// The crewmate brief mandates exactly one write outside the worktree: the
// task's own report under $DATA/$ID (bin/fm-brief.sh Definition of done).
const TASK_DATA_ROOT = realRoot("/tmp/fm-guard-evidence.z2TCGj/demo/home/data/demo");
const ALLOWED_ROOTS = [WORKTREE_ROOT, TASK_DATA_ROOT];

function canonicalize(target) {
  const abs = resolve(target);
  const trailing = [];
  let probe = abs;
  for (;;) {
    try {
      return resolve(realpathSync(probe), ...trailing);
    } catch {
      const parent = dirname(probe);
      if (parent === probe) return abs;
      trailing.unshift(basename(probe));
      probe = parent;
    }
  }
}

function allowedTarget(target) {
  const real = canonicalize(target);
  return ALLOWED_ROOTS.some((root) => real === root || real.startsWith(root + "/"));
}

export const FmWorktreeGuard = async () => {
  return {
    "tool.execute.before": async (input, output) => {
      const tool = input?.tool;
      const args = output?.args || {};
      if (tool === "write" || tool === "edit") {
        const target = args.filePath;
        if (typeof target === "string" && target && !allowedTarget(target)) {
          throw new Error(
            "fm-worktree-guard: refused " + tool + " outside the assigned worktree (" +
              WORKTREE_ROOT + "): " + target
          );
        }
      }
    },
  };
};
- Outcome: 🔧 1 issue found → auto-fixed ✅ across 2 runs (55m41s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • 🚨 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 is PRIMARY_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 name patch, plus arg keys path and file_path alongside filePath. OpenCode's write/edit tools pass filePath; the patch tool carries its targets inside the patch payload, not a filePath arg, so the patch branch never fires and silently allows any escape through that tool while reading as if it is covered. Combined with insideWorktree returning 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 drop patch from the list, rather than hardening it; making patch genuinely 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 ~ &amp;&amp; cd firstmate, or a relative ../../firstmate/x all 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 the write tool 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 bash echo &gt;&gt;), 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 ✅
  • 🚨 tests failed with exit code 1
  • 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-gated
  • bin/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 failures
  • Manual end-to-end evidence: ran a real opencode spawn through the test fixtures, then loaded the generated .opencode/plugins/fm-worktree-guard.js in a plain Node host and invoked its tool.execute.before hook 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.

sKeLe100 and others added 6 commits September 6, 2026 04:57
…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
@sKeLe100
sKeLe100 merged commit 4de3dec into main Sep 6, 2026
13 checks passed
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