Skip to content

fix(bin): allow session-local todo tools in the subagent guard - #1204

Merged
kunchenguid merged 3 commits into
kunchenguid:mainfrom
danielkuykendall23-boop:fm/guard-planonly
Jul 29, 2026
Merged

kunchenguid merged 3 commits into
kunchenguid:mainfrom
danielkuykendall23-boop:fm/guard-planonly

Conversation

@danielkuykendall23-boop

Copy link
Copy Markdown
Contributor

Intent

The developer needed a false positive fixed in firstmate's subagent guard: bin/fm-subagent-pretool-check.sh denied the harness's session-local todo tools TaskCreate and TaskUpdate because they matched the "task" delegation stem, even though they create no runnable work. They required the defect be reproduced first rather than taken on trust, and specified the fix shape explicitly: do not widen OBSERVE_ONLY_TOOLS (whose documented contract covers only observe-or-stop tools), but add a second, separately-reasoned exact-name allowlist (suggested PLAN_ONLY_TOOLS='taskcreate taskupdate') checked alongside it, keeping both exact-name rather than substring so the widening cannot creep. Acceptance required that every currently-denied delegation tool (Agent, Task, TaskCreateAgent, Workflow, CronCreate, SendMessage, EnterWorktree, RemoteTrigger) stay denied, all existing observe-only tools still pass, the mcp__* short-circuit and FM_ALLOW_SUBAGENT=1 escape hatch remain untouched, the guard stay inert in task worktrees and non-firstmate repos, docs/subagent-guard.md document the new list's distinct rationale, and shellcheck stay clean. They further demanded that new tests be colocated per repo convention, watched failing against the pre-fix script with that stated plainly in the report, and that the non-regression assertions be proven to bite by deliberately over-widening the new list and watching the tests go red. Constraints: change no allow/deny behavior beyond those two names, do not touch bin/fm-primary-scope-lib.sh or the scope logic because an in-flight branch already modifies that file, and push to the fork remote rather than origin. In a follow-up the developer said the fix was verified good but delivery was incomplete, and directed that /no-mistakes be run on branch fm/guard-planonly and driven through every gate to an open PR with green CI.

What Changed

  • bin/fm-subagent-pretool-check.sh gains a second exact-name exclusion list, PLAN_ONLY_TOOLS='taskcreate taskupdate', checked alongside OBSERVE_ONLY_TOOLS in the same loop. TaskCreate and TaskUpdate previously matched the task delegation stem and were denied in a primary session even though they only write the harness's session-local todo list, which has no executor. The list is kept separate from OBSERVE_ONLY_TOOLS because these tools write, and both lists match the whole normalized name rather than a substring so neither can widen by accident. No other allow/deny behavior changed: the mcp__* short-circuit, the FM_ALLOW_SUBAGENT=1 escape hatch, and inertness in task worktrees and non-firstmate repos are untouched.
  • tests/fm-subagent-pretool-check.test.sh adds two colocated cases — one asserting both todo tools are allowed, one asserting six near-miss names (TaskCreateAgent, TaskCreateWorktree, TaskUpdateAgent, RemoteTaskCreate, Task, TaskCreator) stay denied so the exact-name contract is tested rather than assumed — and excludes the two names from the known-delegation-tool denial sweep. The suite runs 15/15 green.
  • docs/subagent-guard.md documents the new list's distinct rationale as a third exclusion, and the review gate followed through by dropping TaskCreate and TaskUpdate from the recommended untracked local permissions.deny list, which sits upstream of this hook and would otherwise reproduce the same false positive at a stronger layer; the harness table's Claude row moves from 18 to 16 known tools and the dated deny-list evidence section is annotated to say which form of the list it validated.

Risk Assessment

✅ Low: The branch is a two-name exact-match allowlist addition to a single guard script, backed by colocated tests that pin both the new allows and six near-miss denials, plus a docs-only follow-up that narrows a recommendation by exactly those same two names while preserving the historical validation record verbatim; no shipped allow/deny behavior beyond the two names changed and no sibling enforcement path remains that reproduces the fixed false positive.

Testing

I reproduced the reported false positive before testing the fix: driving the base-commit guard with real Claude PreToolUse JSON on stdin inside a firstmate-shaped primary home, TaskCreate and TaskUpdate both exit 2 with the full [subagent-dispatch] deny text matched on the "task" stem, including the instruction to run fm-brief.sh and fm-spawn.sh for a todo entry. Against the target commit the same payloads exit 0 silently, while Agent, Task, TaskCreateAgent, Workflow, CronCreate, SendMessage, EnterWorktree and RemoteTrigger still deny with correct stem attribution, all seven observe-only names still pass, the mcp__* short-circuit and FM_ALLOW_SUBAGENT=1 escape hatch behave as before, and the guard stays inert in a crewmate task worktree and a non-firstmate repo. The colocated suite tests/fm-subagent-pretool-check.test.sh passes 15/15, and I watched its new tests fail: red against the pre-fix script, and red again under two deliberate over-widenings of PLAN_ONLY_TOOLS (adding bare "task", and switching the match from exact-name to substring), with the near-miss assertion run in isolation to prove it is the assertion doing the catching. I also ran tests/fm-documentation-audiences.test.sh because docs/subagent-guard.md changed, and confirmed the doc's recommended deny list dropped to 16 names consistently with its own harness-table claim. This change has no rendered UI surface — it is a shell PreToolUse hook — so the reviewer-visible artifact is the CLI transcript of the deny and allow decisions the primary session actually receives, rather than a screenshot. I did not run shellcheck; linters are outside this phase.

