Skip to content

fix(bin): key primary-scope guard on physical location, not inherited env - #22

Merged
sKeLe100 merged 4 commits into
mainfrom
fm/primary-guard-env-leak-fix
Aug 26, 2026
Merged

sKeLe100 merged 4 commits into
mainfrom
fm/primary-guard-env-leak-fix

Conversation

@sKeLe100

Copy link
Copy Markdown
Owner

Intent

Fix primary-scope guard env leakage in bin/fm-primary-scope-lib.sh. Problem: a crewmate whose task worktree is a checkout of the firstmate repo itself inherits ambient FM_ROOT_OVERRIDE/FM_HOME from its launch environment; fm-primary-scope-lib.sh keyed its primary-scope match on those env values instead of the process's actual cwd/git-dir, so the crewmate was misclassified as the firstmate PRIMARY and the primary-only turn-end and subagent-dispatch guards misfired inside the crew worktree. Acceptance: (1) a failing-first colocated test simulating a firstmate-repo crew worktree with FM_ROOT_OVERRIDE/FM_HOME pointing at the real primary home, asserting fm-primary-scope-lib.sh classifies it as NOT primary; (2) fix scope match to key on the actual cwd/git-dir (the resolved repo root the guarded process is running in) rather than inherited env alone, so a process running in a treehouse/task worktree of the firstmate repo is never PRIMARY even when env points at the primary home; (3) the genuine primary session (cwd = the real primary checkout) must still classify as PRIMARY, keeping existing tests green; (4) considered whether fm-spawn should also sanitize these vars at crew launch as defense in depth. This is firstmate shared tracked material governed by firstmate-coding-guidelines.

What Changed

  • bin/fm-primary-scope-lib.sh now requires the physical location it is actually sourced from (the resolved parent of bin/) to share a git dir with the scope root before any other check, so a crewmate task worktree of the firstmate repo that inherits FM_ROOT_OVERRIDE/FM_HOME from its launch environment is no longer classified as PRIMARY and the primary-only turn-end and subagent-dispatch guards stop misfiring there.
  • Added fm_resolve_git_path, which resolves --git-dir/--git-common-dir to physical absolute paths (handling relative git paths and CDPATH), and reused it for the existing plain-checkout git-dir vs git-common-dir comparison so symlinked homes, leases, or temp dirs cannot defeat either match.
  • Added tests/fm-primary-scope-lib.test.sh covering the env-leaked firstmate crew worktree, the genuine primary checkout, secondmate markers, and symlinked paths; updated the sessionstart-nudge and subagent-pretool-check tests to stage per-fixture guard bins so their scopes resolve by location.
  • Documented the location-keyed predicate in docs/turnend-guard.md (now the owner of the in-scope conditions), with pointers from docs/configuration.md, docs/scripts.md, and docs/subagent-guard.md.

Risk Assessment

✅ Low: The change adds a single, well-bounded location-vs-env invariant to one sourced predicate with correctly physicalized path comparison, every caller and fixture shape traced still classifies as before except the leaked-env crew worktree it targets, and the new colocated test is genuinely failing-first.

Testing

Ran the targeted primary-scope tests plus the two guard entrypoint suites, verified the new colocated test is genuinely failing-first against the pre-fix library, and captured a CLI transcript showing the real subagent-dispatch guard firing inside a firstmate-repo crew worktree before the fix and going inert after it while the genuine primary session stays guarded; the only failures are two Pi/TypeScript tests that fail identically at the base commit because this machine's Node cannot import .ts files.

Evidence: Crew-worktree vs primary guard transcript (pre-fix vs fixed library)

Source: Crew-worktree vs primary guard transcript (pre-fix vs fixed library)

BASE lib (bb69fc5) | cwd=primary -> exit 2 (guard fires) BASE lib (bb69fc5) | cwd=crew -> exit 2 (guard fires: THE BUG) FIXED lib (763caf0) | cwd=primary -> exit 2 (guard fires) FIXED lib (763caf0) | cwd=crew -> exit 0 (inert, not primary) Both runs export FM_ROOT_OVERRIDE=FM_HOME=<primary home>.

