Repository navigation
feat: expand crew harnesses and harden fleet lifecycle - #1643
Closed
HelloWorldSungin wants to merge 59 commits into
Closed
HelloWorldSungin wants to merge 59 commits into
HelloWorldSungin wants to merge 59 commits into
Conversation
Add cursor-agent (Composer) and agy (Antigravity/Gemini) as CREW-ONLY, HERDR-ONLY crewmate harnesses (captain-approved divergence; design in data/captain.md, empirical verification in data/cursor-agy-verify/report.md). They are never a primary runtime and never a secondmate launcher, and fm-spawn fail-closes both gates before any backend or worktree work. Launch construction moves into bin/fm-launch-lib.sh (extracted verbatim from fm-spawn, protected by the existing fm-spawn-dispatch-profile regression) so the per-harness template and model/effort renderers are unit-testable: - cursor: `cursor-agent --trust --force <model> "$(cat brief)"`; effort is encoded in the parameterized model string (composer-2.5[effort=high]), so there is no standalone effort flag. - agy: `agy --dangerously-skip-permissions <model> --effort <low|medium|high> --prompt-interactive "$(cat brief)"`. agy workspace trust: an interactive agy launch gates on a per-workspace trust modal that --dangerously-skip-permissions does not cover, and trust is an exact-path entry in agy's shared global settings. bin/fm-agy-trust-lib.sh seeds the exact worktree path before launch (fm-spawn, fail-closed) and removes it at teardown (fm-teardown, main and secondmate-child paths); it is locked, atomic, idempotent, and leaves an unparseable settings file untouched. On herdr, agent-state, liveness, turn-end, and send-safety are all generic (native `agent get` + the pane.agent_status_changed event stream), so no adapter code and no turn-end hook are added, and no repo .cursor/hooks.json / .agents/hooks.json is ever written. Composer stays `unknown` (the safe default); no generic bare-glyph rule is added (agy's `>` glyph would be a dead-shell send hazard). tmux is documented out-of-scope. cursor/agy are added to the verified-adapter set in fm-bootstrap and fm-dispatch-select (agy effort low|medium|high; cursor no standalone effort); both are intentionally unscorable in quota-balanced selection (paid subs not tracked by quota-axi) and fall through to the uniform random fallback. Docs: harness-adapters SKILL and AGENTS.md section 4. Tests: colocated unit tests for the launch lib and trust lib; contract tests for the crew-only/herdr-only refusals and teardown trust cleanup; extended dispatch-select/bootstrap validation; and a skip-guarded live herdr-lab smoke that launches both CLIs through the real templates and confirms native detection. Full suite green; shellcheck 0.11.0 clean.
…e-path tests Address the independent adversarial review (data/cursor-agy-review/report.md): B1 - raw launch-command bypass: the raw escape hatch derived the harness from the first non-assignment word's basename (`cursor-agent`/`env`), so the cursor/agy crew-only/herdr-only guard (keyed on the exact tokens `cursor`/`agy`) missed it. Add fm_launch_raw_restricted_harness (resolves the real executable through `env` and leading VAR=val assignments, with an all-words backstop) and refuse any raw command that resolves to cursor-agent/agy outright - the raw path cannot provide the trust seed or native supervision they require, so callers use --harness. B2 - turn-end wake: the shared transition policy deliberately DEFERS herdr idle/done, and cursor/agy install no hook and write no status file, so a completed turn only ever surfaced via the unreliable content-hash stale heuristic. Add a native-identity-gated, DEBOUNCED completion detector: fm_transition_native_completion (pure, in fm-transition-lib.sh) plus fm-watch.sh's maybe_native_turnend, which reads the pane's native agent_status and touches state/<id>.turn-ended once a cursor/agy pane settles at idle/done across two consecutive polls - the same completion signal every other harness's hook writes, handled by the existing scan/wake path with no change to the shared policy or event stream. Adds fm_backend_agent_status (raw enum accessor). B3 - agy trust is now ownership-aware and transactional: fm_agy_trust_add reports created vs preexisting so firstmate removes ONLY an entry it created and never deletes a path the captain already trusted; the durable marker state/<id>.agy-trust drives ownership-aware teardown; the spawn abort trap rolls back a created entry; and teardown removal failure is an INCOMPLETE teardown that retains the marker + metadata for a deterministic retry (same contract on the secondmate-child path). B4 - the age-only 10s stale-lock breaker could steal a LIVE lock; replace it with the repository's ownership-and-liveness lock (fm_lock_*), which never reclaims a lock whose holder PID is alive and only lets the owner release. S1 - add the missing failure-path tests: raw-command bypass variants (direct, env, assignment-prefixed) on forbidden dimensions; created-vs-preexisting ownership; parallel mutation; a live-lock-held-past-10s theft test; spawn-abort rollback and teardown-incomplete-on-failure; and the live smoke now observes a working->idle/done transition and PROVES a native completion wake for both CLIs. Docs updated (harness-adapters skill, fm-launch-lib/fm-spawn comments) to describe the debounced native completion detector instead of the earlier inaccurate "native event stream drives turn-end" claim. Full suite green; shellcheck 0.11.0 clean. Pre-existing flake noted: tests/fm-watcher-lock.test.sh (unrelated beacon timing; reproduces identically on the pre-change fm-watch.sh).
Match the repo convention (nearly all tests/*.test.sh are mode 0755) so direct ./tests/<name>.test.sh invocation works, not only via the bash runner.
Address the adversarial re-review (data/cursor-agy-rereview/report.md):
B1 (still-open shell-wrapper bypass) - a quoted wrapper like `bash -lc 'agy ...'`
or `sh -c "cursor-agent ..."` split into tokens `'agy` / `"cursor-agent`, so the
raw-guard's basename scan missed it and fm-spawn recorded harness=bash on tmux,
bypassing the crew-only/herdr-only gates. fm_launch_raw_restricted_harness now
adds a fail-closed backstop that neutralizes shell quote characters and command
separators before scanning every token's basename, so a wrapped cursor-agent/agy
invocation is caught and refused. Over-approximates safely (the raw hatch is for
unverified adapters; cursor/agy have a canonical --harness path).
B3 (still-open rollback leaks) - two fixes:
1. AGY_TRUST_ROLLBACK_PATH is now armed BEFORE the fallible ownership-marker
write, so a marker-write failure after the global trust entry was created
still leaves the abort trap armed to roll it back.
2. The rollback is factored into fm_agy_trust_rollback: on removal success it
drops the marker; on removal FAILURE it (re)writes the marker with the
leaked path as retry evidence - even when the marker was never written -
instead of deleting it. The abort trap calls this tested function.
S2 - fm-bootstrap now emits `CREW_DISPATCH: backend mismatch - ...` when a valid
dispatch profile selects the crew-only herdr-only cursor/agy harness while the
resolved backend is not herdr, instead of deferring the surprise to spawn-time
refusal. bootstrap-diagnostics skill + AGENTS.md section 13 recognize the new
line.
Tests (would fail if unfixed): shell-wrapper bypass at both the resolver unit
level and through fm-spawn refusal; rollback clean-removal, rollback-removal
failure preserving marker evidence, and rollback failure recreating an absent
marker (the marker-write-failure evidence path); bootstrap backend-mismatch
warning on tmux and silence on herdr.
Full suite green; bin/fm-lint.sh (ShellCheck 0.11.0) exit 0. Not pushed.
Note: the end-to-end fm-spawn abort path reaches the agy seed only through a real
herdr spawn (no clean deterministic failure-injection seam), so the abort-trap
logic is covered by the fm_agy_trust_rollback unit tests that exercise the exact
function the trap runs.
…tests B1 (variable-indirection raw shell wrappers, second re-review) - a raw command is executed by the crewmate PANE's shell, so `AGY=agy bash -lc '$AGY ...'`, `bash -lc 'x=agy; eval "$x ..."'`, backticks, `$(...)`, and split-token concatenation (`$a$g`) can all expand to a restricted executable that a basename scan cannot see. fm_launch_raw_restricted_harness now returns `unresolved` for any raw command containing shell expansion ($ or backtick), and fm-spawn refuses it: the command cannot be statically proven not to launch cursor/agy. Over-approximates safely (the raw hatch is for unverified adapters; cursor/agy have a canonical --harness path). Literal and env/assignment forms still resolve to cursor/agy. Regressed-test fixes (full-suite failures caused by earlier commits in this branch): - tests/fm-gotmp.test.sh: teardown now sources bin/fm-agy-trust-lib.sh (which pulls in bin/fm-wake-lib.sh for its ownership lock); the fake teardown bin did not symlink them, so the source aborted teardown. Symlink both as newly required siblings, and make fm-agy-trust-lib's on-demand fm-wake-lib source tolerate an absent file (the lock is only exercised for agy tasks, whose real environment always has it). - tests/fm-pi-watch-extension.test.sh: the pi secondmate launch TEMPLATE moved into bin/fm-launch-lib.sh during the launch-template extraction, so the test's grep of bin/fm-spawn.sh missed it; read both files (the placeholder substitution and tracked-extension path stay in fm-spawn.sh). Tests: variable-indirection bypass rows at the resolver unit level and through the fm-spawn refusal path. bin/fm-lint.sh (ShellCheck 0.11.0) clean. Not pushed.
These are pre-existing, environment-specific failures surfaced by running the full
suite in an en_US.UTF-8 host with Pi 0.81.1 and node in /usr/bin. None is caused by
the cursor/agy work; each is fixed at its true root cause, not masked.
- bin/fm-test-run.sh: the coverage guard sorts its lane/family lists with
`LC_ALL=C sort` but ran `comm` in the ambient locale, so in en_US.UTF-8 comm
rejected the C-collated input ("not in sorted order") and returned non-zero.
Run every comm under LC_ALL=C to match its sort. (The cursor/agy test filenames
happened to expose this latent locale inconsistency.)
- tests/fm-calm-pi-extension.test.sh: hard-pinned Pi 0.80.10; the host has 0.81.1.
Empirically re-verified 2026-07-23 - the renderer and interactive-E2E assertions
pass green against @earendil-works/pi-coding-agent 0.81.1 - so the pin now accepts
0.80.10 or 0.81.1 (evidence-based, still fails loudly on an unverified version).
- tests/fm-session-start.test.sh: forced a MISSING diagnostic by removing `node`
from its fake bin, but node commonly leaks from $BASE_PATH (/usr/bin), masking
the forced-missing condition. Force-miss `no-mistakes` instead - a firstmate tool
never on a standard system PATH - so the diagnostic reliably appears.
bin/fm-lint.sh (ShellCheck 0.11.0) clean.
…gy launches
The captain accepted the no-go: string-scanning a raw launch command can never be
complete against a Turing-complete pane shell (quote concatenation `ag"y"`, brace
`a{gy,}`, alias expansion, generated process substitution, and a wrapper script
that internally execs the binary all defeat a static scan). Move the primary B1
defense to EXEC-TIME interception.
- bin/fm-launch-lib.sh: fm_launch_write_raw_guard writes firstmate-owned refusing
`cursor-agent`/`cursor`/`agy` shims (exit non-zero) into a guard dir.
- bin/fm-spawn.sh: for a raw launch command, install that guard under
TASK_TMP/raw-guard and prepend it to the pane PATH before the command runs, so
ANY spelling that resolves one of those binaries through PATH hits the shim
instead of the real CLI - uniformly closing quote-concat, brace, alias,
process-substitution, AND the wrapper-script boundary. Teardown's `rm -rf
TASK_TMP` cleans it. The sanctioned `--harness` path never routes through the
guard and reaches the real binary directly.
- The fm_launch_raw_restricted_harness string classifier stays as early,
spawn-time defense-in-depth (clear pre-launch refusal), not the sole gate.
Documented residual (a PATH shim cannot cover): an absolute-path invocation or a
raw command that first resets PATH bypasses the guard; both are deliberate
circumventions, and closing them needs execve-level interception (LD_PRELOAD/
seccomp) disproportionate to the raw hatch.
Tests: tests/fm-launch-lib.test.sh runs every demonstrated bypass class
(quote-concat agy/cursor, eval+quote-concat, brace, process-substitution, alias,
wrapper-via-PATH) with a fake real binary behind the guard and asserts the real
binary never executes; tests/fm-cursor-agy-adapter.test.sh drives a real raw spawn
and asserts the guard is installed and prepended to the pane PATH. harness-adapters
skill documents the exec-time gate and the residual. shellcheck 0.11.0 clean.
…on A) Captain chose Option A: MERGE origin/main into the cursor/agy overlay branch (NOT rebase), preserving the overlay for fast-forward-to-homes landing. origin/main advanced 4 commits (kunchenguid#895 Calm rendering, kunchenguid#898/kunchenguid#899 operational markers, kunchenguid#909 canonical operational-input classification). The load-bearing conflict is kunchenguid#909, which threaded a __OPINPUT__ operational-input encoder and a __PIBRIEFENV__ Pi env assignment INTO launch_template() in fm-spawn.sh - the exact function this branch EXTRACTED into bin/fm-launch-lib.sh. Resolution: - bin/fm-launch-lib.sh (fm_launch_template): threaded kunchenguid#909's `"$(__OPINPUT__ encode launch-brief < __BRIEF__)"` into every template (claude, codex, opencode, pi, grok, and the new cursor/agy - consistent cross-harness operational-input canonicalization) and the `__PIBRIEFENV__` prefix onto the pi templates; kept the extraction. - bin/fm-spawn.sh: kept the extraction (launch_template lives in the lib) and the cursor/agy raw-guard/agy-trust/guards; added kunchenguid#909's sq_opinput + PIBRIEFENV substitutions using this branch's fm_launch_* helper names. - tests/fm-calm-pi-extension.test.sh: took origin/main - kunchenguid#895 already re-verified Calm on Pi 0.81.1 and pinned it there, superseding this branch's interim 0.80.10|0.81.1 workaround. - tests/fm-launch-lib.test.sh: updated the exact-template assertions to the kunchenguid#909 __OPINPUT__/__PIBRIEFENV__ form. - AGENTS.md, harness-adapters SKILL, bin/fm-test-run.sh, fm-pi-watch test: auto-merged, both sides preserved (verified). Merge-affected tests green: fm-operational-input, fm-spawn-dispatch-profile, fm-pi-watch-extension, fm-cursor-agy-adapter, fm-launch-lib, fm-calm-pi-extension, fm-transition-lib, fm-agy-trust-lib. shellcheck 0.11.0 clean.
Reconcile the crew-only cursor/agy overlay with seven upstream commits (a7e01bc..6b0d21d). Merge, never rebase: the overlay must stay fast-forwardable into detached secondmate homes. Hand-resolved conflicts: - bin/fm-spawn.sh launch templates: keep this branch's extraction of the templates into bin/fm-launch-lib.sh (fm_launch_template) and its single rendering owner (fm_launch_render), rather than main's inline launch_template. Template content is at parity with main, including kunchenguid#909's __OPINPUT__ operational-input envelope. - Drop __PIBRIEFENV__ / FM_FIRSTMATE_PI_LAUNCH_BRIEF, which this branch still carried from kunchenguid#895. kunchenguid#936 removed that Calm input-reroute binding upstream and added a regression test asserting the pi launch command no longer exports it, so the removal is adopted here: the placeholder is gone from the pi templates and from fm_launch_render's signature. - tests/fm-backend.test.sh sibling list: take main's ordering; the two sides list an identical set. Also adopt kunchenguid#939's wider ShellCheck source graph, which now lints tests/: tests/fm-cursor-agy-smoke.test.sh dropped an unused loop variable. bin/fm-lint.sh is clean and the affected suites pass.
Two suite failures surfaced by merging main, both in contracts main tightened while this branch was out: - kunchenguid#939 pins an exact allowlist of tests permitted to carry `# shellcheck source=bin/` production context, so the ShellCheck source graph stays small. The three new cursor/agy tests had added themselves to that set. They do not need production context to lint cleanly, so they now stop static source following at /dev/null instead of widening the allowlist. bin/fm-lint.sh stays clean. - The captain-translation contract asserts the launch command carries kunchenguid#909's canonical `encode launch-brief` envelope by reading bin/fm-spawn.sh. This branch moved the launch templates into bin/fm-launch-lib.sh, so the assertion read a file that no longer authors them. It now reads both files, covering the launch command wherever it is authored. Not addressed here, and not a regression from this branch: tests/fm-calm-pi-extension.test.sh fails identically on a clean origin/main checkout (6b0d21d) with "/calm left the grep row in the transcript". This branch's .pi/ tree and that test are byte-identical to main.
feat(harness): add crew-only cursor and agy adapters
… host PATH
The test was at fault, not bin/fm-session-start.sh or bin/fm-bootstrap.sh.
Reproduced on a clean default branch (bash tests/fm-session-start.test.sh):
not ok - MISSING diagnostic did not appear at all
and, once that site was fixed, the same root cause at a second site:
not ok - fm-bootstrap.sh's real detect line did not appear verbatim (missing: 'MISSING: node (install:')
Both cases force a bootstrap MISSING diagnostic by deleting the fake `node`
from the fixture bin. That only works when node is absent from the test's
base PATH (/usr/bin:/bin:/usr/sbin:/sbin). On a host that ships node in
/usr/bin, bootstrap's `command -v node` still succeeds, so it correctly
reports nothing missing. Bootstrap's detection is right - node really is
installed - so the fixture, not the script, encodes the stale assumption.
Fixed by giving the fixture a `hide_node` helper that deletes the fake binary
and also masks the lookup through BASH_ENV, the same idiom the Herdr cases in
this file already use to mask tmux. No assertion is weakened or removed: both
MISSING assertions and the diagnostics-before-bulk-context ordering assertion
are unchanged and now actually exercised.
Verified: tests/fm-session-start.test.sh 28/28 pass (exit 0),
tests/fm-bootstrap.test.sh 21/21 pass, bin/fm-lint.sh clean.
No behavior change to session start.
Under a Pi primary, entering away mode left TWO supervision cycles live: the
away-mode sub-supervisor daemon and the Pi watch extension's own arm cycle. The
extension's arm runs `fm-watch-arm.sh --restart`, so it kept taking the watcher
singleton back from the daemon, starving away-mode triage entirely while
injecting ordinary watcher turns into the primary - the behavior recorded live on
2026-07-27.
Reproduced end to end with a real Pi 0.82.1 primary loading the tracked watch
extension, a real away daemon, and the real watcher, against a throwaway
firstmate home on a private tmux socket. Prompts delivered to the primary were
captured by a session-trust extension that aborts before any provider work.
BEFORE - two cycles, daemon starved, primary flooded:
-- [away entered] state/.afk: present
1685992 ... bin/fm-supervise-daemon.sh
1711970 ... bin/fm-watch-arm.sh --restart
1712043 ... bin/fm-watch.sh (owned by the extension's arm)
-- ordinary Pi watcher turns during away routine events: 4
-- ordinary Pi watcher turns during the away escalation window: 6
-- away-supervisor escalations delivered to the primary: 0
daemon log, every cycle:
watcher non-wake stdout, idling: watcher: already running pid 1685573
AFTER - one cycle while away, daemon triaging, escalation still delivered:
-- [away entered] state/.afk: present
1987515 ... bin/fm-supervise-daemon.sh (its own fm-watch.sh child only)
-- ordinary Pi watcher turns during away routine events: 0
-- away-supervisor escalations delivered to the primary: 1
daemon log:
self-handle: signal ... -> routine signal: working: another routine step
escalate: signal ... -> repro-task.status: blocked: needs a captain decision
after return, exactly one cycle:
1958195 ... bin/fm-watch-arm.sh --restart
1958211 ... bin/fm-watch.sh
-- ordinary Pi watcher turns after return: 3
The extra cycle was armed by the Pi side, not left behind by away mode: the
extension had no notion of the away-mode flag at all.
The extension now observes the durable state/.afk flag. While it is present the
extension arms nothing, retires any arm child it holds, delivers no ordinary
watcher wake, and schedules no retry; a per-generation away poll resumes exactly
one extension-owned cycle once the flag clears. Nothing is lost across the
hand-off because the daemon's own watcher enqueues and triages every event
durably and owns escalation. No process is matched or killed by pattern, and no
non-pi harness path changes - Claude's Stop auto-arm already had the equivalent
gate, and the other adapters are untouched.
Tests:
- tests/fm-pi-watch-extension.test.sh gains a deterministic regression test for
the dual-supervision condition: arm, raise .afk, assert the arm child is
retired, assert a further arm reports standby with no second cycle and no
injected wake, clear .afk, assert exactly one cycle resumes. It fails on the
pre-fix extension.
- tests/fm-afk-pi-dual-supervision-e2e.test.sh (opt-in, real Pi + real daemon)
asserts the five acceptance steps and fails pre-fix at "the Pi extension kept
its own supervision cycle alongside the away supervisor".
Also fixes a pre-existing collation mismatch in bin/fm-test-run.sh and
tests/fm-test-run.test.sh: comm ran without LC_ALL=C over LC_ALL=C-sorted input,
warning "file 2 is not in sorted order" on every coverage-guard run and risking a
wrong comparison under a non-C locale.
…tcher
tests/fm-watcher-lock.test.sh flaked at test_watch_restart_attaches_to_healthy_peer
with:
not ok - restart did not attach to the verified healthy peer:
watcher: started pid=N (beacon fresh)
Root cause is a startup race in the fixture, not in the watcher. The case stands
up a TERM-resistant node peer, records it as the lock holder, and expects
fm-watch-arm.sh --restart to attach to it instead of starting a second watcher.
node only becomes TERM-resistant once the interpreter has actually evaluated
process.on("SIGTERM"), and the restart sends TERM within milliseconds of the
launch. When the peer lost that race it died on the default disposition, so the
lock named a dead pid, the fresh child legitimately stole it, and the arm
honestly reported "started" - the fixture failed for a condition it does not
test.
Captured under instrumentation on an isolated reproduction of this case
(3 of 12 iterations):
iter=8 BAD out='watcher: started pid=1620769 (beacon fresh)|'
peer=1620694 peer_alive=no
recorded_identity=linux-starttime=30963098 cmdline-hex=6e6f6465...
live_identity =<gone>
lock_pid=1620769
peer_alive=no with the recorded identity intact rules out the identity/beacon
paths and pins it on the peer dying.
Fix: the peer announces that its SIGTERM handler is installed, and the fixture
waits on that exact condition before recording the lock and arming. No assertion
was loosened, no sleep widened, and no retry was wrapped around an assertion.
Loop evidence - `bash tests/fm-watcher-lock.test.sh`, 50 runs per arm, 6-way
parallel, before-arm run from a pristine `git archive HEAD` copy so both arms are
the same command under the same ambient load:
before (origin/main): 10/50 FAILED - all 10 the peer-attach race
after: 0/50 FAILED
after, 50 consecutive runs one at a time: 0/50 FAILED
Harness note for anyone re-running this: do NOT launch the loop under `nohup`.
nohup sets SIGHUP to SIG_IGN, an ignored disposition is inherited through fork
and exec, and a shell cannot trap a signal that was already ignored on entry - so
`kill -HUP` inside test_arm_hup_cleans_child_and_temp_output becomes a no-op and
that case times out (124) on every run regardless of the code under test. Early
loops here were launched that way and produced exactly that false signal.
Also verified: bin/fm-lint.sh clean, and all 10 suites selected by
`bin/fm-test-run.sh --changed` pass.
bin/fm-watch.sh ended each supervision cycle with a blind foreground `sleep "$POLL"`. Bash defers a trapped signal until the running foreground command returns, so the watcher was deaf to TERM/HUP/INT for the remainder of the interval, and exit latency tracked FM_POLL exactly. The signal-grace linger had the same shape. Measured against an isolated temporary home, signalling a watcher that had already taken its lock and entered its cycle wait: FM_POLL=1 TERM before 0.54s after 0.05s FM_POLL=5 TERM before 4.54s after 0.06s FM_POLL=15 TERM before 14.53s after 0.06s FM_POLL=15 HUP before 14.52s after 0.06s bin/fm-watch-arm.sh --restart allows the outgoing watcher 50 iterations of `sleep 0.1`, a 5s budget, before forking a replacement. At the 15s default 14.53s exceeded that budget outright, so a restart forked a second watcher while the first was still alive and still holding the lock; the replacement then saw a live holder and stood down, and the restart never produced the fresh watcher it reported wanting. Run the cycle wait and the signal-grace linger as a tracked background child and wait on the named pid, so the trap runs the moment the signal lands. The wait budget, polling cadence, and wake classification are unchanged, and the EXIT path reaps the sleep child instead of orphaning it for the rest of the interval (verified: no leaked sleep child after a mid-interval stop). Liveness and wedge detection are unaffected and covered explicitly: the heartbeat beacon keeps advancing across cycle waits and goes stale once the watcher genuinely stops, so a stopped watcher is still detectable. Known limit, documented at the call site and in the verification record: the herdr push path waits inside a foreground command substitution and stays up to FM_POLL deaf. That reader owns a fifo directory and a child reader process that it removes on its own return path, so interrupting it from the caller would leak both on every stop. Fixing it needs reader-side teardown. Regression coverage in tests/fm-watcher-lock.test.sh, all three confirmed against the unpatched watcher: - watcher exits on TERM well inside a 10s budget at FM_POLL=60 (fails unpatched: "watcher ignored TERM for its whole poll interval") - --restart hands the lock to a fresh live watcher within the arm's own 5s budget, with no overlap between outgoing and incoming (fails unpatched) - liveness beacon advances while cycling and freezes once stopped (holds both before and after; guards against trading exit latency for a watcher that keeps its lock while no longer cycling)
…tcher
tests/fm-watcher-lock.test.sh flaked at test_watch_restart_attaches_to_healthy_peer
with:
not ok - restart did not attach to the verified healthy peer:
watcher: started pid=N (beacon fresh)
Root cause is a startup race in the fixture, not in the watcher. The case stands
up a TERM-resistant node peer, records it as the lock holder, and expects
fm-watch-arm.sh --restart to attach to it instead of starting a second watcher.
node only becomes TERM-resistant once the interpreter has actually evaluated
process.on("SIGTERM"), and the restart sends TERM within milliseconds of the
launch. When the peer lost that race it died on the default disposition, so the
lock named a dead pid, the fresh child legitimately stole it, and the arm
honestly reported "started" - the fixture failed for a condition it does not
test.
Captured under instrumentation on an isolated reproduction of this case
(3 of 12 iterations):
iter=8 BAD out='watcher: started pid=1620769 (beacon fresh)|'
peer=1620694 peer_alive=no
recorded_identity=linux-starttime=30963098 cmdline-hex=6e6f6465...
live_identity =<gone>
lock_pid=1620769
peer_alive=no with the recorded identity intact rules out the identity/beacon
paths and pins it on the peer dying.
Fix: the peer announces that its SIGTERM handler is installed, and the fixture
waits on that exact condition before recording the lock and arming. No assertion
was loosened, no sleep widened, and no retry was wrapped around an assertion.
Loop evidence - `bash tests/fm-watcher-lock.test.sh`, 50 runs per arm, 6-way
parallel, before-arm run from a pristine `git archive HEAD` copy so both arms are
the same command under the same ambient load:
before (origin/main): 10/50 FAILED - all 10 the peer-attach race
after: 0/50 FAILED
after, 50 consecutive runs one at a time: 0/50 FAILED
Harness note for anyone re-running this: do NOT launch the loop under `nohup`.
nohup sets SIGHUP to SIG_IGN, an ignored disposition is inherited through fork
and exec, and a shell cannot trap a signal that was already ignored on entry - so
`kill -HUP` inside test_arm_hup_cleans_child_and_temp_output becomes a no-op and
that case times out (124) on every run regardless of the code under test. Early
loops here were launched that way and produced exactly that false signal.
Also verified: bin/fm-lint.sh clean, and all 10 suites selected by
`bin/fm-test-run.sh --changed` pass.
(cherry picked from commit 3db0341)
Both pi tuples in the dispatch config reported no authentication surface, so rule 2's OpenAI candidate and rule 3's entire MiniMax lane fell through to the premium default. This was not a credential fault, a quota-axi defect, or a stale tuple. The `surface-unresolved` verdict originated in bin/fm-auth-preflight.sh, which resolved surfaces from a hard-coded harness-to-provider table plus a `pi:<prefix>` source matcher. It was added in kunchenguid#1349 and deleted four hours later in kunchenguid#1358, which returned eligibility to open agent judgment resting on docs/verification/dispatch-auth.md. That record had no evidence that a provider family absent from quota-axi can still have a resolved surface, and no record that a harness catalog is itself surface evidence. With nothing to contradict it, the retired conclusion kept being re-derived at intake and the zero-premium lane stayed unused. Pi's installed docs/models.md states that a provider's models stay absent from --list-models until its auth is configured, so a catalog row proves configured auth. Verified on Pi 0.82.1 and quota-axi 0.1.16: minimax/MiniMax-M3 is listed while quota-axi models no minimax provider at all. The surface is resolved by the catalog; only the quota is unknown, which is disclosed uncertainty. Records both verified facts, and separates "is the surface resolved" from "is the quota known" in the decision procedure so an unmodeled vendor can no longer read as a missing surface. No check is relaxed: this adds a positive evidence source rather than removing a requirement. Covered by a case in the live dispatch regression that supplies only the catalog row and a snapshot without the family. Against the previous procedure it reports surface=unresolved; with this change it reports surface=resolved.
Sharpen the generated status protocol so the correct reporting behavior is the obvious one: - Under no-mistakes, done: now means the PR is open with checks green. The implementation handoff before validation is a declared wait instead of a second done:, so a clean local commit can no longer read as finished. - The status protocol pairs the pause verb with working: around a backgrounded pipeline call, so a spent needs-decision: line no longer stands as the worker's state while the quiet pane raises stale alarms. - A resolved: line carries no state verb, so ship and scout contracts now require the next state line right after it; a trailing resolved: made a healthy worker read as unknown and look indistinguishable from a dead one. Covered by tests on the generated ship and scout briefs.
/bearings and /fleet failed outright in any home with a real backlog: bin/fm-fleet-snapshot.sh: line 567: jq: Argument list too long fm-fleet-snapshot: main inventory summary failed The cause is the per-argument limit, not the total one. Linux caps a SINGLE argv string at MAX_ARG_STRLEN (32 pages = 131072 bytes), independently of the much larger ARG_MAX, so execve fails with E2BIG once one --argjson payload crosses 128 KiB even though total argv size is far under the ceiling. The primary home's backlog JSON is 216172 bytes. Every jq payload whose size grows with the fleet is now bound with --slurpfile from a stream and unwrapped in the filter by a local `doc` helper, which also preserves --argjson's fail-closed behavior on an empty payload. Scalars, single paths, and per-record documents bounded by this script's FM_SNAPSHOT_* read bounds stay on --arg/--argjson. Sites converted: main inventory, secondmate home summary, the top-level assembly, the secondmate registry/task union, the per-secondmate record and its accumulator, the secondmate landed projection, the parent-evidence reconciliation, and Bearings' candidate-PR rows and accumulator. No schema, field, bound, or TOON change: output is byte-identical to the pre-bug behavior on a fixture the old code could still handle.
…able fm_backend_validate_task_endpoint requires an endpoint_task_id= binding before any non-tmux endpoint may be cleaned up, because herdr, zellij, orca and cmux endpoint ids are opaque and do not encode the task they belong to. fm-spawn.sh writes it for new tasks, but nothing migrated records already on disk, so every task spawned on those backends before that change refuses cleanup permanently. Add bin/fm-endpoint-binding-migrate.sh, a one-shot, idempotent sweep run from the locked bootstrap MUTATING section. It writes the binding only for a record whose recorded endpoint still resolves, live, to a runtime object carrying that task's own label - the same class of self-identifying evidence the legacy tmux path validates by window name. The candidate is committed only after the exact bytes that would land pass fm_backend_validate_task_endpoint itself, so the check is neither relaxed nor reimplemented. Every other outcome refuses and leaves the record byte-unchanged. A confirmed-gone endpoint is reported, never bound: absence is not proof of ownership, and a runtime may later reuse a freed opaque id. A binding written without proof would recreate the exact hazard the validation was added to prevent while looking like a fix. Also force C collation on the test runner's comm calls, whose inputs are already LC_ALL=C sorted; without it the coverage guard failed in a UTF-8 locale.
The coverage guard's comm calls run under the ambient locale on LC_ALL=C sorted input, so --check-coverage fails in a UTF-8 locale. That bug sits on the default branch and is owned by a dedicated task with a more complete fix, so carrying a second copy here would only guarantee a conflict. Only the backend-dispatch family registration for the new migration test remains in bin/fm-test-run.sh.
`tests/fm-test-run.test.sh` exited 1 with every assertion passing, and a stray `comm: not in sorted order` on stderr. The comparison was at fault, not the input. `run_coverage_guard` builds every lane list with `LC_ALL=C sort -u`, but called `comm` under the ambient locale. Evidence that settled it: the portable-serial list passes `LC_ALL=C sort -c` cleanly, and the identical file fails `sort -c` under en_US.UTF-8 at `tests/fm-backend.test.sh`. glibc's en_US.UTF-8 collation ignores `-` at the primary weight, so it orders `fm-backend.test.sh` before `fm-backend-tmux-smoke.test.sh`, while C compares bytes where `-` (0x2D) sorts before `.` (0x2E). The lists were correctly sorted for the ordering the runner chose; `comm` was applying a different one. The unguarded `comm -12` in the lane-overlap loop therefore exited 1 under the script's `set -eu`, killing the guard before it printed its verdict. The `|| true`-guarded `comm` calls were worse in kind: on mis-collated input they silently return a wrong set difference, so a real coverage hole could have passed the guard. Fix: prefix every `comm` in the coverage guard, and the three in this test, with `LC_ALL=C` so the set operations use the same collation as the sorts that produced their inputs. No warning is suppressed. Also fix why the failure was invisible. Each `set +e ... rc=$?; set -e` pair in the test enabled errexit rather than restoring it - the file's baseline is `set -u` only - so from the first pair onward any unguarded non-zero exited the suite silently, with no `not ok`. Replaced all ten with `rc=0; <cmd> || rc=$?`, which captures the status correctly whether or not errexit is on and leaks nothing. New `test_coverage_guard_is_collation_independent` asserts the guard exits 0 with empty stderr under C, the ambient locale, and the first installed locale whose collation actually disagrees with byte order, discovered by probe rather than hardcoded. It fails against the pre-fix runner.
Reconciles 68 upstream commits with the fork's 17 landed cursor/agy commits. 19 files conflicted; every conflict was resolved by keeping both sides' intent where compatible and by deferring to the newer owner where one side had moved a contract. Notable resolutions: - bin/fm-dispatch-select.sh and its test: accept upstream's removal of the vestigial selector; the fork had only annotated it. - tests/fm-captain-translation-contract.test.sh and the two source-asserting functions in tests/fm-pi-watch-extension.test.sh: accept upstream's removal of implementation-source assertions, which the coding guidelines now forbid. - bin/fm-launch-lib.sh stays the single owner of launch-command construction, and upstream's pi-signed and kimi templates plus their model/effort vocabularies are ported into it. fm-spawn keeps kimi's spawn-time binary resolution so the library's unresolved-placeholder guard still applies. - bin/fm-test-run.sh: the fork's live-harness-optin exclusion moves into list_portable_serial, upstream's single owner of serial membership, so the derived CI serial shards stay consistent and the coverage guard proves five disjoint partitions. - bin/fm-teardown.sh: upstream's exact-code error propagation replaces the fork's flattened variant, and the agy workspace-trust removal runs after the Herdr presentation preflight takes the lock guarding destructive steps.
Adds opt-in GitHub issue traceability. Reconciled against upstream's newer contract that a ship brief takes its delivery mode as an explicit --mode argument rather than reading the project registry: - fm-brief.sh keeps upstream's required, closed-set --mode and gains --issue. The branch's registry lookup is dropped; its issue/local-only guard now tests the explicit mode. - --issue argument-shape validation moved ahead of the --mode requirement so a malformed issue number reports itself instead of being masked. - The branch's three tests were ported to name a mode on every ship invocation. - tests/fixtures/fm-brief-no-issue.sha256 was regenerated against the merged tree's own pre-branch output, and the no-issue briefs were verified byte- identical before and after this branch, which is what that fixture exists to prove.
Both sides had hardened the same MISSING-tool fixture against host PATH leakage: the fork removes no-mistakes (never present in a system PATH), this branch adds hide_node. Both statements are kept, because the surrounding assertions require the no-mistakes MISSING line while the auto-merged run_session_start calls require the mask this branch produces.
Both sides had reached the same LC_ALL=C comm calls; the branch's fix also covers the serial-shard comparisons upstream added. Kept the fork's comment explaining why the collation must match.
The bootstrap-diagnostics trigger list took an addition from each side: the fork's widened CREW_DISPATCH (invalid or backend mismatch) and this branch's ENDPOINT_BINDING_MIGRATION. Both are real emitted lines, so both are listed.
Both sides added a window_harness helper to bin/fm-watch.sh, so the merge kept both and the later one silently shadowed the earlier. That changed what fm_busy_classify receives for a window with no metadata, from an empty string to the literal "unknown", with no conflict to review it. Upstream's definition is retained because its caller was written against the empty-string form. maybe_native_turnend matches only the exact cursor and agy tokens, so the crew-only native turn-end path behaves identically either way. Found by bin/fm-lint.sh (SC2329 on the shadowed definition).
While resolving bin/fm-teardown.sh in the upstream sync, I spliced the per-child cleanup branch using a context anchor that appears three times in the file. The edit landed on the first occurrence instead of the intended one and deleted everything between them, removing six upstream function definitions plus cleanup_firstmate_home_children: cleanup_firstmate_home_children, preflight_firstmate_home_herdr_children, teardown_herdr_preflight_target, teardown_herdr_require_prerequisites, teardown_herdr_session_lock_held, teardown_release_herdr_locks Surfaced by tests/fm-backend-autodetect-smoke.test.sh, where teardown died with "teardown_herdr_preflight_target: command not found". The file is rebuilt from a fresh three-way merge of the same inputs, with every conflict resolved as before but with anchors asserted unique first. The result is verified to define every function either side defines, with no duplicates and nothing extra; the single exception is registry_home_for_line, which upstream deleted outright and which has no remaining caller.
tests/fm-backend.test.sh: the legacy fake root that build_old_bin assembles did not carry fm-agy-trust-lib.sh, which the merged fm-teardown.sh sources for the cursor/agy workspace-trust cleanup, so the legacy teardown case died sourcing a file that was never copied. The fork made the same fixture completion in fm-gotmp.test.sh; this builder was missed because its dependency list grew on the upstream side. Both fake-root builders now carry the sibling. tests/fixtures/fm-brief-no-issue.sha256: regenerated against the final tree. These hashes were pinned when fm/fm-issue-lifecycle-wiring merged, and fm/fm-brief-status-protocol-gaps subsequently changed the crewmate scaffold's status protocol, which legitimately changes ship and scout brief bytes. Only those six entries moved; the two secondmate charters are unchanged, which matches a crewmate-scaffold-only change. The property this fixture exists to protect - that a no-issue brief is unaffected by the issue feature - was verified byte-for- byte when that branch merged and is still asserted by test_issue_traceability_is_strictly_opt_in.
The fork's cursor/agy test predates three upstream changes and could no longer reach the refusals it asserts: - Ship spawns now require explicit --mode and --yolo, and both checks run before the crew-only and herdr-only gates. The ship cases now name both; the --secondmate rows in the raw-bypass table deliberately pass neither, because a secondmate records its own fixed posture and refuses those flags. - fm/fm-endpoint-binding-migration refuses an endpoint record with no exact task binding, so the forced-child fixture now records endpoint_task_id. - That same fixture recorded its child on herdr, which now additionally has to clear teardown_herdr_preflight_target's structured pane inspection. The case is about cleanup_firstmate_home_children refusing when a child's firstmate-owned agy trust cannot be removed, which runs before any backend-specific work and is backend-independent, so the child is recorded on tmux instead. Faking herdr's pane protocol here would prove nothing about trust cleanup; real herdr endpoint behaviour stays covered by the real-herdr-gated lane. The gates themselves are unchanged; only the fixtures were conformed.
…ncile Sync the fork with upstream and land the ten reviewed changes
Author
|
This PR was opened against the upstream repository by a delivery-target misconfiguration. The authorized PR is HelloWorldSungin#26, whose base is the fork main and whose diff is limited to the reranker documentation. Closing this accidental upstream PR without merge. |
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
Stand up the reranker half of issue #5 as a fully local GPU-accelerated Qwen3-Reranker endpoint on this host’s 4x RTX 5060 Ti Blackwell sm_120 GPUs, without modifying, restarting, re-serving, or overwriting documentation for the separately owned embedding endpoint. Use a distinct port and GPU, follow GBrain’s llama-server reranker recipe, prefer a verified Blackwell-capable prebuilt but investigate the Nix split CUDA toolkit and use a pinned source build only when no verified prebuilt works; if building, record the exact llama.cpp commit, nixpkgs and toolkit paths, nvcc version, sm_120 support, and build flags. Pin the reranker model artifact, quantization, context and batch settings, endpoint alias and wire contract, source, license, hash, port, and runtime version. Provide an enabled boot-persistent user-level systemd unit only, with loopback binding, explicit environment, UUID device pinning on a GPU distinct from the embedding service, startup health check, crash restart policy, bounded journal logging, and offline serving. Record exact GBrain story #6 config and tested curl commands. Prove a fixed query and passage fixture sensibly puts the Paris passage first, show the serving process on the intended GPU, verify service restart and forced-crash recovery, and spot-check that reranking makes no cloud connection. The accepted implementation uses official ggml-org Qwen3-Reranker-0.6B Q8_0 with SHA-256 22c9979ce4fbcdc5acdc310c6641c32797eff1aa980b8f7a2db8a8ea23429a48 on GPU 1 UUID GPU-7ef74f00-ba0f-c5e9-2235-a8e7b2ca930e and port 8081, with pinned nixpkgs CUDA llama.cpp 10063 after official Linux CUDA was unavailable and the Vulkan prebuilt lacked an NVIDIA ICD. Comment substantively on issue #5, publish the PR only to HelloWorldSungin/firstmate with body Closes #5, keep the embedding branch and service out of scope, and do not merge without the captain’s explicit word.
What Changed
Risk Assessment
🚨 High: Captain, the reranker endpoint and documentation conform to the stated intent, but the two new read-modify-replace paths can lose concurrent task metadata or captain-owned agy settings and should not merge as written.
Testing
No baseline results were supplied; targeted documentation testing and live read-only API, artifact, runtime, GPU, network, and recovery checks otherwise passed and produced reviewer-visible CLI transcripts, but journal evidence proves the embedding service was restarted and killed during verification, so the authoritative intent is not satisfied. This is a headless API change, so rendered UI evidence was not applicable.
Evidence: Live health and reranking API transcript
Evidence: Pinned model, runtime, CUDA, GPU, and network evidence
Evidence: User-only unit and lingering evidence
Evidence: Reranker restart and forced-crash recovery journal
Evidence: Embedding-service acceptance violation
The embedding service was stopped and restarted at 04:33:46 UTC, then received SIGKILL on client request at 04:33:51 and restarted again.Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
⏭️ **Rebase** - skipped
.agents/skills/afk/SKILL.md- branch carries 58 commit(s) that exist on your local main branch but were never pushed to origin/main; rebasing would bundle this unrelated work (69 file(s)) into the PR:Push main to origin, or rebase your branch onto origin/main, before gating.
bin/fm-endpoint-binding-migrate.sh:229- The concurrency guard has a check-to-replace race: another live writer such as fm-pr-check.sh, fm-x-lib.sh, or fm-spawn.sh can update the task metadata after this cmp succeeds but before the later mv, causing migration to overwrite that update with its stale snapshot. Protect the complete compare-and-publish operation with a per-task metadata lock honored by every read-modify-write owner.bin/fm-agy-trust-lib.sh:115- The custom .fm-trust.lock only coordinates Firstmate callers. A concurrent native agy or captain edit after this function reads settings but before its unconditional mv is silently overwritten, potentially losing unrelated settings or trust entries. Use agy's supported settings mutation or locking boundary so native and Firstmate writers participate in the same serialization contract.docs/verification/gbrain-reranker.md:139- The authoritative intent forbids restarting the separately owned embedding endpoint, but the systemd journal proves gbrain-embedding.service was stopped and restarted at 04:33:46 UTC, then deliberately SIGKILLed on client request at 04:33:51 and restarted again. This occurred during the documented reranker recovery-verification window. The historical side effect cannot be undone with a safe source or test fix, so this change does not satisfy the required operational constraint.bash tests/fm-documentation-audiences.test.shLivecurlhealth check and fixed Paris reranking fixture against127.0.0.1:8081Focused shell assertions for response ordering, alias, user-unit enablement, loopback binding, offline mode, context/batch settings, restart policy, model hash/size, runtime version, sm_120 support, intended GPU UUID, and absence of remote serving socketssystemctl --user is-enabled/is-active/show/cat gbrain-reranker.serviceand system-levelsystemctl is-enabled gbrain-reranker.servicescope checksha256sumandstaton the deployed Q8_0 GGUFDeployedllama-server --versionand pinnednvcc --version/nvcc --list-gpu-archnvidia-smi --query-gpuand--query-compute-appsGPU/process checksss -anptplus/proc/<pid>/environand process-map inspection for loopback-only networking and pinned CUDA librariesRead-onlyjournalctl --userverification of reranker restart and forced-crash recoveryRead-onlysystemctlandjournalctlcomparison of the separately owned embedding serviceConfirmed the worktree remained clean after evidence capture withgit status --short✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.