Evidence: Before/after PreToolUse hook transcript (the primary session's actual experience)

BEFORE (base fbece9c) - the reported false positive, reproduced TaskCreate exit 2 DENY [subagent-dispatch] ... (blocked tool: TaskCreate, delegation-shaped on "task"). TaskUpdate exit 2 DENY [subagent-dispatch] ... (blocked tool: TaskUpdate, delegation-shaped on "task"). AFTER (064d6c8) TaskCreate exit 0 ALLOW (silent: stdout and stderr empty) TaskUpdate exit 0 ALLOW (silent: stdout and stderr empty) Agent/Task/TaskCreateAgent/Workflow/CronCreate/SendMessage/EnterWorktree/RemoteTrigger exit 2 DENY TaskOutput/TaskStop/TaskGet/TaskList/CronList/BashOutput/KillShell exit 0 ALLOW mcp__tracker__create_task exit 0 ALLOW FM_ALLOW_SUBAGENT=1 Agent exit 0 ALLOW crewmate task worktree / non-firstmate repo, TaskCreate and Agent: exit 0 inert (no-op)

================================================================================
BEFORE (base fbece9c) - the reported false positive, reproduced
================================================================================
PreToolUse payload on stdin, firstmate primary home:
  TaskCreate         exit 2  DENY
      what the primary session is shown:
        [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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work 
        (blocked tool: TaskCreate, delegation-shaped on "task"). Launch the session with 
        FM_ALLOW_SUBAGENT=1 for a deliberate exception.
  TaskUpdate         exit 2  DENY
      what the primary session is shown:
        [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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work 
        (blocked tool: TaskUpdate, delegation-shaped on "task"). Launch the session with 
        FM_ALLOW_SUBAGENT=1 for a deliberate exception.

================================================================================
AFTER (064d6c8) - session-local todo tools pass, delegation still blocked
================================================================================
session-local todo tools:
  TaskCreate         exit 0  ALLOW (silent: stdout and stderr empty)
  TaskUpdate         exit 0  ALLOW (silent: stdout and stderr empty)

delegation tools that must stay denied:
  Agent              exit 2  DENY
      what the primary session is shown:
        [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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work 
        (blocked tool: Agent, delegation-shaped on "agent"). Launch the session with 
        FM_ALLOW_SUBAGENT=1 for a deliberate exception.
  Task               exit 2  DENY
      what the primary session is shown:
        [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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work 
        (blocked tool: Task, delegation-shaped on "task"). Launch the session with FM_ALLOW_SUBAGENT=1 
        for a deliberate exception.
  TaskCreateAgent    exit 2  DENY
      what the primary session is shown:
        [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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work 
        (blocked tool: TaskCreateAgent, delegation-shaped on "agent"). Launch the session with 
        FM_ALLOW_SUBAGENT=1 for a deliberate exception.
  Workflow           exit 2  DENY
      what the primary session is shown:
        [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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work 
        (blocked tool: Workflow, delegation-shaped on "workflow"). Launch the session with 
        FM_ALLOW_SUBAGENT=1 for a deliberate exception.
  CronCreate         exit 2  DENY
      what the primary session is shown:
        [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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work 
        (blocked tool: CronCreate, delegation-shaped on "cron"). Launch the session with 
        FM_ALLOW_SUBAGENT=1 for a deliberate exception.
  SendMessage        exit 2  DENY
      what the primary session is shown:
        [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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work 
        (blocked tool: SendMessage, delegation-shaped on "sendmessage"). Launch the session with 
        FM_ALLOW_SUBAGENT=1 for a deliberate exception.
  EnterWorktree      exit 2  DENY
      what the primary session is shown:
        [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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work 
        (blocked tool: EnterWorktree, delegation-shaped on "worktree"). Launch the session with 
        FM_ALLOW_SUBAGENT=1 for a deliberate exception.
  RemoteTrigger      exit 2  DENY
      what the primary session is shown:
        [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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work 
        (blocked tool: RemoteTrigger, delegation-shaped on "remote"). Launch the session with 
        FM_ALLOW_SUBAGENT=1 for a deliberate exception.

observe-or-stop tools (unchanged):
  TaskOutput         exit 0  ALLOW (silent: stdout and stderr empty)
  TaskStop           exit 0  ALLOW (silent: stdout and stderr empty)
  TaskGet            exit 0  ALLOW (silent: stdout and stderr empty)
  TaskList           exit 0  ALLOW (silent: stdout and stderr empty)
  CronList           exit 0  ALLOW (silent: stdout and stderr empty)
  BashOutput         exit 0  ALLOW (silent: stdout and stderr empty)
  KillShell          exit 0  ALLOW (silent: stdout and stderr empty)

mcp__* short-circuit and the FM_ALLOW_SUBAGENT escape hatch (unchanged):
  mcp__tracker__create_task exit 0  ALLOW (silent: stdout and stderr empty)
  FM_ALLOW_SUBAGENT=1 ->  Agent              exit 0  ALLOW (silent: stdout and stderr empty)

================================================================================
AFTER - the guard stays inert outside a primary home
================================================================================
  crewmate task worktree   TaskCreate     exit 0  inert (no-op)
  crewmate task worktree   Agent          exit 0  inert (no-op)
  non-firstmate repo       TaskCreate     exit 0  inert (no-op)
  non-firstmate repo       Agent          exit 0  inert (no-op)
Evidence: Red-before-green and mutation proof

CASE: new tests vs PRE-FIX guard (base fbece9c) not ok - session-local todo tool (TaskCreate) must allow, got exit 2: {"hookSpecificOutput":{..."permissionDecision":"deny"}...} exit=1 (RED) CASE: MUTANT A: PLAN_ONLY_TOOLS='taskcreate taskupdate task' not ok - known delegation tool (Task) must deny with exit 2, got 0 exit=1 (RED) CASE: MUTANT B: plan-only match loosened to substring not ok - plan-only near miss (TaskCreateAgent) must deny with exit 2, got 0 exit=1 (RED) CASE: CONTROL: shipped guard at 064d6c8 15 ok lines, exit=0 (GREEN)

--------------------------------------------------------------------------------
CASE: new tests vs PRE-FIX guard (base fbece9c) - must be RED
--------------------------------------------------------------------------------
ok - tracked Claude settings do not ship permissions.deny
ok - the guard independently denies every work-creating delegation tool by shape
ok - the guard denies delegation-shaped tools that no deny list knows about yet
ok - the guard leaves ordinary tools and observe-or-stop operations alone
not ok - session-local todo tool (TaskCreate) must allow, got exit 2: {"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 use bin/fm-brief.sh followed by bin/fm-spawn.sh for dispatched work (blocked tool: TaskCreate, delegation-shaped on \"task\"). Launch the session with FM_ALLOW_SUBAGENT=1 for a deliberate exception."}
exit=1  (RED)

79:PLAN_ONLY_TOOLS='taskcreate taskupdate task'
--------------------------------------------------------------------------------
CASE: MUTANT A: PLAN_ONLY_TOOLS over-widened with bare 'task' - must be RED
--------------------------------------------------------------------------------
ok - tracked Claude settings do not ship permissions.deny
not ok - known delegation tool (Task) must deny with exit 2, got 0
exit=1  (RED)

for allowed in $OBSERVE_ONLY_TOOLS; do
  [ "$NORMALIZED" != "$allowed" ] || exit 0
done
for allowed in $PLAN_ONLY_TOOLS; do
  case "$NORMALIZED" in *"$allowed"*) exit 0 ;; esac
done
--------------------------------------------------------------------------------
CASE: MUTANT B: plan-only match loosened from exact-name to substring - must be RED
--------------------------------------------------------------------------------
ok - tracked Claude settings do not ship permissions.deny
ok - the guard independently denies every work-creating delegation tool by shape
ok - the guard denies delegation-shaped tools that no deny list knows about yet
ok - the guard leaves ordinary tools and observe-or-stop operations alone
ok - the guard leaves the session-local todo list alone
not ok - plan-only near miss (TaskCreateAgent) must deny with exit 2, got 0
exit=1  (RED)

--------------------------------------------------------------------------------
CASE: CONTROL: shipped guard at 064d6c8 - must be GREEN
--------------------------------------------------------------------------------
ok - tracked Claude settings do not ship permissions.deny
ok - the guard independently denies every work-creating delegation tool by shape
ok - the guard denies delegation-shaped tools that no deny list knows about yet
ok - the guard leaves ordinary tools and observe-or-stop operations alone
ok - the guard leaves the session-local todo list alone
ok - the plan-only exclusion releases exactly two names and nothing that merely contains them
ok - MCP tool names are never classified as harness delegation
ok - deny defers to intake classification and degrades gracefully without fm-scout.sh
ok - the single documented escape hatch releases the guard only on the exact opt-in value
ok - the guard is inert in a crewmate task worktree and in a non-firstmate repo
ok - a marked secondmate home is guarded even though it is a linked worktree
ok - both stdin transports classify correctly and Claude's deny keeps stdout empty
ok - malformed, empty, and tool-name-less payloads fail open rather than blocking every tool call
ok - missing jq for stdin transport fails open rather than denying every tool call
ok - Claude wires the delegation guard, retains only non-status Bash seatbelts, and preserves the Stop guard
exit=0  (GREEN)
Evidence: Near-miss assertion isolated against each mutant
=== widen-stem (PLAN_ONLY_TOOLS gains bare 'task'): near-miss assertion in isolation ===
not ok - plan-only near miss (Task) must deny with exit 2, got 0
exit=1
=== widen-substring (exact-name loosened to substring): near-miss assertion in isolation ===
not ok - plan-only near miss (TaskCreateAgent) must deny with exit 2, got 0
exit=1
=== control (shipped guard): near-miss assertion in isolation ===
ok - the plan-only exclusion releases exactly two names and nothing that merely contains them
exit=0
Evidence: Colocated guard suite, shipped commit

ok - the guard leaves the session-local todo list alone ok - the plan-only exclusion releases exactly two names and nothing that merely contains them (15/15 ok, exit 0)

ok - tracked Claude settings do not ship permissions.deny
ok - the guard independently denies every work-creating delegation tool by shape
ok - the guard denies delegation-shaped tools that no deny list knows about yet
ok - the guard leaves ordinary tools and observe-or-stop operations alone
ok - the guard leaves the session-local todo list alone
ok - the plan-only exclusion releases exactly two names and nothing that merely contains them
ok - MCP tool names are never classified as harness delegation
ok - deny defers to intake classification and degrades gracefully without fm-scout.sh
ok - the single documented escape hatch releases the guard only on the exact opt-in value
ok - the guard is inert in a crewmate task worktree and in a non-firstmate repo
ok - a marked secondmate home is guarded even though it is a linked worktree
ok - both stdin transports classify correctly and Claude's deny keeps stdout empty
ok - malformed, empty, and tool-name-less payloads fail open rather than blocking every tool call
ok - missing jq for stdin transport fails open rather than denying every tool call
ok - Claude wires the delegation guard, retains only non-status Bash seatbelts, and preserves the Stop guard
Evidence: Reproduction driver: before/after hook transcript
#!/usr/bin/env bash
# Drives the real PreToolUse hook exactly the way Claude Code drives it - a
# PreToolUse JSON payload on stdin - inside a firstmate-shaped primary home,
# against the pre-fix (base fbece9c) and post-fix (064d6c8) guard scripts.
# Prints the transcript a primary session would actually experience.
set -u

REPO=${1:?repo root}
EV=${2:?evidence dir}
WORK="$EV/scratch"
rm -rf "$WORK"
mkdir -p "$WORK/bin-prefix" "$WORK/home/bin" "$WORK/home/state"

# Pre-fix guard: the script exactly as it was at the base commit.
git -C "$REPO" show fbece9c:bin/fm-subagent-pretool-check.sh > "$WORK/bin-prefix/fm-subagent-pretool-check.sh"
chmod +x "$WORK/bin-prefix/fm-subagent-pretool-check.sh"
cp "$REPO/bin/fm-primary-scope-lib.sh" "$WORK/bin-prefix/"

PRE="$WORK/bin-prefix/fm-subagent-pretool-check.sh"
POST="$REPO/bin/fm-subagent-pretool-check.sh"

# A genuine primary home: plain checkout, AGENTS.md, bin/, state/.
HOME_DIR="$WORK/home"
printf '# firstmate fixture primary\n' > "$HOME_DIR/AGENTS.md"
git -C "$HOME_DIR" init -q

call() { # call <script> <tool> [env...]
  local script=$1 tool=$2 rc=0 out err
  shift 2
  out=$(mktemp); err=$(mktemp)
  printf '{"tool_name":"%s","tool_input":{}}' "$tool" \
    | env FM_ROOT_OVERRIDE="$HOME_DIR" FM_HOME="$HOME_DIR" FM_STATE_OVERRIDE="$HOME_DIR/state" "$@" \
      "$script" --claude > "$out" 2> "$err" || rc=$?
  if [ "$rc" -eq 0 ]; then
    printf '  %-18s exit 0  ALLOW (silent: stdout and stderr empty)\n' "$tool"
  else
    printf '  %-18s exit %s  DENY\n' "$tool" "$rc"
    printf '      what the primary session is shown:\n'
    jq -r '.systemMessage' "$err" | fold -s -w 96 | sed 's/^/        /'
  fi
  rm -f "$out" "$err"
}

echo "================================================================================"
echo "BEFORE (base fbece9c) - the reported false positive, reproduced"
echo "================================================================================"
echo "PreToolUse payload on stdin, firstmate primary home:"
call "$PRE" TaskCreate
call "$PRE" TaskUpdate

echo
echo "================================================================================"
echo "AFTER (064d6c8) - session-local todo tools pass, delegation still blocked"
echo "================================================================================"
echo "session-local todo tools:"
call "$POST" TaskCreate
call "$POST" TaskUpdate

echo
echo "delegation tools that must stay denied:"
for t in Agent Task TaskCreateAgent Workflow CronCreate SendMessage EnterWorktree RemoteTrigger; do
  call "$POST" "$t"
done

echo
echo "observe-or-stop tools (unchanged):"
for t in TaskOutput TaskStop TaskGet TaskList CronList BashOutput KillShell; do
  call "$POST" "$t"
done

echo
echo "mcp__* short-circuit and the FM_ALLOW_SUBAGENT escape hatch (unchanged):"
call "$POST" mcp__tracker__create_task
printf '  FM_ALLOW_SUBAGENT=1 ->'
call "$POST" Agent FM_ALLOW_SUBAGENT=1

echo
echo "================================================================================"
echo "AFTER - the guard stays inert outside a primary home"
echo "================================================================================"
git -C "$HOME_DIR" -c user.name=fixture -c [email protected] add AGENTS.md >/dev/null
git -C "$HOME_DIR" -c user.name=fixture -c [email protected] commit -qm fixture
git -C "$HOME_DIR" worktree add -q -b task-fixture "$WORK/task-worktree"
mkdir -p "$WORK/task-worktree/bin" "$WORK/task-worktree/state"
mkdir -p "$WORK/plain/bin" "$WORK/plain/state"
git -C "$WORK/plain" init -q
printf '# not firstmate\n' > "$WORK/plain/README.md"

for label in "crewmate task worktree:$WORK/task-worktree" "non-firstmate repo:$WORK/plain"; do
  name=${label%%:*}; dir=${label#*:}
  for t in TaskCreate Agent; do
    rc=0
    printf '{"tool_name":"%s","tool_input":{}}' "$t" \
      | env FM_ROOT_OVERRIDE="$dir" FM_HOME="$dir" FM_STATE_OVERRIDE="$dir/state" \
        "$POST" --claude >/dev/null 2>&1 || rc=$?
    printf '  %-24s %-14s exit %s  %s\n' "$name" "$t" "$rc" "$([ "$rc" -eq 0 ] && echo 'inert (no-op)' || echo 'DENY')"
  done
done

git -C "$HOME_DIR" worktree remove --force "$WORK/task-worktree" >/dev/null 2>&1
Evidence: Reproduction driver: red-before-green and mutation proof
#!/usr/bin/env bash
# Proves the new tests bite: runs tests/fm-subagent-pretool-check.test.sh from a
# scratch repo copy against (1) the pre-fix guard script and (2) two deliberately
# over-widened plan-only exclusions. The tests must go red in every case.
set -u

REPO=${1:?repo root}
EV=${2:?evidence dir}
WORK="$EV/redproof"
rm -rf "$WORK"

build_scratch() { # build_scratch <dir>
  local d=$1
  mkdir -p "$d/bin" "$d/tests" "$d/.claude"
  cp "$REPO/bin/fm-subagent-pretool-check.sh" "$REPO/bin/fm-primary-scope-lib.sh" "$d/bin/"
  cp "$REPO/.claude/settings.json" "$d/.claude/"
  cp "$REPO/tests/lib.sh" "$REPO/tests/fm-subagent-pretool-check.test.sh" "$d/tests/"
}

run_case() { # run_case <label> <dir>
  local label=$1 d=$2 rc=0 out
  out=$(bash "$d/tests/fm-subagent-pretool-check.test.sh" 2>&1) || rc=$?
  echo "--------------------------------------------------------------------------------"
  echo "CASE: $label"
  echo "--------------------------------------------------------------------------------"
  printf '%s\n' "$out"
  echo "exit=$rc  ($([ "$rc" -eq 0 ] && echo GREEN || echo RED))"
  echo
}

# --- 1. the new tests against the PRE-FIX guard (red-before-green) -----------
build_scratch "$WORK/prefix"
git -C "$REPO" show fbece9c:bin/fm-subagent-pretool-check.sh > "$WORK/prefix/bin/fm-subagent-pretool-check.sh"
chmod +x "$WORK/prefix/bin/fm-subagent-pretool-check.sh"
run_case "new tests vs PRE-FIX guard (base fbece9c) - must be RED" "$WORK/prefix"

# --- 2. over-widened by a shorter stem: PLAN_ONLY_TOOLS gains 'task' ---------
build_scratch "$WORK/widen-stem"
sed -i "s/^PLAN_ONLY_TOOLS='taskcreate taskupdate'$/PLAN_ONLY_TOOLS='taskcreate taskupdate task'/" \
  "$WORK/widen-stem/bin/fm-subagent-pretool-check.sh"
grep -n "^PLAN_ONLY_TOOLS=" "$WORK/widen-stem/bin/fm-subagent-pretool-check.sh"
run_case "MUTANT A: PLAN_ONLY_TOOLS over-widened with bare 'task' - must be RED" "$WORK/widen-stem"

# --- 3. over-widened to substring matching instead of exact name ------------
build_scratch "$WORK/widen-substring"
python3 - "$WORK/widen-substring/bin/fm-subagent-pretool-check.sh" <<'PY'
import sys
p = sys.argv[1]
s = open(p).read()
old = '''for allowed in $OBSERVE_ONLY_TOOLS $PLAN_ONLY_TOOLS; do
  [ "$NORMALIZED" != "$allowed" ] || exit 0
done'''
new = '''for allowed in $OBSERVE_ONLY_TOOLS; do
  [ "$NORMALIZED" != "$allowed" ] || exit 0
done
for allowed in $PLAN_ONLY_TOOLS; do
  case "$NORMALIZED" in *"$allowed"*) exit 0 ;; esac
done'''
assert old in s
open(p, 'w').write(s.replace(old, new))
PY
sed -n '/^for allowed in \$OBSERVE_ONLY_TOOLS/,/^done$/p;/^for allowed in \$PLAN_ONLY_TOOLS/,/^done$/p' \
  "$WORK/widen-substring/bin/fm-subagent-pretool-check.sh"
run_case "MUTANT B: plan-only match loosened from exact-name to substring - must be RED" "$WORK/widen-substring"

# --- 4. control: the shipped guard, unmutated -------------------------------
build_scratch "$WORK/control"
run_case "CONTROL: shipped guard at 064d6c8 - must be GREEN" "$WORK/control"

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed ✅
  • ℹ️ docs/subagent-guard.md:114 - The recommended local Claude permissions.deny list (docs/subagent-guard.md:74-99) still contains TaskCreate and TaskUpdate. A denied name is removed from the model's schema entirely, which is a layer upstream of this PreToolUse hook, so a Claude primary that adopts the documented hardening verbatim still cannot use the session-local todo list — the exact symptom this guard change fixes. The docs acknowledge this explicitly at lines 114-116 and frame the list width as a captain-owned decision, so it is deliberate rather than an oversight, and it is untracked per-home config rather than shipped source. Flagging only so you can decide whether the recommendation should now drop those two names alongside the guard fix; no source change is implied.

🔧 Fix: drop session-local todo tools from recommended deny list
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • bash tests/fm-subagent-pretool-check.test.sh — the colocated guard suite, 15/15 green including the two new tests
  • bash tests/fm-documentation-audiences.test.sh — docs surface test, relevant because docs/subagent-guard.md changed; 5/5 green
  • Manual reproduction: piped {&#34;tool_name&#34;:&#34;TaskCreate&#34;} and {&#34;tool_name&#34;:&#34;TaskUpdate&#34;} PreToolUse payloads into the base-commit (git show fbece9c:bin/fm-subagent-pretool-check.sh) guard inside a firstmate-shaped primary fixture — both exit 2 with the [subagent-dispatch] deny message, stem &#34;task&#34;
  • Manual after-state: same payloads into bin/fm-subagent-pretool-check.sh at 064d6c8 — exit 0, stdout and stderr empty
  • Manual non-regression sweep through the same stdin transport: Agent Task TaskCreateAgent Workflow CronCreate SendMessage EnterWorktree RemoteTrigger all deny; TaskOutput TaskStop TaskGet TaskList CronList BashOutput KillShell all allow; mcp__tracker__create_task allows; FM_ALLOW_SUBAGENT=1 releases Agent
  • Manual scope check: TaskCreate and Agent in a linked crewmate task worktree and in a plain non-firstmate git repo — both inert (exit 0, no output)
  • Red-before-green: ran tests/fm-subagent-pretool-check.test.sh from a scratch repo copy whose bin/fm-subagent-pretool-check.sh is the pre-fix version — fails at test_guard_allows_session_local_todo_tools on TaskCreate
  • Mutation A: PLAN_ONLY_TOOLS=&#39;taskcreate taskupdate task&#39; in a scratch copy — suite red; test_plan_only_exclusion_is_exact_name run in isolation fails on Task
  • Mutation B: plan-only match loosened from exact-name to case &#34;$NORMALIZED&#34; in *&#34;$allowed&#34;* in a scratch copy — suite red at test_plan_only_exclusion_is_exact_name on TaskCreateAgent
  • Control: unmutated scratch copy of the shipped guard — suite green, near-miss test green in isolation
  • Doc consistency check: the recommended local deny list in docs/subagent-guard.md now enumerates 16 names, matching the harness table's updated "16 known tools" claim, and no longer lists TaskCreate or TaskUpdate
⚠️ **Document** - 1 info
  • ℹ️ docs/subagent-guard.md:114 - Judgment call, left as-is: the plan-only rationale ("session-local todo list, no executor, spawns nothing") now appears both in the exclusion bullet at docs/subagent-guard.md:58-62 and in the deny-list section at docs/subagent-guard.md:114-115. I did not consolidate it because the two passages answer different questions - why the shipped hook allows the tools, versus why the recommended local deny list omits them - and the second is a compressed restatement carrying its own unique facts (schema removal costs plan tracking and buys no delegation power; this local list is the only layer that can remove a todo tool from the schema). Reducing it to a pointer would strip load-bearing context from a section a captain reads standalone.
⚠️ **Lint** - 1 warning
  • ⚠️ linter found issues (exit code 127)
✅ **Push** - passed

✅ No issues found.

The delegation-shape guard denied TaskCreate and TaskUpdate because their
normalized names contain the `task` stem. Those tools write only the harness's
session-local todo list, which has no executor: it spawns no agent, allocates
no worktree, registers no schedule, and starts nothing that outlives the
session. That is not the unaccounted work the guard exists to stop, so the stem
match was a false positive, and the deny text told the primary to run
bin/fm-brief.sh and bin/fm-spawn.sh to create a todo entry.

Add a separately-reasoned PLAN_ONLY_TOOLS exact-name exclusion rather than
widening OBSERVE_ONLY_TOOLS, whose documented contract is tools that only
observe or stop existing work. Both lists stay exact-name so neither can widen
by substring.

Tests cover the two allowed names and six near-miss names that a substring or
shortened-stem widening would release; both mutations were watched red.
@kunchenguid
kunchenguid merged commit 7cbb3f6 into kunchenguid:main Jul 29, 2026
10 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

Thanks @danielkuykendall23-boop - merged! Really appreciate the contribution.

ironerumi added a commit to ironerumi/firstmate that referenced this pull request Jul 29, 2026
* fix: block primary-session delegation outside the fleet (kunchenguid#854)

* feat: fence primary-session delegation outside the fleet

A firstmate primary that delegates through Claude Code's built-in
delegation tools creates work with no state/<id>.meta. Because
fm-supervision-lib.sh counts *.meta and fm-turnend-guard.sh exits
silently at zero, such work does not merely go unsupervised: it makes
the whole guard stack structurally inert, and it dies with the primary
session. On 2026-07-22 that cost two workers mid-flight and left
supervision down for 73 minutes unnoticed.

Layer 1, the primary fix: a permissions.deny list in
.claude/settings.json removes the 18 delegation, scheduling, worktree,
and task-tracking tools from the model's schema, so they are never
offered. This is removal rather than interception, so there is no call
to intercept and no fail-open path. The list is flat and in one file so
its width stays reviewable; the captain owns that width.

Layer 2, bin/fm-subagent-pretool-check.sh: a deny list is fail-open
against tools that do not exist yet, and permissions.allow is a
pre-approval list rather than an availability list, so there is no
fail-closed allowlist to use instead. This backstop classifies the tool
NAME by shape rather than against a fixed list, so a delegation tool
that ships before the deny list is updated is still refused. It excludes
mcp__* names and observe-or-stop operations, scopes itself to a genuine
primary home via the shared fm_primary_scope_matches predicate so a
crewmate's task worktree is unaffected, and offers one deliberate
FM_ALLOW_SUBAGENT=1 escape hatch that must be set at launch.

Verified live against Claude Code 2.1.217, including a deny-key A/B with
a nonsense-name control, layer 2 denying an un-denied Workflow call, the
same call allowed in a linked worktree, and the escape hatch. Corrects a
prior finding: both Task and Agent work as deny keys, so both are
pinned. Codex 0.144.1 verified to expose no delegation tool; grok,
opencode, and pi are inspected and documented as not wired because those
binaries are absent from this host and the repo requires live validation
before trusting a harness hook. Evidence in docs/subagent-guard.md.

* no-mistakes(review): Ship scoped Claude delegation guard

* no-mistakes(test): Ship Claude delegation deny list

* no-mistakes(document): Clarify PreToolUse guard ownership

* no-mistakes(lint): Keep Claude deny list local

* fix: install tasks-axi in portable CI shards (kunchenguid#866)

Reproduction: portable-parallel-2 completed successfully without tasks-axi while fm-decision-hold-lifecycle emitted a gate skip in 30 ms. The pre-shard lane installed tasks-axi and exercised the test fully. Installing tasks-axi is the smallest counterfactual and makes the representative shard execute the test with gate_skip=false in about 20 seconds. Both parallel jobs receive symmetric setup, while the exact 91-test inventory and coverage guard remain unchanged.

* feat(bin): make dispatch profiles quota aware (kunchenguid#867)

* feat: make dispatch profiles quota aware

* no-mistakes(review): Fix quota window and Grok product scoping

* no-mistakes(document): Document implicit quota-aware dispatch accurately

* Add built-in ahoy recap skill (kunchenguid#873)

* fix: preserve trustworthy Bearings data in partial snapshots (kunchenguid#875)

* fix: preserve mixed Bearings projections

* no-mistakes(review): Enforce strict invalidity precedence for partial snapshots

* no-mistakes(review): Enforce ownership for unknown child metadata

* no-mistakes(document): Document partial structured Bearings projections

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* feat(pi): add session-local calm mode (kunchenguid#884)

* Add session-local Pi calm mode

* no-mistakes(review): Preserve Pi HTML exports during calm mode

* no-mistakes(review): Preserve calm exports across submit bindings and share

* no-mistakes(document): Document calm-mode feasibility across supported harnesses

* fix(pi): prevent redundant watcher re-arms (kunchenguid#885)

* fix(pi): limit watcher arm tool to recovery

* no-mistakes(review): Strengthen Pi live re-arm regression coverage

* no-mistakes(document): Document Pi first-cycle and recovery-only watcher arming

* fix(pi): clean up Calm transcript rendering (kunchenguid#895)

* fix(pi): clean up Calm transcript rendering

* no-mistakes(review): Captain, preserve Calm exports and classify Pi launch briefs

* no-mistakes(review): Captain, eliminate Calm gaps and verify exported conversations

* no-mistakes(review): Restore Calm rows received while active

* no-mistakes(review): Preserve diagnostics during Calm restoration

* no-mistakes(document): Clarify Calm transcript behavior and injection paths

* fix: execute every PR body compliance event (kunchenguid#898)

* fix: execute every PR body compliance event

* no-mistakes(document): Document independent PR compliance events

* fix: exclude operational injections from ahoy boundaries (kunchenguid#899)

* fix: distinguish operational input in ahoy

* no-mistakes(review): Handle legacy Ahoy operational boundaries

* no-mistakes(review): Narrow legacy Ahoy boundaries with live regressions

* no-mistakes(document): Document Ahoy operational marker ownership

* no-mistakes(lint): Suppress intentional literal fixture lint warnings

* fix: canonically classify operational inputs across harnesses (kunchenguid#909)

* fix: type canonical operational inputs

* no-mistakes(document): Correct canonical operational-input documentation ownership

* fix: avoid generic secondmate start acknowledgements (kunchenguid#926)

* fix: avoid generic secondmate acknowledgements

* no-mistakes(document): Document sparse secondmate acknowledgement behavior

* no-mistakes: apply CI fixes

* fix(pi): make calm mode persistent and gapless (kunchenguid#927)

* fix(pi): preserve calm presentation across sessions

* no-mistakes(review): Fix Calm home fallback persistence

* no-mistakes(document): Clarify Calm gapless and export contracts

* no-mistakes: apply CI fixes

* fix(watch): retire merged PR polls after durable notification (kunchenguid#932)

* fix: retire merged PR polls after notification

* no-mistakes(review): Decouple PR retirement recovery from template updates

* no-mistakes(review): Recover pending PR retirements before poll migration

* no-mistakes(document): Document merged PR poll retirement contracts

* fix: refine scout intake and parallel dispatch (kunchenguid#934)

* Clarify intake evidence and overlap handling

* no-mistakes(review): Align scout guard with intake classification

* no-mistakes(document): Clarify scout documentation and intake ownership

* fix(pi): prevent duplicate assistant replies in Calm (kunchenguid#936)

* fix(pi): preserve operational follow-up semantics in Calm

* no-mistakes(document): Correct Calm operational-row visibility documentation

* perf(bin): shrink the ShellCheck source graph (kunchenguid#939)

* perf(lint): shrink shell source graph

* no-mistakes(review): Ensure lint workers terminate fully on cancellation

* no-mistakes(document): Repair stale lint documentation ownership

* fix(pi): remove Calm hidden-block gaps (kunchenguid#942)

* fix(pi): remove Calm hidden-block gaps

* no-mistakes(review): Validate Calm geometry against current viewport

* no-mistakes(review): Synchronize Calm geometry checks with reload completion

* fix: enforce contract boundaries for ask-user findings (kunchenguid#945)

* fix: escalate ask-user contract expansion

* no-mistakes(document): Point project management to authority owner

* docs: prefer direct operational paths (kunchenguid#946)

* fix(pi): hide operational user rows in Calm mode (kunchenguid#948)

* fix(pi): hide Calm operational user rows

* no-mistakes(review): Narrow Calm operational input suppression

* no-mistakes(review): Avoid Calm replay classifier subprocesses

* no-mistakes(document): docs: point Pi verification to Calm owner

* fix: relaunch missing second mates at session start (kunchenguid#950)

* fix(session-start): relaunch missing second mates

* fix(test): detect completed parallel workers

* no-mistakes(review): Isolate session-start recovery test cleanup

* no-mistakes(review): Complete backend-safe secondmate session recovery

* no-mistakes(review): Resolve Zellij task ownership before recovery

* no-mistakes(review): Recover relocated Zellij ghost tabs safely

* no-mistakes(review): Restore conservative Zellij recovery boundary

* no-mistakes(review): Reject malformed tmux recovery targets

* no-mistakes(document): Align secondmate recovery documentation

* no-mistakes: apply CI fixes

* fix(herdr): reclaim resumed task projections after restart (kunchenguid#967)

* fix(herdr): reclaim resumed task projections safely

* no-mistakes(review): Enforce safe Herdr reclaim close boundaries

* no-mistakes(document): docs: clarify Herdr restart projection contract

* Teach Ahoy to surface open decisions (kunchenguid#968)

* Require shipshape routine acknowledgement (kunchenguid#969)

* docs: separate current guidance from verification evidence (kunchenguid#994)

* docs: separate current guides from verification

* no-mistakes(review): Restore Herdr 0.7.5 restart-reclaim verification evidence

* fix: preserve Claude watcher continuity across Stop hooks (kunchenguid#997)

* feat(claude): Stop-owned tokenless watcher continuity via asyncRewake auto-arm

Claude primaries (main home and marked secondmate homes) no longer depend
on the model remembering to re-arm the watcher after each wake. A tracked
Stop asyncRewake hook (bin/fm-claude-stop-autoarm.sh, timeout 28800s)
fires on every turn end, claims one home-scoped single-flight owner,
foregrounds bin/fm-watch-arm.sh inside the hook-owned process tree, and
translates an actionable close or typed watcher failure into exactly one
exit-2 rewake. The hook scopes to genuine primary checkouts, requires the
session lock to be held by its own harness ancestor, stays inert while
AFK owns triage or the home is idle, and hands AFK transitions mid-cycle
to the daemon without rewaking.

The synchronous turn-end guard gains a --claude cooperative mode: it
ignores stop_hook_active (true on every post-continuation stop, which is
what re-opened the 2026-07-21 blind window), waits briefly for a watcher
health proof, a live auto-arm owner claim, or a fresh rewake epoch, and
re-blocks only when the auto-arm genuinely failed to establish - bounded
to 3 consecutive blocks per session, safely below Claude Code's 8-block
override, then a degraded allow with a visible systemMessage. Codex
keeps the previous one-block loop guard byte-identically, and Pi,
OpenCode, and Grok adapters are untouched.

Continuity PreToolUse gate and durable wake queue are preserved; the
gate's recovery guidance now names the Stop-owned re-arm and reserves
manual background arms for auto-arm failure. Claude supervision protocol,
harness-adapters facts, architecture, configuration, and continuity docs
updated; docs/turnend-guard.md records the 2026-07-24 Claude 2.1.218
contract revalidation (tokenless multi-cycle rewake, no-dedup, timeout
process-group kill, 8-block cap, interactive non-stall) and the 2.1.219
product live E2Es.

Regression matrix: hermetic tests cover scope, identity, AFK, need,
single-flight, translation, guard cooperation, budget, and registration;
the new live E2E proves two full tokenless auto-arm rewake cycles with
zero model arm commands; Pi and OpenCode Option B live E2Es pass
unchanged.

* no-mistakes(review): Fix Claude X-mode auto-arm continuity backstop

* no-mistakes(review): Remove unsupported Claude contract-lab verification claims

* no-mistakes(document): Update Claude auto-arm continuity documentation

* fix(herdr): clean stale projections at session start (kunchenguid#996)

* Clean stale Herdr projections at session start

* no-mistakes(document): Document stale Herdr session-start projection cleanup

* no-mistakes(review): Enforce locked exact Herdr projection cleanup

* no-mistakes(review): Fail closed on unverified session lock ownership

* no-mistakes(review): Serialize session lock acquisition atomically

* no-mistakes(document): Align session-start and Herdr cleanup documentation

* no-mistakes(document): Generalize lock-refusal diagnostics

* no-mistakes(lint): Avoid reserved keyword in concurrency test

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: recover Claude supervision without watcher-status gate (kunchenguid#1001)

* fix: recover Claude supervision at session start

* fix: remove Claude watcher-status command gate

* no-mistakes(document): docs: remove stale continuity gate references

* fix: make quota-aware profile selection agent-owned (kunchenguid#1018)

* Replace quota dispatch selector instructions

* no-mistakes(review): Align bootstrap docs with agent-owned dispatch selection

* fix(bin): remove vestigial dispatch selector (kunchenguid#1026)

* remove vestigial dispatch selector

* no-mistakes(review): Synchronize isolation proof and portable shard evidence

* no-mistakes(review): Correct shard history and proof archive date

* no-mistakes(review): Remove reintroduced selector documentation reference

* no-mistakes(document): Remove stale dispatch strategy documentation

* docs(agents): drop superseded interim quota-window rule (kunchenguid#1039)

quota-axi 0.1.13 emits schemaVersion 2 with a quotaSemantics object per
provider, so the successor named in the interim rule has landed and the
rule's own removal condition is satisfied.

Keep the ownership clause so quota-axi remains the single owner of how
model or product windows relate to bounding account windows, and drop
the interim weakest-headroom instruction. The unknown-semantics case is
already covered by the existing requirement to stop and report a
candidate whose applicable quota data or interpretation cannot be
established.

Drop the matching assertion phrase from
tests/fm-instruction-owners.test.sh; the retained ownership phrase still
asserts.

* fix(tmux): scope busy detection and recognize current Claude turns (kunchenguid#1049)

* fix(tmux): scope Claude busy detection by harness

* no-mistakes(review): Separate verified and fallback busy signatures

* no-mistakes(test): Scope busy signatures to supplied harnesses

* no-mistakes(document): Document harness-scoped busy detection

* feat: add verified Kimi crewmate adapter (kunchenguid#1047)

* Add verified Kimi crewmate harness adapter

* no-mistakes(review): Scope Kimi moon detection to spinner lines

* no-mistakes(review): Match only complete Kimi spinner rows

* no-mistakes(review): Resolve Kimi binary portably before pane creation

* no-mistakes(document): Align Kimi adapter documentation

* no-mistakes(lint): Suppress false-positive ShellCheck warning for sourced watcher override

* Fix Kimi busy spinner detection

* no-mistakes(review): Recognize Kimi session-lock ancestry and holders

* no-mistakes(review): Scope pending-reply Kimi busy detection by harness

* no-mistakes(document): Correct Kimi spinner capture documentation

* no-mistakes(document): Clarify optional Kimi spinner whitespace

* no-mistakes(lint): Silence intentional pending-reply test stub warnings

* test: align rebased Kimi busy fixtures

* no-mistakes: apply CI fixes

* Reconcile Kimi busy detection after per-harness scoping

* no-mistakes(review): Clarify observed Kimi spinner whitespace contract

* no-mistakes(document): Clarify Kimi harness documentation

* fix: harden Kimi submission and spinner matching (kunchenguid#1058)

* fix kimi pointer submission and spinner conformance

* no-mistakes(review): Preserve Kimi submit target ownership guard

* feat(bin): add guarded Kimi turn-end wake (kunchenguid#1059)

* Add guarded Kimi turn-end hook

* no-mistakes(review): Require jq before installing Kimi turn-end hook

* no-mistakes(review): Expose jq inside isolated Kimi test fixtures

* no-mistakes(review): Preserve Kimi config boundaries during hook removal

* no-mistakes(review): Document Kimi removal newline safeguard

* no-mistakes(document): Document Kimi shared-home preservation

* fix(tmux): classify bordered composers across all rows (kunchenguid#1066)

* Fix structural tmux composer reading

* Verify Calm compatibility with Pi 0.82

* no-mistakes(review): Harden structural composer classification boundaries

* no-mistakes(review): Refresh composer and Kimi regression fixtures

* no-mistakes(review): Fail closed on unbounded composer edges

* no-mistakes(review): Enforce aligned composer geometry safely

* no-mistakes(review): Make composer ambiguity locale-safe

* no-mistakes(review): Preserve ambiguity through composer submission

* no-mistakes(review): Carry composer proof through retries

* no-mistakes(document): Document structural tmux composer delivery guarantees

* no-mistakes: apply CI fixes

* feat(bin): add verified pi-signed runtime adapter (kunchenguid#1145)

* feat: add verified pi-signed adapter

* no-mistakes(review): Correct pi-signed maintainer verification date

* no-mistakes(review): Correct remaining pi-signed verification dates

* no-mistakes(review): Preserve authoritative pi-signed runtime identity

* no-mistakes(document): Document pi-signed shared adapter semantics

* no-mistakes: apply CI fixes

* fix(pi): rearm watcher across session transitions (kunchenguid#1166)

* fix(pi): rearm watcher across same-process session transitions

Pi emits session_shutdown for ordinary /new, /resume, and /fork replacement
as well as terminal quit. The primary watcher extension latched a module-level
stopping flag on every shutdown, so a replacement session in the same process
could not arm monitoring until Pi restarted.

Own arm authority per session generation so only the active live generation
may start, stop, or rearm the child. Replacement sessions can arm again without
restarting Pi, stale prior-generation callbacks cannot mutate the active cycle,
and real quit still blocks late rearm.

* no-mistakes(review): Preserve Pi generation isolation and exit cleanup

* no-mistakes(document): Correct Pi watcher transition documentation

* feat: route crew dispatch using quota-window pace (kunchenguid#1172)

* Consume quota-axi pace signals in dispatch profile array selection.

Add quota-array-dispatch as the single owner of the pace-aware candidate
choice, keep AGENTS.md to the intake boundary and load trigger, and cover
the acceptance cases with sanitized schemaVersion 3 fixtures.

* no-mistakes(review): Stop and report genuine quota dispatch ties

* no-mistakes(document): Document quota pace freshness and uncertainty

* fix: adapt Grok Stop continuation and harden endpoint cleanup (kunchenguid#1171)

* fix(grok): adapt Stop continuation to runtime capability

* no-mistakes(review): Reject ambiguous Grok Stop payloads

* no-mistakes(review): Reject duplicate Grok fields and accept spaced tmux sessions

* no-mistakes(review): Enforce exact tmux cleanup selectors

* no-mistakes(test): Fix historical tmux fixture and validate Grok Stop

* no-mistakes: apply CI fixes

* fix: restore stock macOS Bash 3.2 brief scaffolding (kunchenguid#1093)

* fix(brief): make DOD scaffolding parse-safe on stock macOS Bash 3.2

fm-brief.sh built each Definition-of-done block and the not-enabled
Herdr declaration with `VAR=$(cat <<EOF ... EOF)`. On Bash 3.2 (macOS
/bin/bash) the lexer scans for the command substitution's closing `)`
textually and tracks quote state through the heredoc body, so a single
apostrophe, unbalanced quote, or unbalanced paren in that prose breaks
parsing of the whole script. Every ship-brief scaffold (no-mistakes,
direct-PR, local-only) failed with `unexpected EOF while looking for
matching )`. Bash 4+ parses it fine, so the breakage stayed invisible
everywhere except stock macOS.

Replace all four command-substitution heredocs with
`IFS= read -r -d '' VAR <<EOF || true`. That removes the `$(...)`
wrapper and the entire defect class regardless of future prose, and
preserves the variable expansion the direct-PR and local-only bodies
need. `read` keeps the heredoc's trailing newline that `$(...)` used to
strip, so trim one newline to keep every generated brief byte-identical
to prior output.

Guard the structure, not one historical phrase: a new test rejects any
heredoc nested in a command substitution anywhere in fm-brief.sh, where
the old assertion pinned a single apostrophe phrase and so missed the
reintroduction. Extend the stock-macOS Bash CI job from parsing one
script to the whole maintained shell surface (bin/*.sh,
bin/backends/*.sh, tests/*.sh), matching bin/fm-lint.sh's canonical file
set so parse scope and lint scope cannot drift apart.

* no-mistakes(review): Captain: harden Bash structure and inventory guards

* no-mistakes(document): Align stock macOS Bash contributor checks

* no-mistakes(lint): Suppress deliberate SC2016 literal fixture warnings

* test: stabilize tmux teardown conformance baseline (kunchenguid#1209)

* fix(test): pin teardown tmux baseline to historical kill selectors

merge-base HEAD main collapses to HEAD after the exact-selector change
lands on the default branch, so the old teardown fixture was accidentally
exercising current exact targets. Resolve a content-historical permissive
tmux adapter from first-parent history and force that post-squash topology
inside the conformance case so main and feature branches keep the same
old-vs-new contract.

* no-mistakes(lint): Suppress intentional literal-pattern ShellCheck warnings

* docs: slim quota-array-dispatch to the pace selection core (kunchenguid#1197)

Cut the runtime skill to the compact pace-aware selection procedure plus
minimum owner pointers. Keep every distinct decision rule and move expanded
acceptance scenarios to deterministic fixture ownership assertions.

Size: 170/1374/10187 -> 63/544/4068 (about 63%/60%/60% reduction).

* feat(bin): inherit backend config into secondmate homes (kunchenguid#1219)

* Inherit config/backend into secondmate homes with deliberate-override preservation

Add backend to the shared inheritable config allowlist so launch, locked
bootstrap, and config-push converge a primary pin into secondmate homes as each
home local future-spawn default. Track last-inherited bytes in a private state
provenance marker so deliberate per-home overrides survive present and absent
primary convergence, keep --backend and FM_BACKEND stronger, and extend the
existing inheritance tests plus docs and skill claims.

* no-mistakes(review): Preserve equal unprovenanced backend overrides

* no-mistakes(review): Preserve symlink overrides and verify spawn precedence

* no-mistakes(review): Snapshot backend inheritance for consistent provenance

* no-mistakes(review): Simplify backend inheritance to primary-authoritative convergence

* no-mistakes(document): Document inherited backend override preservation

* fix: restore primary-authoritative backend inheritance after document regression

The document step reintroduced provenance and deliberate per-home override
semantics after review had simplified config/backend to plain primary-authoritative
allowlist membership. Restore the primary-always-wins path: present overwrites,
absent removes, no provenance marker, and docs/tests match that contract.

* no-mistakes(review): Add divergent backend precedence regression fixtures

* no-mistakes(document): Document backend inheritance contract

* fix(pi): remove Calm's upper version ceiling (kunchenguid#1226)

* fix(pi): remove Calm's exclusive Pi upper-version ceiling

tests/fm-calm-pi-extension.test.sh gated on a closed PI_COMPAT_VERSIONS
allowlist ("0.81.1 0.82.0") that refused any other installed Pi, and docs
described that range as "supported" rather than verified evidence. The
Calm CHANGELOG shows no API introduced at either version, so there is no
evidence for a real minimum; the presentation adapters already probe the
exact method they patch rather than checking a version.

Replace the allowlist with dated version evidence that never rejects a
newer Pi, and make each presentation adapter degrade independently with
a diagnostic if a future Pi removes its API, instead of the whole Calm
extension failing to load. Rewrite the feasibility doc's "Pi 0.81.1
through 0.82.0" phrasing to state it as verified evidence, not a
ceiling.

* no-mistakes(review): Probe missing Calm adapter exports safely

* no-mistakes(document): Document Calm's unbounded Pi compatibility

* fix(bin): allow session-local todo tools in the subagent guard (kunchenguid#1204)

* fix(guard): allow session-local todo tools in the primary

The delegation-shape guard denied TaskCreate and TaskUpdate because their
normalized names contain the `task` stem. Those tools write only the harness's
session-local todo list, which has no executor: it spawns no agent, allocates
no worktree, registers no schedule, and starts nothing that outlives the
session. That is not the unaccounted work the guard exists to stop, so the stem
match was a false positive, and the deny text told the primary to run
bin/fm-brief.sh and bin/fm-spawn.sh to create a todo entry.

Add a separately-reasoned PLAN_ONLY_TOOLS exact-name exclusion rather than
widening OBSERVE_ONLY_TOOLS, whose documented contract is tools that only
observe or stop existing work. Both lists stay exact-name so neither can widen
by substring.

Tests cover the two allowed names and six near-miss names that a substring or
shortened-stem widening would release; both mutations were watched red.

* no-mistakes(review): drop session-local todo tools from recommended deny list

* no-mistakes: apply CI fixes

* fix(session-lock): resolve Claude bg-spare ancestry to the outermost claude pid (kunchenguid#1206)

* fix(session-lock): resolve Claude bg-spare ancestry to the outermost claude pid

fm_harness_ancestry_pid() previously returned the first ancestor process
whose command matched a verified harness name. Claude Code's Stop hook
fires as a bg-spare worker several levels below the session's actual
lock-owning claude process (hook shell -> claude bg-spare ->
claude bg-pty-host -> claude -> claude(lock)), so the first match was
the bg-spare worker, not the lock owner. fm_session_lock_owned_by_self()
then never matched state/.lock, and the Claude Stop auto-arm silently
treated its own primary session as an unrelated live owner and never
armed the watcher.

The walk now keeps going past a claude-named match, looking for a still
more ancestral claude-named match, and stops the instant a non-match
follows an already-found match (bounding it to a contiguous run rather
than the literal ancestry top, so an unrelated claude-named process
further up the real process tree is never mistaken for part of this
session's own nested chain). Every other harness keeps the original
first-match-wins behavior, since e.g. Pi's shared signed-wrapper
ancestry actually holds the session at the inner engine pid, not an
outer wrapper pid. Hop limit raised from 8 to 16 to cover the deeper
bg-spare chain.

* no-mistakes(review): Add nested-claude-ancestry regression test; fix nudge doc depth claim

* no-mistakes: apply CI fixes

* fix: conferma l'avvio del watcher su Windows/MSYS (kunchenguid#1212)

* fix: confirm watcher startup on MSYS

* no-mistakes(review): gate MSYS arm ready timeout, cache uname, harden locale test

* no-mistakes(review): validate OpenCode ready timeout, make uname cache internal

* fix(spawn): forward CLAUDE_CONFIG_DIR to claude crewmates (kunchenguid#1195)

* fix(spawn): forward firstmate's CLAUDE_CONFIG_DIR to claude crewmates

Crewmate panes are created by a long-lived tmux/herdr daemon that does not
inherit firstmate's current environment. When firstmate runs under a non-default
CLAUDE_CONFIG_DIR (for example a work-vs-personal subscription split), a bare
`claude` in the crewmate pane fell back to the default ~/.claude store and
launched unauthenticated, blocking the crewmate before it could do any work.

fm-spawn now prefixes the claude launch with firstmate's own resolved
CLAUDE_CONFIG_DIR when set, so the crewmate uses the same credential/config
store firstmate is authenticated with. An unset value is the single-store
default and adds no prefix; non-claude harnesses are unaffected.

Adds three tests in fm-spawn-dispatch-profile.test.sh (forwarded-when-set,
omitted-when-unset, non-claude-ignored) and pins CLAUDE_CONFIG_DIR in the test
helper so launch assertions no longer depend on the developer's environment.

* no-mistakes: apply CI fixes

* no-mistakes(review): harden teardown kind=adhoc endpoint-gate exemption

* no-mistakes(document): document ad-hoc teardown exemption and adhoc meta fields

* no-mistakes(document): pin kind=adhoc cleanup carve-out with regression evidence

---------

Co-authored-by: ItsFlow <[email protected]>
Co-authored-by: Kun Chen <[email protected]>
Co-authored-by: Christopher McKay <[email protected]>
Co-authored-by: Daniel Kuykendall IV <[email protected]>
Co-authored-by: Trillium Smith <[email protected]>
Co-authored-by: Unknownzed <[email protected]>
Co-authored-by: lhalbert <[email protected]>
quinnbot-ai pushed a commit to quinnbot-ai/firstmate that referenced this pull request Jul 30, 2026
…enguid#1204)

* fix(guard): allow session-local todo tools in the primary

The delegation-shape guard denied TaskCreate and TaskUpdate because their
normalized names contain the `task` stem. Those tools write only the harness's
session-local todo list, which has no executor: it spawns no agent, allocates
no worktree, registers no schedule, and starts nothing that outlives the
session. That is not the unaccounted work the guard exists to stop, so the stem
match was a false positive, and the deny text told the primary to run
bin/fm-brief.sh and bin/fm-spawn.sh to create a todo entry.

Add a separately-reasoned PLAN_ONLY_TOOLS exact-name exclusion rather than
widening OBSERVE_ONLY_TOOLS, whose documented contract is tools that only
observe or stop existing work. Both lists stay exact-name so neither can widen
by substring.

Tests cover the two allowed names and six near-miss names that a substring or
shortened-stem widening would release; both mutations were watched red.

* no-mistakes(review): drop session-local todo tools from recommended deny list

* no-mistakes: apply CI fixes
allstargg added a commit to allstargg/firstmate that referenced this pull request Jul 30, 2026
* fix: prevent no-mistakes gate agents from driving the fleet (#518)

* feat: contain no-mistakes gate agents from driving the fleet

Add bin/fm-gate-refuse-lib.sh, sourced at the top of fm-spawn/fm-send/
fm-teardown before any fleet mutation. It fails closed when NO_MISTAKES_GATE
is set, and via an unspoofable git-common-dir backstop when invoked from a
no-mistakes gate worktree (.no-mistakes/repos/*.git) even with the marker
unset. A normal firstmate session has neither signal and is unaffected.

Set disable_project_settings: true in the tracked .no-mistakes.yaml so the
installed pipeline neutralizes gate agents' project instructions for this repo
(trusted-only, honored from the default branch).

firstmate's own suite runs from a gate worktree during validation, so the
shared test helpers set FM_GATE_REFUSE_BYPASS=1 to exempt it; the dedicated
tests/fm-gate-refuse.test.sh strips it to verify real refusal.

* no-mistakes(review): Captain, refuse empty no-mistakes gate markers

* no-mistakes(document): Document no-mistakes gate authority boundary

* fix: guard secondmate primary sessions from blind turn ends (#505)

* fix: guard secondmate own-home turn ends

Remove the .fm-secondmate-home early-exit in fm-turnend-guard.sh so the
'no turn ends blind' backstop fires in a secondmate's own primary session,
matching the cd-guard's scope: the own home is guarded, child crew/scout
worktrees stay exempt via the retained git-dir/git-common-dir test. This
was pure scoping from the guard's primary-only origin and guarded against
no secondmate-specific hazard.

Add secondmate regression tests (blind-turn block, idle-by-default,
stop_hook_active loop guard, deferred-death recovery loop, child-worktree
exemption) and record the autonomous background-notify re-invoke
measurement (Claude Code 2.1.207, 11s) in docs/turnend-guard.md.

* no-mistakes(document): Correct secondmate guard documentation, captain

* fix: force-include marked secondmate homes in turn-end guard

The prior remove-only form (just deleting the .fm-secondmate-home check)
left the DEFAULT secondmate topology unguarded: a treehouse-leased home is
a linked git worktree (git-dir != git-common-dir), which the retained
git-dir exemption still skipped, so its own primary session could still end
a turn blind. Invert the marker: a genuinely-marked home is force-included
as a guarded primary (treehouse-leased linked OR git-cloned plain), and the
git-dir exemption applies only to UNMARKED child worktrees. Marker
validation (regular non-symlink file, non-empty id-token content) blocks a
stray or empty marker from spoofing inclusion.

Add real linked-worktree regression tests: a treehouse-leased LINKED
secondmate home is guarded, a stray/empty marker stays exempt, and the
unmarked child worktree stays exempt - the topology the plain git-init
fixtures masked. Predicates, in-flight gate, and loop guard untouched.

* fix: force ASCII collation in secondmate marker validation

Add a function-scoped local LC_ALL=C in fm_root_is_secondmate_home so the
[A-Za-z0-9._-] id allowlist matches under C collation, not the ambient
locale - a locale-crafted non-ASCII marker id can no longer slip through
the range match and spoof force-inclusion of a linked child worktree.
Add a regression test proving a non-ASCII marker id is rejected and the
linked worktree stays exempt.

* no-mistakes(test): fix backend baseline gate-refusal dependency

* no-mistakes(document): Correct secondmate turn-end guard documentation

* fix: make bootstrap diagnostics backend-aware (#519)

* fix: make bootstrap required-tool detection backend-aware

Bootstrap demanded tmux and treehouse for every backend except orca, so a
herdr/zellij/cmux home with tmux absent was wrongly told MISSING: tmux.

Required tools now follow the resolved backend via the single-owner
fm_backend_required_tools helper (bin/fm-backend.sh): each backend's own
session-provider CLI, jq for the JSON-emitting adapters (herdr/zellij/cmux),
and treehouse for session-provider-only backends (orca owns its worktree).
The treehouse lease-support check is gated to backends that use treehouse.

Adds install hints for herdr/zellij/cmux, regression tests for the full
backend dependency matrix (herdr-without-tmux repro plus each boundary),
and updates the authoritative Toolchain docs.

* no-mistakes(review): Captain, prevent executing Herdr install guidance

* no-mistakes(review): Captain, harden backend-aware bootstrap diagnostics

* no-mistakes(review): Captain, separate manual dependency remediation

* no-mistakes(review): Captain, align bootstrap diagnostic consumers

* no-mistakes(document): Align backend adapter dependency comments

* fix: preserve follow-up platform context after inbox cleanup (#520)

* fix: recover X/Discord follow-up platform after inbox cleanup

A milestone follow-up posted directly by request_id after the inbox was
drained - and with no task link, because one persistent secondmate's single
x_request slot collides across concurrent requests - resolved platform only
from the local inbox, so a >280 Discord reply silently defaulted to the X
280-char budget and threaded as (1/2).

- fm-x-poll records a durable per-request reply context
  (state/x-context/<rid>.json) at stash time, keyed by request_id so
  concurrent requests never overwrite each other; it survives inbox cleanup
  and restart.
- fm-x-reply resolves platform/budget through registry -> inbox -> relay
  (the relay lookup confined to a live follow-up), recovering the original
  platform independent of task-link availability.
- Fail-safe: a follow-up whose platform/budget cannot be authoritatively
  resolved and that would split is refused (exit 8) and held for retry,
  never wrongly split; fm-x-followup keeps the link on that exit.
- fm-x-dismiss clears the durable context for a dismissed mention.

Refactors reply-context extraction into a single owner and adds regression
coverage for all four cases.

* no-mistakes(review): Captain, fail closed on incomplete follow-up context

* no-mistakes(review): Captain, bound X context registry retention

* no-mistakes(review): Captain, align context retention with answer binding

* no-mistakes(document): Align X follow-up context documentation

* no-mistakes(document): Align durable X follow-up documentation

* fix: preserve secondmate routing markers in terminal sends (#533)

* fix: preserve secondmate routing markers

* no-mistakes(review): Captain, preserve trailing newlines in marked secondmate sends

* no-mistakes(test): Captain, tolerate bootstrap timeout elapsed drift

* no-mistakes(document): Refresh Herdr marker documentation

* fix: align Grok effort handling with 0.2.99 (#527)

* fix: align grok effort docs and spawn with 0.2.99 ceiling

grok 0.2.99 accepts only low|medium|high for --reasoning-effort and
rejects both xhigh and max. Omit unsupported values on spawn, flag them
in crew-dispatch validation, and update harness-adapters.

* no-mistakes(test): Captain: refresh gotmp teardown fixture dependencies

* no-mistakes(document): Clarify Grok effort documentation ownership

* fix: derive bearings from authoritative secondmate state (#555)

* fix: make bearings use secondmate home state

* test: anonymize bearings fixtures

* no-mistakes(review): Bound parent activity evidence scans, captain

* no-mistakes(review): Preserve structured secondmate authority and bounds, captain

* no-mistakes(review): Preserve registry completeness and child inventory, captain

* no-mistakes(review): Reconcile parent evidence by verb and key, captain

* no-mistakes(review): Treat unkeyed parent evidence as inconclusive, captain

* no-mistakes(document): Document bearings local snapshot and PR opt-in

* no-mistakes(lint): Fix fleet snapshot ShellCheck findings

* no-mistakes: apply CI fixes

* fix: restore fleet snapshots on stock macOS Bash (#578)

* fix: restore stock macOS snapshot parsing

* no-mistakes(document): Clarify Linux gate and macOS CI coverage

* fix(afk): make Pi escalation and return catch-up reliable (#587)

* fix: close away-mode blocker supervision gap

* no-mistakes(review): Gate teardown retries and verify U+2063 dedupe

* no-mistakes(test): Fail closed on incomplete Pi composer separators

* no-mistakes(document): Document Pi composer recognition and return gating

* feat: support Pi max reasoning profiles (#537)

* support Pi max thinking profiles

* no-mistakes(review): Captain, allow Pi max dispatch profiles

* chore: no-mistakes(document): Clarify yolo response ownership (#595)

* Clarify validation response ownership

* no-mistakes(document): Clarify yolo response ownership

* feat: establish instruction ownership foundation (#619)

* Add instruction owners foundation

* no-mistakes(document): Refresh project-management owner pointers

* fix: compress Firstmate contract and enforce delivery rigor ownership (#626)

* docs: compress firstmate operating contract

* docs: make delivery rigor single-owner

PR B already removed personal and stacked review requirements, but it did not explicitly assign rigor to the selected delivery path or forbid risk-based manual clean gates. That gap still permitted the Hi Bit inversion.

* no-mistakes(review): Honor configured merge authority across faster delivery paths

* no-mistakes(document): Align docs with compressed operating contract

* feat: add durable captain decision holds (#593)

* Add durable captain decision holds

* no-mistakes(review): Validate decision hold retries and origin paths

* no-mistakes(review): Enforce durable decision lifecycle boundaries

* no-mistakes(review): Harden decision display and partial retry recovery

* no-mistakes(test): Update scout teardown fixtures for decision inventory

* no-mistakes(document): Align decision lifecycle and scout teardown documentation

* no-mistakes: apply CI fixes

* no-mistakes(review): Reconcile terminal decision holds

* no-mistakes(document): Align captain decision-hold documentation

* fix(bin): harden PR check artifacts (#556)

* fix: harden PR check artifacts

* fix: close PR check migration gaps

* fix: close PR check retry gaps

* fix: clarify migration outcomes and ESM boundary

* fix: keep failed migrations authoritative

* test: use inert PR validation fixtures

* no-mistakes(review): Reserve noncanonical PR quarantine namespace

* no-mistakes(review): Prevalidate final PR-check teardown artifacts

* no-mistakes(review): Preserve X metadata and validate teardown IDs

* no-mistakes(review): Initialize migration state before watcher exclusion

* no-mistakes(review): Isolate failed poll migrations from bootstrap recovery

* no-mistakes(review): Allow safe polling during incomplete private repairs

* no-mistakes(review): Authenticate watcher checks at execution time

* no-mistakes(review): Preserve custom checks with hash-bound registration

* no-mistakes(review): Clean custom check snapshots on watcher signals

* no-mistakes(review): Stop watcher checks promptly on signals

* no-mistakes(review): Terminate watcher check groups before cleanup

* no-mistakes(document): Correct stale X-mode watcher documentation

* fix: drain returned watcher check groups

* no-mistakes(review): Harden quarantine links and recover validated replacement polls

* no-mistakes(review): Preserve X mode across shim version transitions

* no-mistakes(review): Refresh legacy X shims before marker short-circuits

* no-mistakes(document): Correct persisted PR-check artifact documentation

* no-mistakes(document): Correct stale PR-check documentation

* fix: bind PR poll repair provenance

* no-mistakes(review): Enforce single-link ownership for custom check artifacts

* no-mistakes(review): Preserve private checks, X polling, and lifecycle IDs

* no-mistakes(review): Separate task creation and legacy teardown validation

* no-mistakes(review): Restore safe legacy operations and teardown validation

* no-mistakes(review): Disambiguate migration obligations and preserve legacy retries

* no-mistakes(review): Preserve fail-closed diagnostics and legacy quarantine evidence

* no-mistakes(review): Reconcile legacy migration retries and teardown collisions

* no-mistakes(review): Force legacy namespace reconciliation before marker short-circuits

* no-mistakes(document): Document private poll artifact safety contracts

* no-mistakes(lint): Suppress intentional literal-dollar lint finding

* fix: migrate historical X poll identity

* fix: harden PR check artifacts

* no-mistakes(review): Preserve fail-closed diagnostics and legacy quarantine evidence

* no-mistakes(review): Reconcile legacy migration retries and teardown collisions

* fix: migrate historical X poll identity

* no-mistakes(review): Harden X-mode artifact publication against symlink corruption

* no-mistakes(review): Guard X artifact publication

* no-mistakes(review): Enforce private X artifact reads

* no-mistakes(test): Fix backend compatibility fixture dependencies

* no-mistakes(document): Refresh PR-check documentation

* no-mistakes(lint): Remove unused x-mode test locals

* no-mistakes: apply CI fixes

* fix(bin): compact session-start backlog digest (#636)

* fix: compact session-start backlog digest

* no-mistakes(test): Fix legacy backend fixture helper

* no-mistakes(test): Fix watcher exit wait helper

* no-mistakes(document): Document compact backlog digest

* fix: dedupe stale watcher guard banners (#637)

* fix: dedupe stale watcher guard banner

* no-mistakes(review): Keep read-only guard state nonmutating

* no-mistakes(document): Clarify stale watcher docs

* fix(bin): balance bearings landed baseline (#640)

* fix: balance bearings landed defaults

* no-mistakes(document): Document balanced landed baseline

* no-mistakes: apply CI fixes

* fix: clarify captain-facing translation contract (#644)

* docs: clarify captain-facing translation contract

* no-mistakes(review): Restore runtime fallback mandate

* no-mistakes(document): Align Bearings translation wording

* fix(bin): make bootstrap output and nudges deterministic (#646)

* fix: make bootstrap nudges deterministic

* no-mistakes(review): Honor state override for bootstrap nudges

* no-mistakes(review): Update benign bootstrap documentation labels

* no-mistakes(review): Validate bootstrap nudge retry markers

* no-mistakes(document): Align bootstrap nudge documentation

* no-mistakes: apply CI fixes

* docs(secondmate-provisioning): clarify concise registry ownership (#649)

* Clarify concise secondmate registry contract

* no-mistakes(review): Expand secondmate registry boilerplate coverage

* no-mistakes(document): Point route docs to owner

* fix(bin): strip quoted blocked_by values during decision hold resolve (#654)

* fix(bin): strip quotes on blocked_by in decision-hold resolve

tasks-axi quotes multi-entry blocked_by as "a,b,c", so the comma-boundary
membership test only matched middle elements. Strip surrounding quotes
before matching so first and last hold ids resolve correctly.

* no-mistakes(document): Refresh decision-hold regression evidence

* feat(secondmate): inherit shared captain preferences (#656)

* feat(secondmate): inherit shared captain preferences

* no-mistakes(review): Honor shared captain data overrides

* no-mistakes(review): Honor bootstrap data override registry

* no-mistakes(document): Refresh shared inheritance docs

* no-mistakes(document): Clarify inherited local-material docs

* feat: gate local agent secret injection (#658)

* feat(spawn): gate local agent secret injection

* fix(spawn): align final Keychain slot

* no-mistakes: apply CI fixes

* test: isolate Herdr autodetect smoke sessions (#662)

* test: isolate herdr autodetect smoke session

* no-mistakes(review): Restored autodetect smoke gate bypass

* no-mistakes(test): Harden Herdr lab provisioning

* no-mistakes(document): Refresh Herdr lab docs

* docs: adopt under way for active work (#666)

* Revert "feat: gate local agent secret injection (#658)" (#668)

This reverts commit c27135cd9d35bc4c237d49b3b374da31fbd52eef.

* fix(pi): distinguish stale locks when arming watcher (#681)

* fix(pi): distinguish stale locks when arming watcher

* no-mistakes(test): Stabilize watcher extension async waits

* no-mistakes(document): Document Pi lock recovery

* fix: accept secondmate house vocabulary (#685)

* fix: accept secondmate as house vocabulary

* no-mistakes(test): Update captain vocabulary contract test

* no-mistakes(document): Align secondmate documentation vocabulary

* fix(bin): parse handoff homes after registry parentheticals (#686)

* fix: parse secondmate home after pre-field parentheses

Registry summaries often include parentheticals before the structured
(home: ...) field. Match that field with a greedy prefix so handoff
no longer reports "has no home" for those entries.

* no-mistakes(document): Refresh handoff test comments

* feat: add native session-start nudges (#687)

* feat: add native session-start nudges

* no-mistakes(document): Document nudge script inventory

* docs: call built-in defaults the firstmate repo, not template (#688)

Relabel absent-captain and related domain defaults wording so it names
the firstmate repo rather than treating "template" as this domain's
identity label. Keep the design-tenet "shared template" statements and
unrelated launch/PR-poll template uses unchanged.

* fix(bin): repair fm-brief.sh parse error and harden set -u array expansion (#205)

* fix(bin): use set -u-safe empty-array expansion in pr-merge and spawn

Expanding "${arr[@]}" on an empty array under set -u fails on bash < 4.4
(notably macOS bash 3.2). Quote the portable "${arr[@]+"${arr[@]}"}" idiom
in fm-pr-merge and fm-spawn batch dispatch so empty arrays expand to nothing.

Co-authored-by: Cursor <[email protected]>

* test(brief): harden fm-brief regression coverage for parse and scaffolds

Tighten bash -n checking, pin literal backtick rendering in the no-mistakes
DOD wording assertion, and keep a scout/secondmate scaffold smoke test so the

Co-authored-by: Cursor <[email protected]>
#166 apostrophe regression cannot return unnoticed.

---------

Co-authored-by: Cursor <[email protected]>

* fix(bin): keep watcher supervision continuous across child cycles (#693)

* fix: make watcher supervision continuous

* no-mistakes(review): Bound watcher retries and log attached signals

* no-mistakes(review): Add bounded successor-recovery wake fallbacks

* no-mistakes(review): Prevent overlapping successor-arm retries

* no-mistakes(review): Resume supervision after late arm closes

* no-mistakes(review): Bind OpenCode recovery to attempted arm

* no-mistakes(test): Synchronize peer beacon regression fixture

* no-mistakes(test): Synchronize Pi and OpenCode late-close lifecycle fixtures

* no-mistakes(document): Captain: document watcher successor protocol behavior

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* no-mistakes: apply CI fixes

* fix: fetch current PR head for review diffs (#722)

* fix: always fetch PR head for review diffs

Prefer a freshly fetched refs/pull/<n>/head over a reachable recorded
pr_head= so reviewers never hold a merge over a "missing" fix that already
landed on the remote PR. Recorded SHA is offline fallback only; local branch
is last resort with a warning. Store the tip under refs/fm-review/ so a later
base-branch fetch cannot clobber the compare tip via FETCH_HEAD.

* no-mistakes(test): Isolate session-start nudge tests from gate state

* no-mistakes(document): Correct review-diff documentation

* docs: resolve five contract contradictions across AGENTS.md, README, and skills (#736)

* docs: resolve five contract contradictions

* no-mistakes(test): align owner-pointer assertions with reworded docs; skip absent shellcheck

* docs(harness): correct Grok exit guidance (#742)

* docs(harness): reverify grok exit command

* no-mistakes(test): Correct Grok exit resume attribution

* fix(watcher): bound stale wakes for parked crew (#743)

* fix(watcher): bound stale wakes for exited paused crew

* no-mistakes(review): Gate pause suppression on confirmed agent death

* no-mistakes(test): Fixed stale pause cadence

* no-mistakes(document): Document dead-agent hold cadence

* fix(supervision): distinguish ordinary wakes from recovery (#744)

* fix(supervision): distinguish ordinary wakes from repair

* no-mistakes(review): Make passive guard follow-ups recovery-only

* no-mistakes(document): Clarify recovery-only turn-end guard documentation

* fix(x-mode): dedupe pending mention wakes (#745)

* fix(x-mode): dedupe pending mention wakes

* no-mistakes(review): fix x-poll claim error deduplication

* no-mistakes(review): separate claim diagnostics from relay recovery

* no-mistakes(document): Document X-mode once-only mention wakes

* feat(wake): enrich drained signals with bounded status context (#747)

* feat(wake): enrich drained signal context

* no-mistakes(review): Bound wake enrichment reads

* no-mistakes(document): Document wake-drain annotations

* docs(wake): explain at-least-once drain boundary

* no-mistakes(review): Prevent symlink races in wake annotations

* no-mistakes(review): Exercise wake symlink race regression

* test: document intentional AFK marker subprocesses

* fix(wake): isolate annotation marker state

* feat(herdr): add optional presentation spaces (#784)

* feat(herdr): add optional presentation spaces

* no-mistakes(review): Harden Herdr projection creation and spawn serialization

* no-mistakes(review): Captain, disarm Herdr cleanup before launch submission

* no-mistakes(test): Correct stale Orca metadata failure fixture

* no-mistakes(document): Document Herdr presentation projection accurately

* fix(send): treat opencode busy-queued composer state as submitted (#775)

* fix(send): treat opencode busy-queued composer state as submitted

When fm-send sends a message to a BUSY opencode crewmate on the tmux
backend, opencode accepts the Enter and queues the message for the next
turn, but leaves the typed text visible in the composer row.  The
submit-verification loop sees a pending composer, exhausts retries, and
reports a false "Enter swallowed" failure while the message is actually
delivered.

Fix: after Enter retries are exhausted and the composer still shows
pending, check fm_pane_is_busy.  If the pane is busy (agent mid-turn,
footer shows "esc interrupt"), the harness queued the message, so
return "empty" (accepted).  On an idle pane, keep returning "pending"
(genuine swallow detection preserved).

Regression tests cover four scenarios:
- busy pane + pending composer -> empty (message queued)
- idle pane + pending composer -> pending (genuine swallow)
- busy pane + composer clears on first Enter -> empty
- idle pane + composer clears on first Enter -> empty (existing path)

* docs: document busy-queued Enter exception across backend docs and skills

Add explanatory comments and backend documentation for the
busy-queued Enter fix (opencode 1.18.4 accepts Enter mid-turn
but keeps typed text in composer until the turn ends):

- bin/fm-tmux-lib.sh: document the busy-aware fallback in the
  file header and above fm_tmux_submit_enter_core
- .agents/skills/afk/SKILL.md: daemon-facing policy note
- .agents/skills/harness-adapters/SKILL.md: harness-specific fact
- docs/tmux-backend.md: submit-acknowledgement section with the
  busy-queue exception
- docs/herdr-backend.md: record the known gap
- docs/architecture.md: cross-reference in the daemon section

* test(tmux): fix SC2181 and make busy-submit test executable

* fix(spawn): require two stable reads before accepting worktree path (#765)

* fix(spawn): require two stable reads before accepting worktree path

The treehouse-get worktree-detection loop in fm-spawn.sh accepted the
first pane_current_path read that differed from the project path, but
on some tmux/WSL setups a brand-new window transiently reports a
stale-but-real path before the pane actually settles into the
worktree. Since that stale path is itself a real, distinct git
checkout, it also passes validate_spawn_worktree's isolation check,
so the loop silently recorded the wrong worktree in state/<id>.meta
(and, for claude harness spawns, installed the turn-end hook there
too).

Require two consecutive polls to agree on the same non-project path
before accepting it, using the existing inter-poll sleep as the
confirmation gap so an already-settled pane isn't slowed down by an
extra cycle.

* fix(tests): drop unused CASE_DIR read in worktree-settle test

ShellCheck SC2034: CASE_DIR is split out of the case record but
never referenced; discard it with _ instead.

---------

Co-authored-by: Freudator86 <[email protected]>

* fix(bin): make watcher process identity immune to Linux wall-clock changes (#752)

* fix(watcher): stabilize Linux process identity

* no-mistakes(document): document FM_PROC_ROOT_OVERRIDE and Linux starttime identity rationale

* fix: prevent AFK idle stalls and stale run attribution (#758)

* fix(supervision): verb-aware captain relevance, AFK wedge, head-bound state

Stop free-text tokens like "merged" from promoting nonterminal working: lines
to captain-relevant, so AFK no longer permanently suppresses idle recovery.
Defend wedge aging independently for nonterminal progress verbs, bind
no-mistakes current-state attribution to code identity (not branch alone),
and mark setup-complete as nonterminal in the ship brief scaffold.

* no-mistakes(review): Enforce nonterminal suppression and head-bound run attribution

* no-mistakes(document): Document current-code-bound run attribution

* no-mistakes(test): Wait for stable Herdr shell readiness

* no-mistakes(test): Make Herdr and watcher readiness tests deterministic

* no-mistakes(test): Make tmux capture and watcher lifecycle deterministic

* no-mistakes(document): Document corrected supervision contracts

* fix(bin): allow safe teardown during watcher recovery (#750)

* fix: allow safe teardown during watcher recovery

* no-mistakes(review): Distinguish unsafe-teardown deny guidance via policy reason code

* no-mistakes(document): Sync continuity-gate docs to allow teardown recovery

* test: mark dynamic teardown fixture literal

* no-mistakes(document): docs: add teardown to continuity gate allow list

* feat(herdr): order presentation spaces while preserving focus (#790)

* feat(herdr): order presentation worker spaces

* fix(herdr): preserve focus during projected cleanup

* no-mistakes(review): Serialize Herdr cleanup and protect active seeded tabs

* no-mistakes(review): Serialize Herdr aborts with guarded focus regressions

* no-mistakes(review): Fall back flat when Herdr serialization is unavailable

* no-mistakes(test): Stabilize watcher startup and AFK handoff tests

* no-mistakes(document): Correct Herdr ordering and focus documentation

* fix(bin): send literal config reread nudges after pushes (#809)

* Send literal config reread after inherited config push

When declared inherited config changes under an already-running secondmate,
build a per-home instruction from validated destination post-write bytes and
deliver it on the routed secondmate path. Unchanged config sends nothing;
ABSENT represents removal; captain-shared is never inlined. Covers mid-session
config-push and the locked bootstrap convergence path without hardening spawn
against deliberate runtime choice.

* no-mistakes(review): Fix config reread framing, partial propagation, and respawn order

* no-mistakes(review): Send config rereads via durable single-line pointers

* no-mistakes(review): Make failed config rereads retryable

* no-mistakes(review): Make config reread retries generation-safe

* no-mistakes(review): Make config rereads durable and ordered

* no-mistakes(review): Drain retries, bound history, preserve detect-only read-only mode

* no-mistakes(review): Retain write retries and quarantine stale respawn generations

* no-mistakes(review): Preserve exact config reread retries and delivery order

* no-mistakes(review): Preserve exact retry bytes and bounded quarantine pruning

* no-mistakes(document): Consolidated config-reread documentation

* feat(watch): follow GitLab merge requests to merge (#797)

* feat(watch): follow GitLab merge requests to merge

The merge watch only understood GitHub pull requests, so a task whose
deliverable is a GitLab merge request was never followed to merge.

Generalize the stored poll identity from owner/repository to a
provider-tagged provider/url/host/path/number record. GitLab runs mostly on
self-hosted instances and its projects nest under groups at no fixed depth,
so the host and the full project path are data in the record rather than
constants, and every consumer rebuilds the URL from those parts and refuses
any record that does not reconstruct it exactly.

The GitLab state is read with plain glab, matching the GitHub path's use of
plain gh, so an upstream checkout needs no extra tooling. Two things about
glab were established by running it rather than assumed, because a wrong
invocation here fails silently into a permanent "not merged":

- glab has no field selector, and its JSON would need a JSON processor that
  firstmate does not require, so the state is read from glab's own field
  output. Only an exact "merged" wakes firstmate, so a changed format stays
  silent instead of reporting a merge.
- glab cannot take a merge request URL the way gh can, because that form
  resolves through the current git repository and the watcher has none. It
  is addressed by project URL and merge request number instead.

An absent glab produces no wake rather than a false merge, and arming
refuses with a clear message since that is the one point where a missing
CLI can still be reported. A GitLab task records no pr_head, which both
consumers already treat as optional. The merge path still addresses GitHub
only and refuses a merge request URL rather than sending it to the wrong
forge.

The record version moves to v2, and the existing non-executing migration
rebuilds an already-armed watch from its recorded URL, so no watch is lost
by upgrading.

docs/gitlab-merge-watch.md records the evidence, taken against the public
fixture project https://gitlab.com/KarotKris/gitlab-merge-watch-fixture.

* no-mistakes(review): Reject github.com host in GitLab MR URL/sidecar validation

* no-mistakes(document): Note GitLab MR URLs are explicitly refused, not just malformed ones, in fm-pr-merge.sh docs

* fix(herdr): group projected children beneath owning parents (#821)

* feat(herdr): correct all-home child presentation topology

Inherit the presentation opt-in to secondmate homes, label new projected
spaces with the approved corner format, insert each child under its owning
parent under one session-scoped lock, and keep flat non-destructive fallback.

* no-mistakes(review): Exclude secondmates from Herdr presentation projection

* no-mistakes(review): Harden shared Herdr locks and ambiguous child ordering

* no-mistakes(review): Use adjacency-only Herdr child ownership

* no-mistakes(review): Reject foreign legacy projections safely

* no-mistakes(review): Validate Herdr session sockets before projection

* no-mistakes(test): Fix Herdr teardown fixture session socket metadata

* fix(herdr): canonicalize presentation lock socket paths

Always resolve the session socket parent directory so symlink parents
such as /tmp -> /private/tmp cannot split the shared cross-home lock
identity. Refuse relative socket paths. Clarify lock-unavailable warnings.

* no-mistakes(test): Fix Bash-compatible GitLab merge request URL parsing

* no-mistakes(document): Document all-home Herdr child topology

* no-mistakes(lint): Quote fallback provenance string for ShellCheck

* fix: keep local no-mistakes tests intent-targeted (#823)

* fix(no-mistakes): drop full-suite local Test override

Local no-mistakes Test is intent-targeted; CI Behavior keeps the bro