=== Fixture ===
primary: /tmp/fm-scope-e2e/primary  (plain checkout of firstmate, .git is a directory)
crew   : /tmp/fm-scope-e2e/crew     (linked git worktree of the SAME firstmate repo = crewmate task worktree)
Both runs export the leaked env of the real primary home:
  FM_ROOT_OVERRIDE=/tmp/fm-scope-e2e/primary  FM_HOME=/tmp/fm-scope-e2e/primary

############ bin/fm-primary-scope-lib.sh = BASE (bb69fc5, pre-fix) ############
--- $ cd /tmp/fm-scope-e2e/primary && bin/fm-subagent-pretool-check.sh --claude --tool Agent
exit: 2  (guard FIRED - classified PRIMARY)
stderr:
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny"},"systemMessage":"[subagent-dispatch] the firstmate primary dispatches through the fleet, not the harness's own delegation tools: work started that way has no durable fleet record, leaves every firstmate guard inert, and dies with this session. Instead, first classify the work under the AGENTS.md intake contract, then 

--- $ cd /tmp/fm-scope-e2e/crew && bin/fm-subagent-pretool-check.sh --claude --tool Agent
exit: 2  (guard FIRED - classified PRIMARY)
stderr:
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny"},"systemMessage":"[subagent-dispatch] the firstmate primary dispatches through the fleet, not the harness's own delegation tools: work started that way has no durable fleet record, leaves every firstmate guard inert, and dies with this session. Instead, first classify the work under the AGENTS.md intake contract, then 

############ bin/fm-primary-scope-lib.sh = FIXED (763caf0, this change) ############
--- $ cd /tmp/fm-scope-e2e/primary && bin/fm-subagent-pretool-check.sh --claude --tool Agent
exit: 2  (guard FIRED - classified PRIMARY)
stderr:
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny"},"systemMessage":"[subagent-dispatch] the firstmate primary dispatches through the fleet, not the harness's own delegation tools: work started that way has no durable fleet record, leaves every firstmate guard inert, and dies with this session. Instead, first classify the work under the AGENTS.md intake contract, then 

--- $ cd /tmp/fm-scope-e2e/crew && bin/fm-subagent-pretool-check.sh --claude --tool Agent
exit: 0  (inert - NOT primary)

Expected: primary FIRES in both; crew worktree FIRES under BASE (the bug) and is INERT under FIXED.
Evidence: Failing-first proof for the new colocated test
$ (pre-fix bin/fm-primary-scope-lib.sh) bash tests/fm-primary-scope-lib.test.sh
ok - fm_primary_scope_matches classifies a genuine primary checkout as PRIMARY
not ok - a crew task worktree with root/state env-leaked to the real primary home must NOT classify as PRIMARY
exit=1

