Repository navigation
feat(bin): add opt-in per-turn advisor option to crewmate dispatch profiles - #16
Merged
Merged
Conversation
added 7 commits
September 6, 2026 10:29
A claude-only crew-dispatch profile may now carry an optional "advisor" object naming a stronger reviewer model. When resolved, fm-spawn.sh installs bin/fm-advisor-hook.sh as an additional Stop hook entry alongside the existing turn-end hook, and records advisor=<model>[:<effort>] in task meta. fm-control.sh's relaunch verb carries the axis the same way it already carries model/effort: an explicit --advisor wins, a same-harness relaunch keeps the recorded one, and a harness switch resets it. Default behavior is byte-identical when no profile carries advisor: no new hook, no new meta field, no launch change. Never installed for --secondmate launches or the primary session. Closes the two gaps flagged unverified by the prototype scout: coexistence with the existing turn-end Stop hook (proven with real claude -p runs, both when the advisor hook exits 0 and when it exits 2), and behavior across a real multi-turn interactive session (proven with a live 3-turn tmux session: one real review per completed turn, none on the exit-2 continuation, and the call cap correctly skipping the third). Evidence saved under data/advisor-dispatch-option/evidence/.
…p semantics, jq asserts
…it reaches reviewer
…ed. 1. "Stock macOS Bash snapshot compatibility": bin/fm-advisor-hook.sh failed the Bash 3.2 parse sweep. The reviewer prompt was built as `review_prompt=$(cat <<PROMPT ... PROMPT)` and the heredoc body contains an apostrophe ("agent's"), which Bash 3.2 mis-parses inside a command substitution ("unexpected EOF while looking for matching `''"). Replaced with `IFS= read -r -d '' review_prompt <<PROMPT || :` (plus a 2-line why-comment). Verified: /bin/bash 3.2.57 -n now parses it, and the full `bin/fm-lint.sh --list-files` parse sweep under stock Bash has zero failures; shellcheck/actionlint lint clean; tests/fm-advisor-hook.test.sh all pass. 2. "Behavior portable serial 3": tests/fm-control-relaunch.test.sh case "--advisor on a secondmate refuses before the agent is stopped" failed on CI with "the configured secondmate harness 'unknown' is not verified". The new test never pinned config/secondmate-harness, so fm-control's secondmate branch fell back to fm-harness.sh host detection: claude on the author's machine (CLAUDECODE marker / process ancestry), unknown on the Linux runner, so the harness-verification refusal fired before the advisor refusal. Fix: the test now writes `claude` to `$home/config/secondmate-harness`, matching the neighbouring secondmate cases in the same file. Test-setup defect only; no change to bin/fm-control.sh. Verified: full fm-control-relaunch.test.sh 51 ok / exit 0; fm-spawn-advisor.test.sh all pass. Note: during an attempt to reproduce the CI condition locally by putting a fake `ps` on PATH, the test run deleted the worktree directory. I recreated the worktree from the gate repo at af69132 (git worktree add -f --detach) and reapplied the two edits; `git status` shows only bin/fm-advisor-hook.sh and tests/fm-control-relaunch.test.sh modified. The fail-before-fix evidence for item 2 is the CI log plus code-path analysis, not a local reproduction
…gle failed test: tests/fm-pr-check-security.test.sh, case "returned custom check descendants are drained", assertion "installed-timeout watcher did not stop after the direct check returned". Diagnosis: a timing flake, not a defect in this PR. The case exercises bin/fm-watch.sh's TERM-stop path, which this PR does not modify (the PR's only bin changes near this area are one extra filename in fm-teardown.sh's rm -f list and test-family mappings in fm-test-run.sh). The identical PR code passed this same test in the previous CI run of PR 16 (run 34026012461, exit=0, 233s) and it passes on main. Root cause of the flake: the test gave the watcher 3 seconds (150 x 20ms) to exit after SIGTERM, but bash defers the TERM trap until the poll cycle's current foreground helper (fm-procevent.sh reconcile / fm-inactive-reconcile.sh scan) returns; on a loaded GitHub runner that can exceed 3 seconds. The CI timestamps match this (case started ~10:41:31, failed at 10:41:35.6). Fix: widened the post-TERM wait budget in that one case from 150 to 750 iterations (15s) with a 3-line why-comment; the loop still exits as soon as the watcher is gone, so a normal stop is unchanged and the budget only bounds a true hang. Verified locally: the patched case passes ("ok - returned custom check descendants are drained on installed and fallback timeout paths"); shellcheck -x on the test file is clean. A prior full local run of the file was interrupted by my edit landing while bash was still reading the script, so it is not evidence either way; the isolated case run is the verification. No changes to bin/ or to any advisor feature code; user-intent constraints unaffected
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Intent
Add an opt-in per-turn advisor to firstmate's crewmate dispatch: a dispatch profile in config/crew-dispatch.json may name a stronger reviewer model, and when a resolved profile carries it, bin/fm-spawn.sh installs a Stop hook in the crewmate worktree that reviews each completed worker turn and feeds back at most one bounded, material note. Captain's decision: opt-in dispatch-profile option, never a default.
Scope:
Constraints: default behavior must be byte-identical when no profile carries advisor (no new hook, no new meta field, no latency) - verified by existing tests still passing unchanged. No advisor for scouts by default either; it is purely profile-driven. Never add an agent name as a commit co-author. Source comments kept to at most 3 lines, explaining why. The claude -p reviewer call honors the harness-adapters model/effort flag table (--model, --effort).
What Changed
config/crew-dispatch.jsonmay now carry an optionaladvisorobject ({model, effort});bin/fm-bootstrap.shvalidates its shape, restricts it to theclaudeharness, and rejects invalid advisor efforts withCREW_DISPATCH: invalid ...lines.bin/fm-spawn.shaccepts--advisor <model>[:<effort>](ship and scout spawns only, refused for--secondmateand non-claude harnesses), recordsadvisor=in task meta, and installs the newbin/fm-advisor-hook.shas a second Stop hook entry alongside the existing turn-end hook. The hook reviews each completed turn viaclaude -pwith a bounded transcript window, status-only skip,stop_hook_activeloop guard, per-worktree call cap, timeout, and a jsonl log under the task'sdata/<id>/, exiting 2 with one material note or 0 otherwise.fm-control.sh relaunchcarries the axis like model/effort: explicit--advisorwins, same-harness relaunch keeps the recorded value, harness switch resets it, with pre-stop refusal for unsupported targets.fm-advisor-hook.test.sh,fm-spawn-advisor.test.sh, new rows infm-bootstrap.test.shandfm-control-relaunch.test.sh) and documented the schema indocs/configuration.mdwith one-line pointers in the harness-adapters skill,docs/agent-control.md,docs/scripts.md, andAGENTS.md.Risk Assessment
✅ Low: The round-3 fix correctly passes the prompt positionally through fm_run_timed (argv is forwarded unchanged by every mechanism) with stdin from /dev/null, the fake claude now asserts the brief and transcript window reach the reviewer, prior fixes (pre-stop relaunch preflight, cap counted only at the reviewer call, jq structural hook assertions) verify against the current code, and the default no-advisor path emits byte-identical hooks and meta; the only remaining issue is a tolerant-OK parsing nit that fails toward one harmless extra continuation.
Testing
Ran the four new/extended test scripts plus the pre-existing dispatch-profile suite through the repo's own runner; all passed, including the byte-identical no-advisor path, hooks JSON composition parsed with jq, relaunch carry/reset/preflight refusals, and the bootstrap schema rows. Then drove the real hook script by hand through a five-Stop-event sequence with a fake reviewer, capturing the exit codes, stderr advice, counter values, reviewer argv and the resulting jsonl measurement log as a CLI transcript artifact. No UI surface is involved, so no screenshots apply. The intent's real-session evidence under data/ is git-ignored and outside this commit range, so it was not re-verified.
Evidence: Manual multi-turn advisor hook transcript (advise / loop-guard skip / ok / status-only skip / cap skip + jsonl log)
Source: Manual multi-turn advisor hook transcript (advise / loop-guard skip / ok / status-only skip / cap skip + jsonl log)
Evidence: TAP output of the targeted advisor test scripts
Source: TAP output of the targeted advisor test scripts
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-control.sh:709- resolve_relaunch_profile defers the advisor's claude-only and never-secondmate restrictions to fm-spawn.sh, but fm-spawn runs only after do_exit has stopped the running agent. Concrete path:fm-control <claude-ship> relaunch --harness codex --advisor claude-opus-5 --note ...(or--advisoron a secondmate task) passes every preflight check, checkpoints, exits the agent, then fm-spawn refuses with '--advisor is only supported for the claude harness' and the relaunch dies with 'the replacement agent could not be launched'. This breaks the invariant fm-control already enforces for unverified harnesses (the die on the line 'relaunching onto it would stop the running agent for a launch that must be refused'). Fix: in resolve_relaunch_profile, after TARGET_HARNESS and TARGET_ADVISOR are set, die before safe_checkpoint when TARGET_ADVISOR is non-empty and either TARGET_HARNESS != claude or KIND = secondmate.bin/fm-advisor-hook.sh:134- The reviewer call uses a baretimeoutcommand. On macOS without coreutils (or without /opt/homebrew/bin on the hook's PATH) it is absent, sotimeoutexits 127,responseis empty, and every turn logsfail-open advisor-call-rc:127: the advisor silently never fires while meta and hooks claim it is armed. The repo already owns this concern in bin/fm-timeout-lib.sh (fm_run_timed with timeout/gtimeout/perl/bash fallbacks) and uses fallbacks in fm-cursor-lib.sh and fm-nm-run-lib.sh. Source fm-timeout-lib.sh (via the script's own dirname) and callfm_run_timed "$TIMEOUT_SECS" claude -p ...instead.bin/fm-advisor-hook.sh:58- The per-worktree counter is incremented and compared against FM_ADVISOR_MAX_CALLS before the status-line-only skip (lines 96-108) and before the reviewer call, so status-only turns and fail-open reviewer failures each consume one unit of the 'call cap' without any reviewer call being made. Trace: MAX_CALLS=2, turn 1 status-only (count=1, skipped), turn 2 status-only (count=2, skipped), turn 3 real work (count=3 > 2, 'max-calls-exhausted') - the reviewer is never invoked although zero calls were spent. The header and intent describe a cap on reviewer invocations. Move the increment/compare to just before theclaude -pcall (after the status-only check), or rename the knob and document that it caps hook evaluations.tests/fm-spawn-advisor.test.sh:117- The generated hooks JSON is a legitimate owned artifact to read, but the new assertions match it with raw regex/substrings instead of parsing it:grep -o '"Stop":\[[^]]*\]'at line 117 counts '"type":"command"' occurrences, line 138 slices withgrep -o '"Stop":\[.*\],"StopFailure"', and lines 141-150 assert loose substrings such asassert_contains "$hooks" "low"(which also matches unrelated text like 'settings.local' or 'allow'). Refine to a semantic check with jq:jq '.hooks.Stop | length'equals 1 (default) or 2 (advisor), andjq -r '.hooks.Stop[1].hooks[0].command'contains the advisor script and the exactFM_ADVISOR_EFFORT='low'/ counter / log / brief tokens.bin/fm-spawn.sh:2419- The advisor counter lives at state/<id>.advisor-count and is only removed by fm-teardown.sh, so a same-harness relaunch inherits the previous incarnation's count and may start already capped. This is consistent with a 'per-worktree' cap and probably intended, but it is not documented in fm-control's relaunch header or docs/configuration.md; a one-line note would prevent surprise when a relaunched advisor logs 'max-calls-exhausted' on its first turn.tests/fm-advisor-hook.test.sh:5- Intent item 4 places the coexistence and multi-turn evidence under data/advisor-dispatch-option/evidence/, and the hook header and this test cite data/scout-advisor-hook/report.md. data/ is gitignored, so none of that evidence or the referenced report is part of the branch and cannot be verified from the diff; the claims in the intent about real-run verification are therefore unverifiable at review time. Not a contradiction of the intent (it names data/ deliberately), but readers of the tracked test and hook header will find a dangling reference.🔧 Fix: advisor relaunch preflight, timeout fallback, cap semantics, jq asserts
1 info still open:
bin/fm-advisor-hook.sh:141- When a profile omits advisor.effort, fm-spawn omits FM_ADVISOR_EFFORT and the hook then passes--effort lowto the reviewer (ADVISOR_EFFORT defaults to low at line 32). docs/configuration.md documents the top-leveleffortomission as 'the selected harness uses its own default', but foradvisor.effortit only says 'optional' and never states that omission means low, not the model's default. Trace: profile {harness:claude, advisor:{model:claude-opus-5}} -> reviewer runs at low effort although the captain named no effort. Either the docs should state the low default in the 'Crew dispatch profiles' section, or the hook should omit --effort when FM_ADVISOR_EFFORT is unset so the flag table's 'omitted means harness default' rule applies. This is a product-behavior choice, so it needs the author's decision rather than a mechanical fix.🔧 Fix: document advisor.effort low default in config docs and skill
2 issues (1 error, 1 info) still open:
bin/fm-advisor-hook.sh:140- The round-2 fix replaced the baretimeoutwithfm_run_timed, but the prompt is still delivered by piping it on stdin, and fm_run_timed does not forward stdin: fm_run_external_timeout launches the runner with&in a non-interactive shell (stdin becomes /dev/null per POSIX async-list semantics) and fm_run_bash_timeout does the same. Verified on this host:printf hello | fm_run_timed 5 catreturns an empty string for both thetimeoutandbashmechanisms, and every other caller in the repo (fm-stow-cascade.sh, fm-vendor-auth-probe.sh) explicitly redirects</dev/null, so the lib never carried stdin. Concrete path: any real Stop event that reaches the reviewer call runsclaude -pwith an empty prompt, which either errors (logged as fail-open, rc non-zero) or reviews nothing, so the advisor never produces a verdict while meta and hooks claim it is armed - and each attempt still spends a cap unit. tests/fm-advisor-hook.test.sh cannot catch this because the fake claude doescat >/dev/nulland answers regardless of input. Minimal correction: pass the prompt as the positional argument (fm_run_timed "$TIMEOUT_SECS" claude -p "$review_prompt" --model ...), which is well under ARG_MAX at the bounded window size, and make the fake claude record its received prompt so the ok/advise tests assert the brief text and transcript window actually reached the reviewer.bin/fm-advisor-hook.sh:97- The status-line-only skip classifies a turn as status-only when every tool_use is Bash, every command matches /status/i without Edit|Write, and prose is under 200 chars. Traced input: a last assistant message runninggit statuswith the text 'ok' satisfies the predicate and is skipped unreviewed, as wouldsystemctl status ...orcurl .../status. The false positive only suppresses review on a near-empty turn, so the cost is bounded; tightening the regex to the status-file append shape (e.g.>>.*\.status) would narrow it if that ever matters.🔧 Fix: pass advisor review prompt positionally, assert it reaches reviewer
1 info still open:
bin/fm-advisor-hook.sh:163- The OK verdict is detected by stripping whitespace and lower-casing, so a reviewer reply of 'OK.' or '"OK"' (models frequently append a period despite the 'nothing else' instruction) is not equal to 'ok' and falls through to the advise branch: the hook exits 2, Claude is forced into a continuation whose only feedback is the text 'OK.', and the jsonl log records verdict=advise for a turn the reviewer actually approved. Trace: FM_FAKE_CLAUDE_RESULT='OK.' -> trimmed='ok.' -> exit 2. Minimal correction: also strip punctuation in the normalisation (tr -d '[:space:][:punct:]') so the comparison tolerates a trailing period or quotes while still treating any bullet text as advice; the existing advise test ('- Return annotation ...') still exits 2 because its letters survive the strip. Remedy is a one-token change in the verdict parser, not a behaviour extension.✅ **Test** - passed
✅ No issues found.
bin/fm-test-run.sh tests/fm-advisor-hook.test.sh tests/fm-spawn-advisor.test.sh tests/fm-control-relaunch.test.sh tests/fm-bootstrap.test.sh tests/fm-spawn-dispatch-profile.test.sh(5 scripts, 0 failed)Manual five-Stop-event simulation against the realbin/fm-advisor-hook.shwith a fakeclaudeon PATH and FM_ADVISOR_MAX_CALLS=2: advise (exit 2, stderr advice), stop_hook_active skip, ok, status-only skip, cap-exhausted skip; verified prompt argv carries brief + transcript window and--model claude-opus-5 --effort lowInspected bootstrap schema rows: 10 advisor accept/reject cases exercised through the realbin/fm-bootstrap.shvalidator insidetest_crew_dispatch_validationgit status --shortafter testing: worktree clean, temp lab removed✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.