$ (fixed lib) all three assertions pass
- Outcome: ⚠️ 1 info across 1 run (5m3s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 4 issues found → auto-fixed (2) ✅
  • 🚨 bin/fm-primary-scope-lib.sh:49 - The new git-dir equality check makes fm_primary_scope_matches reject any invocation where the running script lives outside the root named by FM_ROOT_OVERRIDE/FM_HOME. tests/fm-subagent-pretool-check.test.sh invokes the REAL repo script (CHECK="$ROOT/bin/fm-subagent-pretool-check.sh", line 9) with FM_ROOT_OVERRIDE pointing at tmp fixtures ($PRIMARY line 49, $second line 214), so the guard now exits 0 instead of 2 for every deny/secondmate assertion in that file. Verified directly: sourcing bin/fm-primary-scope-lib.sh from this repo and calling fm_primary_scope_matches on a well-formed external fixture root returns 1. The nudge test was migrated to per-fixture script copies (tests/fm-sessionstart-nudge.test.sh:55) but fm-subagent-pretool-check.test.sh was not; apply the same staging there.
  • ⚠️ bin/fm-primary-scope-lib.sh:46 - Only the relative branch of each git-dir is normalized with pwd -P; an absolute git-dir (what git rev-parse --git-dir returns for a linked worktree, e.g. a treehouse-leased secondmate home) is compared unresolved, while actual_git_dir is always physical. If the home is reached through a symlinked path (macOS /tmp -> /private/tmp, symlinked $HOME, symlinked treehouse lease), root_git_dir keeps the logical path and never equals the physical actual_git_dir, so a genuine primary/secondmate session silently classifies as NOT primary and the turn-end and subagent guards fail open — the exact blind window they exist to close. Physicalize both values in the absolute branch too (e.g. cd &#34;$dir&#34; &amp;&amp; pwd -P).
  • ℹ️ bin/fm-primary-scope-lib.sh:51 - root_git_dir (line 44) and git_dir (line 51) run the identical git -C &#34;$root&#34; rev-parse --git-dir; the second call can reuse root_git_dir (comparing it against a similarly normalized git-common-dir), removing one subprocess and one normalization asymmetry.
  • ℹ️ bin/fm-spawn.sh:2857 - Acceptance item (4) asked whether fm-spawn should sanitize FM_ROOT_OVERRIDE/FM_HOME at crew launch as defense in depth. bin/fm-spawn.sh:2857 clears those vars only for KIND=secondmate; crew/scout launches still propagate the ambient values, which is the leak source this fix mitigates downstream. No code or note in the change records the outcome of that consideration — worth a one-line rationale in the lib header or commit trail so the deferred decision is traceable.

🔧 Fix: physicalize git-dir resolution and stage per-fixture guard bins in tests
3 issues (2 warnings, 1 info) still open:

  • ⚠️ bin/fm-primary-scope-lib.sh:51 - actual_dir is computed with a bare cd &#34;$(dirname &#34;${BASH_SOURCE[0]}&#34;)/..&#34; — no CDPATH=&#39;&#39; and no --, unlike the guarded (CDPATH=&#39;&#39; cd -- &#34;$path&#34; ... ) in the new fm_resolve_git_path helper and unlike every caller's own SCRIPT_DIR computation (e.g. bin/fm-subagent-pretool-check.sh:173). When a hook is invoked by a relative path (BASH_SOURCE relative, as in bin/fm-turnend-guard.sh run from the home) and the captain's environment exports CDPATH, cd resolves through CDPATH and echoes the resolved directory to stdout, so the command substitution captures "<echoed path>\n<pwd>" or an unrelated directory. actual_git_dir then never equals root_git_dir and fm_primary_scope_matches returns 1, silently failing the turn-end, session-start and subagent guards open in a genuine primary home — the exact blind window this predicate exists to close. Fix: actual_dir=$(CDPATH=&#39;&#39; cd -- &#34;$(dirname -- &#34;${BASH_SOURCE[0]}&#34;)/..&#34; 2&gt;/dev/null &amp;&amp; pwd -P) || return 1.
  • ⚠️ tests/fm-sessionstart-nudge.test.sh:106 - test_gate_env_is_silent (line 91) and test_gate_common_dir_is_silent (line 106) still invoke the real repo entrypoint $NUDGE (line 32) against tmp fixtures, while every other nudge assertion was migrated to per-fixture staged copies (run_nudge, line 63). Under the new predicate the real bin/ copy's git-dir never equals the fixture root's git-dir, so fm_primary_scope_matches returns 1 and the hook exits silently at line 21 of bin/fm-sessionstart-nudge.sh regardless of whether fm_is_gate_agent (line 20) works at all. Both assertions expect only silence, so they now pass with the gate-refuse logic they were written to protect fully broken — a regression in NO_MISTAKES_GATE or .no-mistakes common-dir detection would go undetected. Stage bin/ for those two fixtures (call run_nudge / stage_nudge_bin) so the gate branch is the thing actually exercised.
  • ℹ️ tests/fm-sessionstart-nudge.test.sh:200 - stage_run_bin does cp -R &#34;$ROOT/bin/.&#34; (3.5 MB, 160 files) into each of ~14 run-tier fixtures, ~50 MB of copying per suite run. Pragmatic given the run wrapper's wide dependency fan-out, but if the suite gets slow, a hardlinked copy (cp -al) or an explicit dependency list would cut it; noting the tradeoff, no action required.

🔧 Fix: guard CDPATH in scope match and de-vacuum gate nudge tests
✅ Re-checked - no issues remain.

⚠️ **Test** - 1 info
  • ℹ️ tests/fm-turnend-guard.test.sh ('Pi guard must inject once...') and tests/fm-sessionstart-nudge.test.sh ('Pi continuation classification') fail on this machine because Node 22.22 cannot import the .ts Pi extension (ERR_UNKNOWN_FILE_EXTENSION). Both failures reproduce unchanged at base commit bb69fc5, so they are pre-existing environment issues, not regressions from this change.
  • bin/fm-test-run.sh tests/fm-primary-scope-lib.test.sh tests/fm-sessionstart-nudge.test.sh tests/fm-subagent-pretool-check.test.sh tests/fm-turnend-guard.test.sh
  • Failing-first check: replaced bin/fm-primary-scope-lib.sh with the bb69fc5 version and ran bash tests/fm-primary-scope-lib.test.sh (fails on the leaked-env crew case), then restored the fixed lib
  • Manual end-to-end: clone of the repo as PRIMARY + git worktree add crew worktree; ran cd &lt;crew&gt; &amp;&amp; FM_ROOT_OVERRIDE=&lt;primary&gt; FM_HOME=&lt;primary&gt; bin/fm-subagent-pretool-check.sh --claude --tool Agent and the same from <primary>, under both the pre-fix and fixed library
  • Baseline comparison: ran bin/fm-test-run.sh tests/fm-turnend-guard.test.sh and tests/fm-sessionstart-nudge.test.sh in a checkout of base commit bb69fc5 to confirm the two Pi failures are pre-existing
  • node -e &#39;import(&#34;file:///tmp/t.ts&#34;)&#39; to confirm ERR_UNKNOWN_FILE_EXTENSION is the root cause of the Pi test failures
⚠️ **Document** - 1 info
  • ℹ️ docs/turnend-guard.md:22 - The intent's item (4) — whether bin/fm-spawn.sh should also sanitize FM_ROOT_OVERRIDE/FM_HOME at crew launch as defense in depth — was considered but not implemented in this change, and I did not document a decision that the code does not yet make. If the maintainers want that non-sanitization recorded as deliberate, its owner would be docs/turnend-guard.md's Guard Predicates section (or the spawn docs) once the decision is settled.
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

fm_primary_scope_matches trusted FM_ROOT_OVERRIDE/FM_HOME alone, so a
crewmate whose task worktree is a firstmate-repo checkout inherited those
vars from its launch environment and was misclassified as PRIMARY,
misfiring the turn-end/subagent guards inside the crew worktree.

Now requires the git-dir of this library's own on-disk location (where the
guarded script actually runs from) to match the claimed root's git-dir, so
a leaked-env task worktree fails classification even though the override
still points at a genuine primary home.

fm-sessionstart-nudge.test.sh's primary/worktree fixtures updated to stage
per-fixture script copies so scope matching stays keyed to real locations.
@sKeLe100
sKeLe100 merged commit 8e7b0f4 into main Aug 26, 2026
12 checks passed
sKeLe100 added a commit that referenced this pull request Nov 23, 2026
… to fork contracts

Test-only adaptations found in CI triage. No production code changes.

- fm-stow-guard: run a staged copy of the guard from each fixture root's
  bin/, because the fork's primary-scope check (#22) keys on the guard's
  physical location; same pattern as fm-sessionstart-nudge.
- fm-backend-t3code: give codex spawns an explicit --effort (the fork
  refuses a codex launch without one), and give the native-restart case a
  fake tmux pane so the fork's pre-arm host check (#31) passes.
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