Skip to content

test: clear inherited launcher environment in shared fixtures - #7589

Merged
kunchenguid merged 6 commits into
kunchenguid:mainfrom
babbarc:fm/offer-fleet-env-leak-fixes-upstream
Nov 1, 2026
Merged

kunchenguid merged 6 commits into
kunchenguid:mainfrom
babbarc:fm/offer-fleet-env-leak-fixes-upstream

Conversation

@babbarc

@babbarc babbarc commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Offer the local launcher-environment fixes to the firstmate project upstream as a pull request.

The fix being offered is the fixture-level environment sanitization in tests/lib.sh: a suite run from a Herdr-hosted terminal inherits the launcher's own identity (the Herdr pane and socket variables), its terminal marker, and the home/state overrides a supervisor shell exports, so spawn and backend fixtures bind to the host's real session instead of the isolated one their case creates - several suites then fail with a launcher/belongs-to-another-session error, or record a real workspace's pane path as a fixture worktree, while the same suites pass in CI. The suite's shared fixture layer should start from the environment CI gives it, while a case that deliberately exercises a launcher identity or a home/state override keeps working by exporting its own value afterwards.

Context: the matching production-side correction (a restored second mate keeping its own home despite a leaked launcher environment) is already offered upstream as a separate pull request and is deliberately out of scope here.

do an upstream pull. rebase our commits on top

What Changed

  • tests/lib.sh now unsets the inherited Herdr identity and socket variables (HERDR_*), TERM_PROGRAM, FM_BACKEND, and the home/state overrides (FM_HOME, FM_ROOT, and the FM_*_OVERRIDE set), so every suite that sources it starts from a CI-like environment. A case can still export its own value after sourcing.
  • The two T3 Code live suites capture FM_CONFIG_OVERRIDE into LIVE_CONFIG before sourcing tests/lib.sh, so an operator's config override still locates the token file.
  • tests/fm-test-fixtures.test.sh adds a regression test that the inherited variables are cleared, that backend and config resolution ignore the decoy values, and that a launcher identity, backend, or home exported afterwards is honored.

🤖 Generated with Claude Code

Risk Assessment

✅ Low: The change is test-only and runs after no-exported-state dependents were traced: no suite sets a cleared name before its first lib.sh source, the only documented operator input (FM_CONFIG_OVERRIDE for the T3 live suites) is captured before sourcing and the token is passed explicitly to the helper, and the session-lock test is net unchanged.

Testing

Provisioned a named fm-lab Herdr session and ran 34 launcher-sensitive suites directly from real panes, carrying real HERDR_* identity, TERM_PROGRAM=herdr and decoy FM_HOME/state/config overrides, against both the fix and a pre-fix tests/lib.sh copy. Exit status was captured per suite without pipes. All 34 pass with the fix. Pre-fix, 25 exited non-zero: 24 real failures, plus orca, which only recorded my driver's timeout. Two suites first stalled under my driver's plain timeout in a pane; with timeout --foreground orca passed 26 cases and dispatch-profile passed 100. Separate decoy homes showed 0 files written with the fix and 10 without it, and the pre-fix runs also created stray fixture workspaces in the launcher's lab session. T3 override routing was driven with a disposable config, but a real T3 server was not available. The session-lock suite fails identically with and without the fix. Lab torn down with the helper's tripwire check passing, temp files removed, worktree clean. Rendered UI evidence does not apply: this is a test-fixture change with no visual surface.

  • Live validation: ✅ go - 7 of 8 scenarios driven live against the product
Scenario Result Live Evidence
A developer runs spawn/backend suites directly from a Herdr pane with leaked supervisor overrides and they pass as in CI ✅ pass live suite-exit-status-herdr-pane.tsv and launcher-env-in-lab-pane.txt: 34 of 34 pass with the fix; pre-fix 24 fail on the leak, and orca's exit 137 was a driver timeout
The reported 'launcher pane belongs to another session' failure appears without the fix and is gone with it ✅ pass live pre-fix-launcher-errors.txt shows herdr launcher pane 'w2:p1' belongs to the server at ...; the same match in the fixed logs returned 0 suites
Fixtures do not bind to the launcher's real session (adversarial) ✅ pass live lab-workspaces-after-runs.txt: stray settle-single-stale-z1 fixture workspaces w3 and w5 appeared, each created after a pre-fix run started; the first fixed run preceded w3, and none appeared after…
A leaked FM_HOME and state/config overrides are not written to by a suite (adversarial) ✅ pass live decoy-home-writes.txt: 0 files written to the fixed run's decoy, 10 to the pre-fix run's decoy, over the same 7 suites
A case that exports its own launcher identity, backend or home after sourcing the library is honored ✅ pass live tests/fm-test-fixtures.test.sh exit 0 from the lab pane and via bin/fm-test-run.sh, plus launcher-identity suites fm-backend-herdr and fm-herdr-groups in the TSV
The documented T3 live command still reads the operator's FM_CONFIG_OVERRIDE after sourcing the library ✅ pass live t3-config-override.txt: both live suites report the credential path under the named override; a credential there reaches bin/fm-t3-mcp.mjs; no override falls back to checkout config; an explicit token…
A credential-backed T3 refresh completes against a real T3 server ⏸️ untested no Tried a disposable credential at the override; it reached the helper but no server. No T3 server binary is on PATH and the operator's real credential is off limits for this run, so an end-to-end refre…
The session-lock ancestry suite is unaffected by this change ✅ pass live session-lock-fixed.log and session-lock-prefix.log both end with not ok - the pty-host was not reparented to init after the daemon ended; the branch diff leaves that test unmodified
Evidence: Per-suite exit status from a real Herdr pane, pre-fix vs fixed

Source: Per-suite exit status from a real Herdr pane, pre-fix vs fixed

suite	pre_fix_exit	fixed_exit	fixed_time
fm-backend-herdr.test.sh	0	0	30s
fm-backend-t3code.test.sh	1	0	177s
fm-backend.test.sh	1	0	21s
fm-backend-tmux-smoke.test.sh	0	0	2s
fm-claude-trust.test.sh	1	0	12s
fm-control-relaunch.test.sh	1	0	124s
fm-control.test.sh	1	0	44s
fm-extension-binding.test.sh	1	0	19s
fm-git-strip-ai-trailers.test.sh	0	0	2s
fm-harness-precedence.test.sh	1	0	3s
fm-herdr-groups.test.sh	0	0	4s
fm-herdr-session-cleanup.test.sh	0	0	7s
fm-project-capacity.test.sh	0	0	56s
fm-secondmate-harness.test.sh	1	0	156s
fm-secondmate-liveness.test.sh	1	0	22s
fm-send-inbox.test.sh	1	0	10s
fm-send-resolve-key.test.sh	1	0	24s
fm-send-strict.test.sh	1	0	2s
fm-session-start.test.sh	1	0	179s
fm-spawn-batch.test.sh	0	0	2s
fm-spawn-compact-adviser-disable-remote.test.sh	1	0	62s
fm-spawn-compact-adviser-disable.test.sh	1	0	28s
fm-spawn-dispatch-profile.test.sh	1	0	359s
fm-spawn-external-review.test.sh	1	0	5s
fm-spawn-manual-pr-text.test.sh	1	0	6s
fm-spawn-orca-worktree.test.sh	137	0	46s
fm-spawn-pool-base-freshen.test.sh	1	0	127s
fm-spawn-worktree-settle.test.sh	1	0	9s
fm-t3-mcp.test.sh	0	0	25s
fm-teardown-endpoint-safety.test.sh	1	0	28s
fm-test-fixtures.test.sh	1	0	7s
fm-tmux-agent-liveness.test.sh	0	0	3s
fm-trace-context-spawn.test.sh	1	0	50s
fm-worker-account.test.sh	1	0	56s
note: pre_fix orca exit 137 was the driver's own timeout-tty artifact; both long suites' fixed rows come from timeout --foreground reruns
Evidence: Launcher environment inherited in the lab pane

Source: Launcher environment inherited in the lab pane

FM_BACKEND=herdr
FM_HOME=/tmp/fm-envleak/decoy
FM_STATE_OVERRIDE=/tmp/fm-envleak/decoy/state
HERDR_BIN_PATH=~/.local/bin/herdr
HERDR_ENV=1
HERDR_PANE_ID=w1:p1
HERDR_SESSION=fm-lab-envleak-1510401-22339
HERDR_SOCKET_PATH=~/.config/herdr/sessions/fm-lab-envleak-1510401-22339/herdr.sock
HERDR_TAB_ID=w1:t1
HERDR_WORKSPACE_ID=w1
TERM_PROGRAM=herdr
Evidence: Reported launcher error reproduced pre-fix

Source: Reported launcher error reproduced pre-fix

error: herdr launcher pane 'w2:p1' belongs to the server at '~/.config/herdr/sessions/fm-lab-envleak-1510401-22339/herdr.sock', not session 'fm-lab-envleak-1510401-22339' at '/tmp/fm-backend-tests.YYOQCM/user-ho
ok - fm_backend_herdr_launcher_identity: refuses a launcher pane whose injected socket belongs to another herdr server
Evidence: Files written into the leaked decoy home, fixed vs pre-fix

Source: Files written into the leaked decoy home, fixed vs pre-fix

== decoy-after: files written into the leaked home
== decoy-before: files written into the leaked home
./config/startup-memory-budget
./data/pr-text-s1/brief.md
./state/home-summary.json
./state/.lock
./state/.session-start-complete
./state/t3code-sends/f53297567028301f008f37b0fab83c34dfdec7ec9c300cf9f9e985d4496a5c7f
./state/t3code-sends/fm-1793487508-3818595-1531.accepted
./state/t3code-sends/fm-1793487511-3822466-418.accepted
./state/.trace-context-effective
./state/.wake-queue
Evidence: Lab workspaces after the runs, showing stray fixture workspaces

Source: Lab workspaces after the runs, showing stray fixture workspaces

{"workspace_id":"w1","label":"after"}
{"workspace_id":"w2","label":"before"}
{"workspace_id":"w3","label":"└ settle-single-stale-z1 · p:4h5SUFPA39hxKY8npsgm7A"}
{"workspace_id":"w4","label":"before2"}
{"workspace_id":"w5","label":"└ settle-single-stale-z1 · p:Ta8mtBaVvFDK9IZhCVu0sQ"}
Evidence: T3 live suite override transcript

Source: T3 live suite override transcript

# 1 no credential at the named override (bash, direct)
skip: live: no T3 credential at <lab>/config/t3code-token
exit=0
# 2 documented runner command, no credential
FM_TEST_END 2026-10-31T22:37:08Z tests/fm-backend-t3code-live-e2e.test.sh exit=0 duration_ms=249 gate_skip=true
FM_TEST_SUMMARY total=1 failed=0 skipped_gate=1 duration_ms=299
FM_TEST_SUMMARY_FAMILY family=live-harness-optin count=1 duration_ms=249 failed=0
FM_TEST_SLOWEST rank=1 script=tests/fm-backend-t3code-live-e2e.test.sh duration_ms=249
exit=0
# 3 pr-tools opt-in, no credential
not ok - FM_T3CODE_PR_TOOLS_LIVE was requested but there is no T3 credential at <lab>/config/t3code-token
exit=1
# 4 credential present at override, server down
not ok - T3 status refused (exit 4): {"ok":false,"error":{"code":"credential_permissions","message":"T3 credential <lab>/config/t3code-token is readable by others (mode 644); chmod 600 it or sign in again"}}
exit=1
# 5 no override at all falls back to checkout config
skip: live: no T3 credential at ~/.no-mistakes/worktrees/b2ec250c52f2/01M6A1HNKV5VPQFVZ6TZRMCZTQ/config/t3code-token
exit=0
# 6 explicit token file still outranks
skip: live: no T3 credential at <lab>/none
exit=0
Evidence: Session-lock suite log with the fix

Source: Session-lock suite log with the fix

ok - session-lock: a version-named Claude Code session is identified from its install path and argv[0]
ok - session-lock: a harness that is pid 1 of its own namespace is examined, not skipped
ok - session-lock: ordinary script paths under a harness directory are not harness processes
ok - session-lock: ownership stops at the first non-harness gap above the contiguous run
ok - session-lock: a live version-named session holding the lock is not mistaken for a stale owner
ok - session-lock: a trusted same-session id keeps owning a recycled background chain, and nothing weaker does
ok - session-lock: a trusted id anchors the lock on the model-loop process, anything else on the outermost pid
ok - session-lock: a Windows session is identified from its published pid across the severed parent link
ok - session-lock: a published Windows pid is confirmed against the process table before it is trusted
ok - session-lock: a tagged Windows pid is never resolved against the Cygwin process table
ok - session-lock: a published identity is accepted by every gate that reads the lock
ok - session-lock: a live tagged lock holder is a live foreign owner to a second Windows session
ok - session-lock: a published Windows Claude pid is accepted only with its session id
ok - session-lock: a Windows /clear keeps the lock and re-keys its session id
ok - session-lock: a Windows-tagged lock stays inert off Windows
ok - session-lock: a task lease follows a live tagged lock holder and goes stale when it exits
ok - session-lock: a harness in the local process table resolves untagged when ps has no -o option
ok - session-lock e2e: a version-named session claims the home and arms supervision
ok - session-lock e2e: a session parented by a harness-named daemon claims the home and arms supervision
ok - session-lock e2e: a version-named session under a harness-named daemon keeps its own lock
not ok - the pty-host was not reparented to init after the daemon ended
Evidence: Session-lock suite log on the pre-fix copy

Source: Session-lock suite log on the pre-fix copy

ok - session-lock: a version-named Claude Code session is identified from its install path and argv[0]
ok - session-lock: a harness that is pid 1 of its own namespace is examined, not skipped
ok - session-lock: ordinary script paths under a harness directory are not harness processes
ok - session-lock: ownership stops at the first non-harness gap above the contiguous run
ok - session-lock: a live version-named session holding the lock is not mistaken for a stale owner
ok - session-lock: a trusted same-session id keeps owning a recycled background chain, and nothing weaker does
ok - session-lock: a trusted id anchors the lock on the model-loop process, anything else on the outermost pid
ok - session-lock: a Windows session is identified from its published pid across the severed parent link
ok - session-lock: a published Windows pid is confirmed against the process table before it is trusted
ok - session-lock: a tagged Windows pid is never resolved against the Cygwin process table
ok - session-lock: a published identity is accepted by every gate that reads the lock
ok - session-lock: a live tagged lock holder is a live foreign owner to a second Windows session
ok - session-lock: a published Windows Claude pid is accepted only with its session id
ok - session-lock: a Windows /clear keeps the lock and re-keys its session id
ok - session-lock: a Windows-tagged lock stays inert off Windows
ok - session-lock: a task lease follows a live tagged lock holder and goes stale when it exits
ok - session-lock: a harness in the local process table resolves untagged when ps has no -o option
ok - session-lock e2e: a version-named session claims the home and arms supervision
ok - session-lock e2e: a session parented by a harness-named daemon claims the home and arms supervision
ok - session-lock e2e: a version-named session under a harness-named daemon keeps its own lock
not ok - the pty-host was not reparented to init after the daemon ended
- Outcome: ⚠️ 1 info across 1 run (36m35s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

⚠️ **Test** - 1 info
  • ℹ️ tests/fm-session-lock-ancestry.test.sh - This suite exits 1 on this host with and without the fix, with not ok - the pty-host was not reparented to init after the daemon ended. It is unrelated to this change and deliberately left unmodified per the author's plan.
  • Live validation: ✅ go - 7 of 8 scenarios driven live against the product
Scenario Result Live Evidence
A developer runs spawn/backend suites directly from a Herdr pane with leaked supervisor overrides and they pass as in CI ✅ pass live suite-exit-status-herdr-pane.tsv and launcher-env-in-lab-pane.txt: 34 of 34 pass with the fix; pre-fix 24 fail on the leak, and orca's exit 137 was a driver timeout
The reported 'launcher pane belongs to another session' failure appears without the fix and is gone with it ✅ pass live pre-fix-launcher-errors.txt shows herdr launcher pane &#39;w2:p1&#39; belongs to the server at ...; the same match in the fixed logs returned 0 suites
Fixtures do not bind to the launcher's real session (adversarial) ✅ pass live lab-workspaces-after-runs.txt: stray settle-single-stale-z1 fixture workspaces w3 and w5 appeared, each created after a pre-fix run started; the first fixed run preceded w3, and none appeared after…
A leaked FM_HOME and state/config overrides are not written to by a suite (adversarial) ✅ pass live decoy-home-writes.txt: 0 files written to the fixed run's decoy, 10 to the pre-fix run's decoy, over the same 7 suites
A case that exports its own launcher identity, backend or home after sourcing the library is honored ✅ pass live tests/fm-test-fixtures.test.sh exit 0 from the lab pane and via bin/fm-test-run.sh, plus launcher-identity suites fm-backend-herdr and fm-herdr-groups in the TSV
The documented T3 live command still reads the operator's FM_CONFIG_OVERRIDE after sourcing the library ✅ pass live t3-config-override.txt: both live suites report the credential path under the named override; a credential there reaches bin/fm-t3-mcp.mjs; no override falls back to checkout config; an explicit token…
A credential-backed T3 refresh completes against a real T3 server ⏸️ untested no Tried a disposable credential at the override; it reached the helper but no server. No T3 server binary is on PATH and the operator's real credential is off limits for this run, so an end-to-end refre…
The session-lock ancestry suite is unaffected by this change ✅ pass live session-lock-fixed.log and session-lock-prefix.log both end with not ok - the pty-host was not reparented to init after the daemon ended; the branch diff leaves that test unmodified
  • 34 suites run directly (bash tests/&lt;suite&gt;.test.sh) from real Herdr lab panes via bin/fm-herdr-lab.sh, on the fix and on a pre-fix tests/lib.sh copy, with per-suite exit status recorded in a TSV
  • timeout --foreground reruns of tests/fm-spawn-orca-worktree.test.sh and tests/fm-spawn-dispatch-profile.test.sh in a lab pane
  • tests/fm-test-fixtures.test.sh from the lab pane and via bin/fm-test-run.sh
  • Isolated decoy-home hash comparison for fixed and pre-fix runs over 7 suites that wrote into the shared decoy
  • Lab workspace listing after the runs, to detect fixtures bound to the launcher's session
  • FM_CONFIG_OVERRIDE=&lt;lab&gt;/config bin/fm-test-run.sh tests/fm-backend-t3code-live-e2e.test.sh and direct runs of both T3 live suites: override present, absent, with credential, and with an explicit token file
  • tests/fm-spawn-orca-worktree.test.sh outside the lab, to isolate the driver stall
  • tests/fm-session-lock-ancestry.test.sh on the fix and on the pre-fix copy
  • bin/fm-herdr-lab.sh teardown tripwire check
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Thanks @babbarc, and welcome. I read the diff at 76f0b100 against main. It's one unset block in tests/lib.sh. It touches no product code, workflows, or CI scripts.

  • Contract class: restore (test-only). tests/lib.sh already clears inherited operator state such as FM_TASK_ID and the tasks-axi overrides, so every suite starts from CI's environment. This extends that same isolation to the Herdr launcher identity, TERM_PROGRAM, FM_BACKEND, and the home and state overrides. An unconfigured firstmate run behaves exactly the same.
  • I checked that the suites that set FM_BACKEND, FM_CONFIG_OVERRIDE, and similar values do so after sourcing the helpers, so this doesn't clear them. CI will confirm the rest.
  • The no-mistakes attestation is bound to this head, and your base-vs-fix live run covers the reported symptoms. Thank you for including the per-suite logs.

This was a first-time fork run, so I approved the CI and no-mistakes workflow runs. There's nothing you need to do right now. If CI comes back green, this is ready to merge on the next pass.

@babbarc
babbarc force-pushed the fm/offer-fleet-env-leak-fixes-upstream branch from 76f0b10 to 237d4c4 Compare October 23, 2026 19:52
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @babbarc for the update.

What I checked: the new head 237d4c4d against main 86437e28 (mergeable). It's still the single unset block in tests/lib.sh: Herdr launcher identity, TERM_PROGRAM, FM_BACKEND, and the home/state overrides. No product code, workflows, or CI scripts change. It doesn't touch bin/fm-test-run.sh or tests/fm-test-run.test.sh, so it doesn't overlap the main-red fix in #7699. A fresh fork run needed approval again, so I've approved CI and the no-mistakes check for this head.

Contract-class: restore (test-only), unchanged: tests/lib.sh already promises that every suite starts from CI's environment (it clears FM_TASK_ID and the tasks-axi overrides), and this extends that to the launcher variables. An unconfigured firstmate run is unaffected. VISION.md: One captain aligns · Authority aligns · Scripts aligns · Restart aligns · Delegation aligns (tests isolated from the host make supervision evidence trustworthy) · Vendor aligns (keeps Herdr host identity out of fixtures) · Scope aligns.

One thing I need from you: the no-mistakes attestation in the PR body still points at the earlier head 76f0b100, not 237d4c4d. Could you re-raise it with git push no-mistakes so the attestation covers this head? Once that's done and CI is green, it's eligible to merge. If the only red is the packing exactly at the budget case in Behavior portable parallel 2, that one is inherited from main and won't count against this PR.

@babbarc babbarc changed the title test: start suites from CI's environment, not the launching terminal's fix(tests): clear inherited launcher environment in the shared test library Oct 31, 2026
@greptile-apps

greptile-apps Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge.

Reviews (3) · Last reviewed commit: "test: keep the session-lock subreaper fi..." · Reviewed by Greptile

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thanks @babbarc. Head acf4f54f answers my 10-23 ask: the no-mistakes attestation now binds this head, and live validation is go 5/5. You also added test_inherited_launcher_env_is_cleared, which shows the decoy launcher variables are cleared and that values exported later are still honored. Greptile rates it safe, and the branch merges cleanly with main 30d6d15e.

It's still test-only (tests/lib.sh and tests/fm-test-fixtures.test.sh) with no workflow, network or credential changes, so I approved the first-time-contributor runs on this head: CI 41211063795 and Require no-mistakes 41211063730 / 41211077165.

One small thing from you (this is waiting on you): the attestation's rebase step shows as skipped, and the merge gate needs every step to run on the head. When it suits you, please re-raise once more with git push no-mistakes and let every step complete. Your live evidence carries over if nothing changes. After that, the full suite is on us. Please ignore the Full suite check until then.

Contract-class: restore (test-only), unchanged. VISION: every rule aligns, as before.

@babbarc
babbarc force-pushed the fm/offer-fleet-env-leak-fixes-upstream branch from acf4f54 to efa1e04 Compare October 31, 2026 19:07
@babbarc babbarc changed the title fix(tests): clear inherited launcher environment in the shared test library test: start suites from CI's environment, not the launching terminal's Oct 31, 2026
yeti added 6 commits October 31, 2026 22:33
…minal's

A suite run directly from a terminal hosted by herdr inherited that launcher's
identity (HERDR_ENV, HERDR_PANE_ID, HERDR_SOCKET_PATH and siblings), its
TERM_PROGRAM marker, the FM_BACKEND selector bin/fm-spawn.sh exports into task
panes, and any home/state override (FM_HOME, FM_*_OVERRIDE) a supervisor shell
exports. Spawn and backend fixtures then bound to the host's real herdr session
instead of the isolated one their case creates: several suites failed with
`herdr launcher pane '...' belongs to the server at ... not session 'default'`,
and fm-spawn-worktree-settle recorded a real workspace's pane path as a fixture
worktree, while the same suites passed in CI. The effect only appears on a
herdr-hosted machine.

Clear that inherited environment once in tests/lib.sh, the shared fixture
layer. bin/fm-test-run.sh already cleared the overrides and FM_BACKEND per
worker, but not the herdr identity, and a direct `bash tests/x.test.sh` run got
neither. A case that deliberately exercises a launcher identity, a backend, or a
home/state override still exports its own value after sourcing the library.
The reparent assertion in fm-session-lock-ancestry fails the same way on
untouched upstream under a child subreaper, so it is a pre-existing host
portability issue this change did not cause. Restore the file so the offer
carries only what the launcher-environment fix requires.
@babbarc
babbarc force-pushed the fm/offer-fleet-env-leak-fixes-upstream branch from efa1e04 to e6fbf87 Compare October 31, 2026 23:12
@babbarc babbarc changed the title test: start suites from CI's environment, not the launching terminal's test: clear inherited launcher environment in shared fixtures Oct 31, 2026
@kunchenguid kunchenguid added the full-ci Maintainer go-ahead: run the full CI suite on this outside pull request label Nov 1, 2026
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: thank you @babbarc for re-raising. The attestation now binds head e6fbf87a with every step completed, including rebase, and live validation is go 7/8. You also kept the session-lock subreaper change out of this offer, so the diff is test-only again: tests/lib.sh clears the inherited Herdr identity, TERM_PROGRAM, FM_BACKEND and the home/state overrides. The two T3 live suites capture FM_CONFIG_OVERRIDE before sourcing, and test_inherited_launcher_env_is_cleared covers both directions. No workflow, network or credential changes. The first-time-contributor runs on this head were approved last pass, and the quick checks pass. Greptile passes with no threads.

I've added the full-ci label so the full suite runs. Contract-class: restore (test-only). The unconfigured product is unchanged, and suites start from the environment CI gives them, as tests/lib.sh already promises for other inherited state. If it's green, this can merge. VISION: aligns. It's in-scope validation discipline and changes no authority, restart or delegation behavior.

@kunchenguid
kunchenguid merged commit f1ad899 into kunchenguid:main Nov 1, 2026
32 of 33 checks passed
@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate: this is merged. Thank you @babbarc — really appreciate you taking the time on this.

nathanjgaul-agile added a commit to nathanjgaul-agile/firstmate that referenced this pull request Nov 2, 2026
* fix(bin): keep failed or non-schema remote reply reads out of captures (#7874)

* Keep malformed remote reply captures from wedging

* no-mistakes(document): Fix garbled remote reply source failure comment

* no-mistakes(document): Document remote reply failure handling

---------

Co-authored-by: Pitch Perfekt Collective <[email protected]>

* feat(bin): add per-project pr=manual registry token for worker-written PR text (#7937)

* feat(bin): per-project pr=manual registry token for hand-written PR text

A no-mistakes ship on a project where an outside maintainer reviews the PR let
the pipeline's pr step rewrite the hand-written title and body on every
validated push. The registry now records pr=manual, resolved by
fm-project-mode.sh --pr and carried by fm-brief.sh --pr, fm-spawn.sh and
fm-promote.sh like forge=. The generated brief skips pr and ci, and the worker
writes and publishes the PR text itself.

* no-mistakes(review): Drop pr_text key; fix manual-PR checks wait and base

* no-mistakes(review): Remove dead PR_TEXT and timeout example

* no-mistakes(document): Fix README pr=manual sentence grammar

* test(bin): restore the displaced placeholder comment and rename the spawn agreement test

The comment for the leftover-placeholder test sat above the new pr=manual tests.
The spawn test said it recorded the PR text, but it only checks that a launch happens.

* fix: refuse teardown when Git hides untracked files (#7909)

* fix(teardown): detect untracked work regardless of Git status config

* test(watcher): avoid blocking FIFO contention handshakes

* no-mistakes(document): Document hidden-untracked teardown safety

---------

Co-authored-by: Kun Chen <[email protected]>

* fix(bin): keep newest run attribution in crew-state (#5954)

* fix: prefer current run over stale overview row

* fix: preserve newest run precedence over stale status

* no-mistakes(document): Document live-run precedence in crew-state attribution

* fix: use ledger order for same-minute run precedence

* test: cover both overview orders for same-minute run attribution

Document and pin newer-first (recorded AXI) and historical-first overview
orders. Same-minute ledger timestamps use row order as the tie-break so an
older live bare status cannot hide a newer completed run.

* no-mistakes(review): Treat failed as overridable terminal overview status

* no-mistakes(review): Fix equal-head live run precedence with identity ordering

* no-mistakes(document): Updated run identity ordering documentation

* no-mistakes(lint): Fix ShellCheck export warning

* no-mistakes(review): Prove same-head ordering or report unknown

* no-mistakes(review): Guard failed selected-run reads and drop dead same-head ordering

* no-mistakes(ci): I fixed both Greptile findings (ci-1, ci-2) in bin/fm-crew-state.sh. The change is in the working tree. I did not commit it, push it, or reply to the Greptile threads, because those steps belong to the outer pipeline. ci-1. Invariant: a live run from bare `axi status` may replace a terminal overview selection only when it is proven newer than every other run on the same branch. Previously the code compared it only against the selected run. Now crew-state reads each other candidate with `axi status --run <id>` and compares the live run against each one: - If another candidate is also live, it reports `unknown`, "competing live runs". This keeps the competing-live-runs check. - If two runs share a head and a ULID timestamp, it reports `unknown`, "same-head run ordering unverified", as before. - It promotes the live run only when it is proven newer than all other candidates. - If the live run is newer than the selected run but not proven newer than some other candidate, it reports `unknown`, "run ordering unverified", and names every run id. This means neither the stale selected run nor the live run can hide a newer failed run. This branch is the one judgement call: without it, the stale "done" row A would still hide C's failure. - In all other cases the overview's selection stands. The lib helper is now a pairwise compare called `fm_nm_run_is_newer_than` (it was `fm_nm_run_is_newer_than_selected`). The selected run's detail from the loop is reused when the read succeeded, as in the round-1 fix. I updated the sentence in docs/architecture.md to match. ci-2. Invariant: the `no-mistakes runs` ledger is read only to order runs with different heads. It is now fetched lazily, at most once, and only when a candidate's head differs from the live run's head. Same-head ULID comparisons never call it. Regression test: `test_live_run_newer_than_selection_does_not_hide_newer_failed_run` covers A (stale completed, listed first), C (newer failed) and B (live, created between them). All three share one head and use ULID ids. It expects `state: unknown`, C's id in the output, and no `state: working`. Before the fix it fails: with the fixed code stashed it printed `state: working ... run: 01M1...` (run B). On the original base 3fbace9f the overview would select A, so the output would be `done`, which also fails the `unknown` check. I did not run that base case. Verification: `bash tests/fm-crew-state.test.sh` passes in full ("all fm-crew-state tests passed", the new test included). `shellcheck` on the three changed shell files reports only the existing info-level SC1091 "not following sourced file" notes. No end-to-end run against a live no-mistakes daemon was possible here. I checked the change with the crew-state test harness and its fake `no-mistakes` CLI

---------

Co-authored-by: mehulbhagwani <[email protected]>
Co-authored-by: Pitch Perfekt Collective <[email protected]>

* chore(ci): run the full suite on outside pull requests only after the full-ci label

Outside pull requests run only the coverage guard and repo invariants until the full-ci label is added; lint and every test lane wait.

A new Full suite check fails naming the full-ci label until it is added, and fails whenever a lane fails or is cancelled.

The label starts the full suite, and later pushes run it again; main pushes, own branches and write-access authors run everything as before.

Other labels run no job at all: their skipped checks take a 'Not run for label - ' prefix, so they cannot hide an earlier failure or a later pass.

Close main pushes keep only the newest run; CONTRIBUTING.md explains the label, and the full-ci label now exists.

* feat(bin): add opt-in systemone and openai decision providers to dispatch resolution (#7664)

* feat(bin): add opt-in systemone and openai providers to typed dispatch resolution

Extend the FM_DISPATCH_PROVIDER/FM_DISPATCH_MODEL seam with a generic
systemone provider (any System One-compatible host at FM_DISPATCH_BASE_URL,
optional FM_DISPATCH_API_KEY) and an openai provider that maps the Choice
request to OpenAI's Decisions API and its answer back. No provider set keeps
the original off line; the never-send check runs on the endpoint and the final
per-provider body. Live provider captures are recorded as pending.

Refs #7643, builds on #7149.

* docs(verification): record the live OpenAI Decisions capture for dispatch resolution

Add a dated 2026-10-23 section for the openai provider: 25 hand-labeled
synthetic briefs against gpt-6-luna, outcome and latency tables, the usage
and header fields actually returned, a calibration note, and one verbatim
request and response pair. The systemone live check stays pending.

Refs #7643.

* docs(verification): record the live Clef capture for the systemone provider

Replace the pending systemone section with a dated 2026-10-23 run against
Cloudflare Workers AI's @cf/cloudflare/clef, reached through a local
test-only relay because Workers AI serves System One at /ai/run/<model> in
a {result, success} envelope. Adds the outcome and latency tables, a
calibration note compared with the gpt-6-luna run, and one verbatim request
and envelope pair. A direct Workers AI option stays out of scope.

Refs #7643.

* feat(bin): promote agy to a full primary and secondmate harness (#7941)

* feat(agy): promote Antigravity CLI to full primary and secondmate harness

Add tracked .agents/hooks.json, bin/fm-sessionstart-agy.sh, bin/fm-turnend-guard-agy.sh, PreToolUse --agy seatbelt flags, session-lock agy ancestry, autoarm supervision model, and --secondmate agy workspace trust pre-registration and spawn support.

* no-mistakes(review): Fix agy Stop-hook park, hooks.json shape, and live coverage

* no-mistakes(review): Unbound agy Stop park, raise ceiling, prove live deny

* no-mistakes(review): Correct agy verification doc park-bound wording

* no-mistakes(document): Document agy as verified primary and secondmate harness

* no-mistakes(ci): I fixed all three selected findings, and every check I ran passed, including the live agy end-to-end run. **ci-1 (`tests/fm-agy-primary-live-e2e.test.sh`):** The invariant is that the live Stop-hook test passes only if a real watcher starts and its wake reaches a follow-up turn. The old test passed as soon as `.agy-park-owner` existed. I replaced the Stop-hook park block with the one the user specified. It waits until both `.agy-park-owner` and `.last-watcher-beat` exist, wakes the watcher with a `done:` status line, and asserts that the park owner was recorded, the watcher started, and `DONE` appears in the agy output. **ci-2 (agy away daemon):** The invariant is that `/afk` must not launch a separate away daemon on any primary whose home runs the supervision host. The agy Stop-hook guard already runs the host when it is enabled, but `fm_afk_launch_host_primary` left agy out. I added `agy` there, which is the one shared check all three callers use. I also added agy to: - the header comment in `bin/fm-afk-launch.sh`; - the three harness loops and the pass message in `tests/fm-afk-launch.test.sh`; - the primary lists and counts in `docs/supervision-host.md`, the matching lines in its engine-selection section, and a new Antigravity (`agy`) row in its Arm owners table; - the header comment in `bin/fm-supervision-instructions.sh`. **user-1 (`.agents/hooks.json`):** The invariant is that each hook command stays one script under Windows `cmd /c` and exits 0 when `sh` is missing. All 5 commands now use `sh -c "..." || cd .`. This does not change behaviour on Linux or macOS, because the `--agy` hooks report deny or continue as JSON on stdout and exit 0. The file keeps its live-verified `{"firstmate":{...}}` shape, matchers and 28800s Stop timeout. **Verification:** - `tests/fm-agy-primary.test.sh` passes, including running the SessionStart hook command from both `.agents/` and the repo root. - `tests/fm-afk-launch.test.sh` has no failures, and the new agy check passes. Its rex end-to-end cases were skipped because the rex CLI is not installed. - `tests/fm-supervision-instructions.test.sh` has no failures. - `bin/fm-lint.sh` and `bin/fm-doc-audience-check.sh` pass. - `FM_AGY_PRIMARY_LIVE=1 tests/fm-agy-primary-live-e2e.test.sh` printed all four `ok` lines and no failures, including "Stop hook parks on a real watcher and delivers its wake to a follow-up turn". The output went through `tail`, so the exit code shown is `tail`'s, not the test script's

* feat(bin): add shared_quota opt-out from quota-based dispatch ranking (#7894)

* feat(dispatch): add shared_quota home opt-out from quota-based ranking

A home whose Claude and other provider usage draws on one combined AI
budget has no meaningful per-provider quota rows, so spendPriority
ranking and runway gates pick the wrong candidate. An optional
top-level "shared_quota": true in config/crew-dispatch.json now opts
the home out: the typed resolver makes no quota-axi call, applies no
quota floor or runway gate, ranks nothing by spendPriority, and
resolves the matched rule's use profiles in declared order, printing
every candidate line with quota ranking off by home declaration.
Firstmate's quota-array-dispatch intake honors the same declaration.
Without the setting, behavior is unchanged. Non-boolean values are
actionable configuration errors in both the resolver and bootstrap.

* test(dispatch): cover shared-quota bypass of unmet rule and profile floors

The shared_quota opt-out test picked a rule with no quota floor, so the
separate rule-floor and profile-floor bypass paths stayed untested.
Two cases now run against the same fixture: a rule whose model:fable
floor (20%) exceeds the snapshot's 15%, and a profile whose all_models
floor (50%) exceeds codex's 31%, each asserting the declared-order pick
still wins with no quota-axi invocation.

* no-mistakes(review): Narrow shared-quota skill opt-out to quota-only gates

* no-mistakes(review): Document preferred_provider under shared_quota opt-out and test it

* no-mistakes(document): Document shared_quota in schema example and verification inventory

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup (#7958)

* fix(bin): distinguish recycled reaper PIDs in tombstone cleanup

* no-mistakes(ci): ci-2 fixed in tests/fm-watcher-lock.test.sh (test_lock_tombstone_tracks_reaper_start_time). Invariant: no fixture child may outlive a SIGKILLed runner without a bound. (1) The paused reaper's wait loop now also stops when FM_TEST_SUITE_PID is no longer alive or when SECONDS reaches FM_TEST_STUB_MAX_BLOCK_SECONDS. (2) The one sibling child in the same test, the unrelated `sleep 300`, now sleeps for FM_TEST_STUB_MAX_BLOCK_SECONDS so it uses the same bound. Verification, run serially: bash tests/fm-watcher-lock.test.sh. The new test passed on 4 of 4 runs. Red-before still holds: with the base bin/fm-wake-lib.sh from c9da5523, the test fails with 'not ok - recycled reaper pid kept an abandoned tombstone alive'. Separately, the known stand-down flake ('the replaced watcher did not stand down on its own', watch-legacy-local-time-identity) failed on every run on this host and also fails on base c9da5523 without this change, so the test file still exits 1; left unfixed as instructed. ci-1 (Full suite waiting on the full-ci maintainer label) was ignored per the user's decision

* feat(bin): allow omp as a remote secondmate harness (#7939)

* feat: allow omp as a remote secondmate harness

* test: cover omp on the remote secondmate gates

* fix: retire a remote secondmate whose busy state left with its home

* docs: record omp remote retirement evidence

* review: Refresh pinned remote doctor bootstrap checksum

* fix(bin): name a consumed branch grant instead of a wiring bug (#7969)

* fix(bin): name a consumed branch grant instead of a wiring bug

When a supervision branch's own acknowledgement consumes every granted
row, the drain removes the branch-eligible row snapshot while the owner
record stays live. A repeat drain or acknowledgement in the same turn then
refused with a message implying a broken handoff. Say instead that the
grant was already consumed; the refusal and its exit status are unchanged.

* no-mistakes(document): Document consumed-grant refusal in watcher continuity doc

---------

Co-authored-by: c-c6aw <[email protected]>

* fix: preserve literal ampersands in spawn and supervision paths (#7906)

* feat(bin): read dispatch provider keys from a declared credential source (#5409)

* feat(dispatch): read Typesafe key from Keychain

* no-mistakes(review): Share Keychain key lookup with bootstrap; hard-code service name

* no-mistakes(review): Use one readable-secret Keychain check for bootstrap and resolver

* no-mistakes(document): Point AGENTS key row to owner; record Keychain bootstrap evidence

* feat(dispatch): read provider keys from a declared credential source

bin/fm-dispatch-resolve.sh took the typesafe.ai and OpenRouter keys only
from the environment or $FM_HOME/.env, so a home that keeps its key in the
macOS Keychain needed a wrapper to supply it, and the documented direct
call reported off.

Let the resolver consume an optional, provider-keyed declaration in the
effective config directory, config/dispatch-credential-sources.json. It
names where a key lives and never holds one. macos-keychain is the first
adapter (service, optional account), kept behind a small schema and adapter
registry in bin/fm-credential-source-lib.sh so the shared surface binds to
no one OS or provider.

- Precedence is the environment, then .env, then the declared source, which
  is read only when neither supplied a key and only for the selected
  provider.
- No entry and no key stays off, exactly as before. An unreadable or
  invalid declaration exits 2 with a line that names the problem and never
  a declared value.
- A declared source that this host cannot run, that yields no key, or that
  does not answer within FM_CREDENTIAL_SOURCE_TIMEOUT ends as a structured
  error outcome with nothing sent, so it is not mistaken for an
  unconfigured resolver.
- The key is captured into the same private variable as before and still
  reaches curl only as an fd 3 header. The adapter puts only the service
  and account on argv and discards the tool's stderr.
- --supports-credential-source <source> answers supported or unsupported
  without reading a declaration or running the credential tool, so an
  installer can refuse an unsupported activation before it writes anything.

The resolver tests cover the mapping, effective-home and provider
isolation, precedence, the three failure kinds, and secret containment
with a stubbed security and uname.

Closes #7879

* no-mistakes(review): Gate bootstrap typed checks on declared source; fix timeout

* no-mistakes(review): Document storing the declared Keychain item without access dialog

* no-mistakes(document): Clarify that only a typesafe declaration keeps resolver on

* no-mistakes(document): Merge dispatch key-source precedence into one configuration sentence

---------

Co-authored-by: Kun Chen <[email protected]>

* fix: clean up remote reply temporary files and locks on exit (#6489)

* fix(bin): clean remote reply temp paths on every exit

The remote reply adapter left its temporary staging directory and fetch files behind on several exit paths.
The ingest staging directory leaked on the continuity-broken return, whose EXIT trap fired after its local tmp left scope.
The trap cmd_ingest installed also replaced the lifecycle-lock release of the handle subshell.
One EXIT trap now owns every temporary path, each lock subshell runs it before releasing its lock, and the empty hash no longer stages a file.
A test under a private TMPDIR covers the continuity return, a die after staging, a locked handle, and a signal during a document fetch.

* no-mistakes(document): Document remote-reply temporary-file cleanup

* no-mistakes(ci): Fixed ci-1 in tests/fm-remote-reply.test.sh: interrupt the blocked SSH child before waiting, fail if it already exited, and require adapter exit status 143 before checking cleanup. Confirmed the strengthened test rejects an adapter that ignores TERM; the temporary mutation was restored. The full remote-reply suite passed on a serial rerun, and syntax, pinned ShellCheck, and diff checks passed. One earlier run alongside lint timed out waiting for the third reply generation

* fix(bin): clean up the staged source-read output on every exit path

The source leg stages the remote read's output in a temporary file. Track it
with the adapter's other temporary paths so a signal during the read removes
it, and extend the regression test and docs to cover that path.

* chore: ignore Claude Code per-user settings (#6482)

* chore: gitignore Claude Code's per-user local settings file

* no-mistakes(ci): Addressed ci-1 by preserving the staged --no-index correction for both Claude settings assertions in tests/fm-gitignore-config.test.sh, making ignore-rule checks independent of tracking state. Reproduced the original false pass with tracked shared settings and an overly broad .claude/ rule; the corrected test rejects it. Verified normal tracked/untracked settings cases and rejection of a missing local-settings ignore rule. Targeted test runner, pinned ShellCheck, Bash syntax check, and diff checks all passed. No unrelated changes were made

* fix: prefilter inbox history for idempotent remote steering (#7905)

* fix(inbox): prefilter idempotent steering history

* no-mistakes(document): Clarify delivery mode in steering retry contract

* test(inbox): cover acknowledgement before prefilter opens

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter (port of #7956) (#7979)

* feat(bin): add Kiro CLI as a crewmate/scout harness adapter

Port of #7956 onto current main so it gets a fresh CI run.

Adds a `kiro` (Kiro CLI, V2 engine) harness adapter, crewmate/scout only
(--secondmate launches are refused). fm-harness.sh detects it by kiro-cli
ancestry; fm-spawn.sh launches it with a per-task KIRO_HOME under
state/<id>.kiro-home (generated userPromptSubmit and stop hooks plus
chat.disableTrustAllConfirmation); busy, control, send, watch, procevent,
teardown and bootstrap wiring recognise it. Composer ghost-text and busy
footer matching is scoped to FM_COMPOSER_HARNESS=kiro, so other harnesses
read exactly as before. Adds references/harness/kiro.md,
docs/verification/kiro.md, tests/fm-kiro-harness.test.sh and an opt-in
live e2e signals guard.

Conflicts with main were resolved by keeping main's agy promotion and
adding kiro to the crewmate-only lists next to it.

Co-authored-by: kiatng <[email protected]>
Co-authored-by: Marsjohn-11 <[email protected]>

* fix(send): detect kiro on meta-less explicit targets

An explicit session:window send has no task meta, so TARGET_HARNESS stayed
empty and the kiro composer rules never applied. A finished kiro idle
placeholder then read as pending, extra Enters were pressed, and fm-send
exited 3 even though kiro accepted the message.

Resolve kiro from the live pane's foreground process group when meta is
absent, and keep every other explicit-target send on the unknown-harness
path. Move the kiro live e2e version probe to after the live gate so an
opted-out run never starts kiro-cli.

Co-authored-by: Kun Chen <[email protected]>

---------

Co-authored-by: kiatng <[email protected]>
Co-authored-by: Marsjohn-11 <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Kun Chen <[email protected]>

* fix(bin): publish hold origins only after backend success (#6777)

* fix(captain-hold): refuse a previous origin's answer after an incomplete hold move

A hold moved to a new origin wrote its stamp and origin before the backend
hold. A process stopped between those writes, or a refused hold whose rollback
also failed, left the task associated with the new origin while it carried
only the earlier call's answer, and complete and verify accepted that answer.

Verification now treats an open, unheld task that leads with a hold-set stamp
above a recorded answer as a re-hold that never completed, so the answer no
longer satisfies the new origin however the move was interrupted. A refused
hold also restores the body the attempt started from, and the origin lookup
runs before any write, so a clean failure leaves the earlier answer valid.

Closes #6461

* no-mistakes(review): Publish hold origins only after backend success

* no-mistakes(review): Publish verified holds before origin writes

* no-mistakes(document): Clarify hold-origin durability documentation and regression coverage

* no-mistakes(lint): Quote done subcommand to resolve ShellCheck warning

* no-mistakes(document): Clarify recorded-origin provenance guarantees

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend (#7963)

* feat(backends): add experimental explicit-only hc (herdr-core) runtime backend

herdr-core is the terminal core under Herdr.app and is not Herdr 1.
The adapter follows the tmux shape: one login-shell terminal per task,
Treehouse keeps the worktree, and fm-spawn drives it through the same
send/current-path primitives.

- bin/backends/hc.sh: create, capture, visible capture, send line, typed
  literal through hc keys, named keys, current path, composer state,
  submit, native busy state, recovery agent state from the foreground
  process and its process group, and a close that proves the terminal gone.
  Targets are <session>:<address>; every call pins that HC_SESSION, and an
  empty session never reaches hc. Task and home labels gate input and close.
- bin/fm-backend.sh, bin/fm-spawn.sh: hc arms, explicit-only selection,
  endpoint validation, hc_session/hc_terminal metadata, secondmate refusal.
- tests: fake-CLI suite and a real-hc smoke test on a private core.
- docs: hc-backend.md, configuration, verification record, README links.

* fix(hc): submit the spawn launch line by paste and add the hc liveness live guard

The launch line always carries a + that hc keys cannot type, so fm-spawn
pastes it with hc send and consumes the Enter that follows. The launch
environment floor keeps HC_SESSION, HC_TERMINAL_ID, HC_TERMINAL_SOCKET and
HC_SCOPE. tests/fm-backend-hc-liveness-live-e2e.test.sh launches every
installed harness bare in a private core and requires alive. The
verification record gains the end-to-end spawn, steer, peek and teardown run.

* no-mistakes(review): Allow hc interrupt keys and drop unused hc send_literal

* no-mistakes(document): Sync hc backend inventories and adapter header comment

* no-mistakes(ci): Fixed. When an hc task was torn down, the kill function read the task's expected label from the wrong argument, so it ended up accepting any terminal in the same home and could close another task's worker. - Invariant: every hc close must be gated by the task label that teardown passes as the third argument to fm_backend_kill. - Where it must hold: fm-teardown.sh calls `fm_backend_kill <backend> <target> <zellij_tab_id> fm-<id>` at all its sites (around lines 3482, 3491, 3494, 3876, 3986 and 3995). The dispatcher at bin/fm-backend.sh:1156 passes "$@" through to fm_backend_hc_kill, and that function is the only hc close path. So fixing that one function's arguments covers every teardown site. - Fix in bin/backends/hc.sh:279: the signature is now `<target> [unused] [expected-label]` and it reads `expected=${3:-'*'}`, the same shape tern, rex, cmux and paseo use. The label value matches what hc terminals carry: spawn creates them with firstmate.task=$W where W="fm-$ID" (bin/fm-spawn.sh:4545 and 4955), and teardown passes "fm-$ID". - New test in tests/fm-backend-hc.test.sh, test_kill_refuses_another_tasks_terminal, goes through the public fm_backend_kill path. A terminal labeled fm-other is refused for expected label fm-a1, stays alive and gets no `hc kill`. The terminal labeled fm-a1 is closed and removed. Before the fix the test failed ("expected a refusal"), and after it the whole suite passes. - Checks: `bash tests/fm-backend-hc.test.sh` passes every test and `shellcheck -x` is clean on both files. The live smoke and e2e hc tests call kill without a label, which keeps the existing behavior of accepting any task label from this home. I did not run them because they need a real herdr-core. VERIFIED with the unit tests on the fake hc CLI, not against a real hc core

* fix(hc): keep the live liveness guard from repointing the operator's claude

A real claude started under the guard's scratch XDG_DATA_HOME can self-update into it and repoint ~/.local/bin/claude there, leaving the link dangling once the scratch directory is removed.
Export DISABLE_AUTOUPDATER=1, as bin/fm-live-lab.sh already does for its live harnesses.

* fix(hc): drop an inherited HC_SOCKET so the session pin holds

* no-mistakes(document): Document hc dropping inherited HC_SOCKET for session pin

* no-mistakes(ci): I fixed both Greptile findings. The hc unit suite passes all 12 tests, three runs in a row, and `shellcheck -x` is clean on the 4 touched files. VERIFIED with unit tests (a fake hc CLI plus a real process group). NOT VERIFIED against a real hc core, because the live tests need herdr-core. ci-1, live tests could stop an unrelated core - Invariant: every direct `hc` call a test makes must reach only its private scratch core, so an inherited HC_SOCKET (which wins over HC_SESSION in hc 0.1.14) must never be set. - Where it must hold: the two suites that call `hc` directly (`hc server status` at startup and `hc server stop` in cleanup), `tests/fm-backend-hc-liveness-live-e2e.test.sh` and `tests/fm-backend-hc-smoke.test.sh`. Adapter calls already go through `fm_backend_hc_cli`, which drops HC_SOCKET. - Fix: both suites add HC_SOCKET to the `unset HC_TERMINAL_ID HC_TERMINAL_SOCKET HC_SCOPE` line, before any `hc` call. ci-2, a shell wrapper running a live worker was reported as dead - Invariant: `fm_backend_hc_agent_state` may return `dead` only when neither the foreground process nor anything else in its process group is a harness. - Where it must hold: there is one classification path, `bin/backends/hc.sh` around line 326. Before the fix, the `shell` branch returned `dead` before the process-group check ran. Callers such as the inbox ring and the watcher read this value through `fm_backend_agent_state`, so fixing this one function covers all of them. - Fix: the result is now `alive` when the foreground process is a harness. Otherwise the process group is checked, which can also give `alive`. After that a shell gives `dead` and anything else gives `ambiguous`. An idle shell, whose group holds no harness, is still `dead`, and the existing test_agent_state_classifies_foreground_and_absence still passes (`t2=dead`). - New test `test_agent_state_reads_a_shell_wrappers_group` in `tests/fm-backend-hc.test.sh`. It starts a real `bash` wrapper in its own process group with a child that runs as `claude`, and points the fake hc terminal's foreground at the wrapper. With the old code the test fails ("expected 'dead', got 'alive'"). With the fix it passes. The comment in the code was updated. `docs/hc-backend.md` already describes the process-group read, so it did not need a change. Not run: `fm-backend-hc-smoke.test.sh` and `fm-backend-hc-liveness-live-e2e.test.sh`, because they need a real hc core

* fix: refresh Herdr upstream references and licensing (#8000)

* docs(herdr): record the Apache-2.0 relicense and herdrdev org rename

Herdr relicensed from AGPL-3.0-or-later to Apache-2.0 in 0.8.0 and the
GitHub organization moved ogulcancelik/herdr to herdrdev/herdr. The old
release URLs redirect to the same assets, so the CI installer and the
version-floor guard now fetch via the canonical org with the pinned
version and checksums unchanged; verified end to end by running the
installer against the new URL.

* no-mistakes(document): Clarify Herdr product boundaries and preserve historical evidence

* fix(pi): stop repeated numbered and byte excerpt reads (#7992)

Fixes #7990

* fix(bin): keep the PR merge watch working when a worker with a PR is relaunched (#7996)

* Preserve PR poll authentication on relaunch

* no-mistakes(review): Keep trace and polytoken meta ahead of PR lines

* test: pin lock staleness in malformed presentation lock wake-queue case (#7837)

* fix(tests): pin lock staleness in malformed presentation lock case

A plain-file presentation lock older than FM_LOCK_STALE_AFTER (default 2s) is reclaimed as garbage, so a slow runner could age the malformed-lock fixture into a successful acquire. Pin the staleness window far above the case runtime so the case is deterministic.

* test(wake-queue): correct the malformed presentation lock staleness comment

---------

Co-authored-by: Trillium Smith <[email protected]>

* feat(bin): add configurable self-update source for /updatefirstmate (#5603)

* feat(bin): let /updatefirstmate follow a configured self-update source

An optional local config/self-update-source ("<remote> <branch>") makes
fm-update.sh fast-forward the primary from that one remote branch instead of
origin/<default>, under the same fast-forward-only guards, and makes local
secondmates advance to the primary's resulting commit (a standalone clone
imports it from the primary first). A home can then run its own fixes from a
branch that carries them on top of upstream, while worker spawns, review
diffs, the cleanup landed-work test, lint and default-branch detection keep
using origin, so new contributions still branch from upstream.

Absent, behaviour is unchanged. An unreadable or malformed file, an unknown
remote or an invalid branch name refuses the whole update before anything
moves rather than falling back to origin. A remote secondmate's host follows
its own code root's config, which the docs record as the limit.

* no-mistakes(document): List config/self-update-source in AGENTS.md config inventory

* no-mistakes(document): Mention self-update source in updatefirstmate skill description

* fix: bound watcher auto-arm failures and recover interrupted locks (#8018)

* fix(bin): commit the attended alarm from the exhausted Stop auto-arm

A Claude failure episode could suppress indefinitely without ever raising
the attended alarm. On every Stop cycle the auto-arm opens its generation
claim before the guard's sync-wait decision, so the guard always steps
aside; terminal_fail_open is never reached and no participant knew that
automatic continuation was exhausted. The block budget still climbed
because the guard's step-aside path accounts for the epoch, so Stops kept
rewaking with empty failed-suppressed bodies forever.

The auto-arm is the only participant that knows its own continuation is
exhausted, so it now owns the terminal escalation: once the failure
notice was consumed and the session block budget is over, the terminal
failure path commits .claude-autoarm-failure-alarmed and the
failed-suppressed outcome inside the owner lock (owner then budget, the
same order the guard's writer uses), then emits one loud final rewake
telling the operator to keep the session attended and diagnose the
Stop-hook supervision. A healthy watcher verified inside that hold resets
the episode instead of alarming, and a refused commit stays suppressed
without a false alarm.

Later Stops in the same episode see the alarm, record failed-suppressed,
and exit 0 so no further continuation or alarm is produced. Positive
watcher recovery still clears the notice, the alarm, and the budget.

Every failed-suppressed commit now carries a one-line stderr reason
naming why the operator notice is not repeated and whether the
Stop-owned retry stays alive, replacing the silent empty bodies that
made suppressed Stops indistinguishable from a wedged hook.

Adds an integrated guard/auto-arm regression driving both hooks through
the exhaustion boundary and asserting the single alarm, post-alarm
suppression, and clean recovery; updates existing tests for the reasoned
suppression contract.

* fix(bin): outlast an unpublished lock pid for one freshness window

CI run 40805704864 ("recovery drain after forced arm interruption")
failed because a dying watcher could not publish .watcher-down inside
its bounded cleanup window, so the drain saw no downtime marker to ack.

The blocker was an empty-pid lock artifact: fm_lock_claim and the
bounded-wait handoff published ownerdir/pid with a truncating write,
and a creator killed mid-write (the bounded handoff helper runs under
timeout -k with a process-group KILL) left a resolvable symlink whose
pid file stayed empty forever. fm_lock_try_acquire treats that as a
fresh mid-acquire hold for a full freshness window, cannot steal it,
and a bounded waiter whose bound equals the window gave up before the
evidence expired.

Two changes. First, both pid writes now go through a same-directory
pid.tmp file renamed into place, so a killed write can no longer leave
a live lock with a permanently empty pid; fm_lock_clean_known_files
sweeps leftover tmp files. Second, fm_lock_acquire_wait_max polls one
extra freshness window when the remaining blocker still has no
published pid, so a waiter outlives the residue instead of failing at
its bound; the moment a pid publishes or the artifact goes stale the
ordinary live-holder and steal rules apply unchanged, and published
live holders keep the original bound.

Adds a regression test that links an owner dir with no pid and asserts
the bounded wait outlasts the freshness window to reclaim it, while a
live holder still fails at the nominal bound; verified to fail against
the pre-change implementation.

* no-mistakes(review): Route every suppressed exit through alarm decision

* no-mistakes(document): Clarify exhaustion and lock-wait documentation

* no-mistakes(lint): Quote empty grace deadline assignment for ShellCheck

* no-mistakes(ci): Fixed tests/fm-x-mode.test.sh: atomic lock-pid publication consumed its overly broad injected mv failure. Targeted the counter-record destination and asserted injection occurred. Reproduced failure before fix; full X-mode test script, pinned lint, bash syntax, and diff checks pass afterward. Full suite failure is downstream of this lane failure; no separate fix needed

* no-mistakes(ci): Fixed Full suite’s underlying shard timeout: the PR marker test’s broad mv failure injection blocked atomic lock-PID publication indefinitely. Restricted injection to the marker destination. Reproduced the hang before fixing; targeted regression, all 49 PR-security tests, ShellCheck, bash syntax, and diff checks pass

* no-mistakes(ci): Fixed load-sensitive remote lifecycle test timeout: all three inheritance/launch barrier waits now honor the existing convergence budget instead of failing after 30 seconds. Full suite failure is downstream of this shard. Full lifecycle E2E, Bash syntax, ShellCheck excluding SC1091, and diff checks pass. Production behavior unchanged

* no-mistakes(ci): Fixed remote-reply fixture races, preserved the committing auto-arm’s final rewake on signals, and asserted the live-holder wait bound. Remote-reply and turnend-guard suites and focused lock test pass; signal regression fails before fix and passes after. Full watcher-lock suite fails earlier in an unchanged macOS watcher-replacement test. Full suite CI failure is downstream of the shard failure

* no-mistakes(ci): Fixed teardown race in tests/fm-watch-arm.test.sh: atomically rename state/home/root fixtures away before deleting contents after process exit. Preserved all existing assertions; production code unchanged. Affected suite passed three runs, including two concurrent copies; targeted unpublished-PID lock test and syntax/diff checks passed. Additional full lock suite failed twice at a separate watcher-replacement exit assertion. Standalone ShellCheck reported existing warnings

* fix(bin): cut stat forks in the wake drain by reading identity and size together (#6271)

Local cherry-pick of https://github.com/kunchenguid/firstmate/pull/6271 pending upstream merge.

* fix(bin): keep pr= merge-poll identity last when recording captain-hold completion (#6732)

* fix(bin): keep PR merge polls authenticated across relaunch

A relaunch rewrote the task record with control_relaunch_tx after the
preserved pr= line. fm_pr_metadata_identity_parse rejects any key after
pr= other than pr_head= and x_*, so the watcher stopped authenticating
the armed merge poll and reported it as an unauthenticated state check,
and the merged-PR wake never arrived. Write the transaction id before
the preserved lines, as fm-remote-secondmate-relaunch.sh already does.

* no-mistakes(review): Keep pr= last for traceparent and completion writes

* no-mistakes(document): Note completion record placement ahead of pr= lines

* no-mistakes(ci): Fixed the Greptile P1 finding (ci-1) as the user decided. **Invariant:** a task's `.meta` record holds exactly one `decisions_reviewed`/`decision_keys` pair, and it sits before `pr=`. Then `meta_value` (which reads the last match) returns the current inventory, and `fm_pr_metadata_identity_parse` still sees `pr=` last. The only place that writes this pair is the awk rewrite in `command_complete` (`bin/fm-captain-hold.sh`). The other hits for these keys under `bin/` are only a comment and an error message. `verify` and later `complete` calls read the pair through `meta_value`, so fixing this one writer fixes them too. **Fix:** added one awk rule, `/^(decisions_reviewed|decision_keys)=/ { next }`. It removes every existing occurrence of both keys, in either the old layout (pair after `pr=`) or the new one, before the single updated pair is written ahead of `pr=` (or at the end if there is no `pr=`). When there is no existing pair the output is the same as before, so the normal path is unaffected. **Regression test:** added `test_completion_replaces_a_pair_recorded_after_pr` to `tests/fm-captain-hold-lifecycle.test.sh` and registered it in the runner list. It builds a record in the old layout (`pr=` followed by `decisions_reviewed=1` / `decision_keys=old-call`), then runs `complete <id> new-call`. It checks that exactly one `decision_keys=new-call,old-call` line and one `decisions_reviewed` line remain, that `verify` passes, and that `fm_pr_metadata_identity_parse` still accepts the PR identity. **Verification:** - The full `tests/fm-captain-hold-lifecycle.test.sh` suite passes with the fix (exit code 0, every result `ok`), including the new test. Some tests were skipped because this environment has a markdown-only tasks-axi. - I meant to also run the suite with the fix removed, but both attempts to take the line out left the file unchanged, so that run also tested the fixed code. The new test has not been shown to fail without the fix. - Instead I ran the old and new awk programs directly on an old-layout record. The old program leaves `decision_keys=old` after `pr=`, so the last match is the stale inventory and `pr=` is no longer last. The new program writes a single `decision_keys=new,old` before `pr=`. - The worktree file has the fix (the diff shows the added awk line)

* no-mistakes(ci): The branch is rebased onto base dbcb5abb and the rebase completed cleanly. All 4 commits applied, and the only remaining change is one staged, uncommitted file (listed below). **Why it conflicted:** upstream #7996 had already landed the same relaunch fix. It writes `control_relaunch_tx` before the preserved `pr=` lines, and its shared helper `spawn_meta_rewrite_before_pr` keeps the traceparent write ahead of `pr=`. **Invariant:** an armed `pr=` block must stay last in `<id>.meta`, because `fm_pr_metadata_identity_parse` rejects any key after it. Three writers must respect this. Upstream now covers two: the relaunch rewrite and the traceparent write, both in `bin/fm-spawn.sh`. The branch still covers the third: the completion write in `bin/fm-captain-hold.sh`, which removes any older copies of the completion fields and writes them once, before `pr=`. **How the conflicts were resolved:** 1. **Relaunch reorder in `bin/fm-spawn.sh`:** the code was already identical upstream. The branch keeps only its two-line comment explaining why the preserved lines go last. 2. **Traceparent write in `bin/fm-spawn.sh`:** I took upstream's helper version of `spawn_record_traceparent` and dropped the branch's inline awk, which did the same thing. 3. **`tests/fm-control-relaunch.test.sh`:** I restored it to the base version. This change is staged but not committed yet. - Upstream's `test_relaunch_preserves_durable_task_metadata` already covers an untraced relaunch with an armed poll. - Upstream's `test_traced_relaunch_keeps_an_armed_pr_poll_authenticated` covers the traced case. - The branch's version redefined that traced test, so upstream's would have been silently replaced and run twice. **Net diff against base:** - The completion-write fix in `bin/fm-captain-hold.sh`. - Its regression tests in `tests/fm-captain-hold-lifecycle.test.sh`. - A one-line note in `docs/captain-hold-lifecycle.md`. - The comment in `bin/fm-spawn.sh`. **Checks:** - `bash -n` passes on `bin/fm-spawn.sh` and `bin/fm-captain-hold.sh`. - `tests/fm-control-relaunch.test.sh` exits 0, including upstream's armed-poll and traced-relaunch PR poll tests. - `tests/fm-captain-hold-lifecycle.test.sh` exits 0, including the test that a completion record written after `pr=` by the old code gets replaced. No file-mode or authentication check was changed

* no-mistakes(document): Clarify completion pair replacement ahead of pr= lines

* fix: explain how to recover missing worktree identity (#8027)

Last-resort port of #7575. Keep main's fm_backend_endpoint_u64_valid and
the PR's fm_backend_worktree_identity_repair_hint, with the existing
validate_task_endpoint call site.

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: thelad-dev <[email protected]>
Co-authored-by: Kun Chen <[email protected]>

* fix: prevent watcher startup interruptions from cascading stale locks (#8025)

* fix(bin): bound watcher startup locks and defer arm TERM to the safe point

Under host CPU/fork contention a fresh watcher could outrun the arm's
fixed confirmation budget, so the timeout TERM landed before the child
installed its EXIT cleanup trap. The killed startup left .watch.lock
and micro-locks recorded against a dead pid, and each next arm
inherited a slower stale-lock walk - a cascade that made loaded hosts
progressively less able to keep a watcher armed.

The watcher now installs watcher_cleanup immediately after claiming the
singleton and publishes its home-bound lock identity (fm-home,
watcher-path, pid-identity) right after, so an interruption past that
point can only abandon locks recorded against the watcher's own pid;
the cleanup releases those outright before its bounded downtime
publication, so a stop taken inside a marker or queue critical section
cannot self-block or strand the singleton.

Every pre-identity lock the watcher takes is bounded by
FM_WATCHER_STARTUP_LOCK_BOUND (default 60s): the steal's downtime
publish, the recovery reopen and arm-check transitions, and the
successor's queued-row check. A bound spent against a live foreign
holder ends the child with the typed line
`watcher: FAILED - startup lock <path> held by live pid <n>`, which the
arm relays; a dying or clearing holder retries instead.

The arm's confirmation is now a liveness backstop rather than a fork
budget: FM_ARM_CONFIRM_TIMEOUT defaults to FM_GUARD_GRACE and never
drops below the legacy 10s/30s-on-MSYS floor, so host load stretches
how long the arm waits instead of how soon it kills. Signal forwarding
and the deadline TERM share one safe-point helper that waits for the
child's published lock identity; a child still mid-claim at the
deadline is killed outright and its dirs reap as ordinary dead
evidence. The already-live successor handoff keeps its own short bound,
FM_ARM_SUCCESSOR_CONFIRM_TIMEOUT (10s, 30 on MSYS), which the Stop
auto-arm now also uses for its successor status wait.

The state-directory teardown check is fixed for macOS, where devfs
serves each /dev/fd entry on its own device so -ef never matched and a
missing lock pid alone read as a torn-down state directory; the poll
now compares the held directory's recorded device+inode.

Regression tests cover a post-claim startup slower than the legacy
budget confirming under the grace-tracked backstop, a live foreign
startup-lock holder ending the child with the relayed typed line while
keeping downtime drainable, and a stop forced before the safe point
leaving no dead lock evidence a re-arm cannot reclaim.

* no-mistakes(review): Invalidate inherited watcher beacon at singleton claim

* no-mistakes(review): Defer deadline TERM to startup safe point, leave no locks

* no-mistakes(review): Exit watcher startup if identity cannot publish

* no-mistakes(test): Clean interrupted watcher lock-owner staging

* no-mistakes(test): Join in-flight lock mutations before watcher cleanup

* no-mistakes(document): Correct startup deadline documentation

* no-mistakes(ci): Fixed both attached-arm tests to configure the independent successor timeout, and quoted both escalation tokens flagged by ShellCheck. Full suite failure is downstream of failed lanes. Both focused behavioral tests, direct ShellCheck, bash syntax, and diff checks pass. Broader verification was limited by an earlier concurrency-test failure and timeouts in canonical lint and pending-reply tests

* no-mistakes(review): Read successor queue state inside arm-check hold

* no-mistakes(document): Clarify startup lock bound scope

* no-mistakes(ci): Fixed dead-watcher reclamation to exit with a typed watcher: FAILED diagnostic naming the downtime marker when publication fails, preserving bounded live-pid contention. Added a deterministic directory-marker regression that reproduced the pre-fix hang and now passes. Shell syntax, five focused behavioral tests, and git diff --check passed

* fix(bin): allow cd to the home itself and add --help to fm-pr-merge.sh (#8021)

* fix(bin): allow cd to the home itself and give fm-pr-merge.sh a --help

The cd-guard denied a top-level cd whose single literal absolute target
resolves to the primary checkout, although that cd cannot move the shell
out of the home. The transport now passes the checkout as --home and the
policy allows exactly that target after realpath resolution on both sides.
Every other cd, pushd, and popd keeps its deny, including a child, sibling,
parent, relative, expanded, option-bearing, or glob target.

fm-pr-merge.sh refused -h and --help as an invalid merge request with exit
2. It now prints its header, which gained a usage block, and exits 0.

The issue's suggested test that runs every bin/fm-*.sh --help and expects
exit 0 is left out: a survey of the 222 scripts shows more than 50 fail
--help today (usage printed with exit 2, missing FM_HOME, argument parsing
that treats --help as a task or path), and two installer scripts start a
download on it, so that test is neither cheap nor stable. The new test
covers fm-pr-merge.sh alone.

Fixes https://github.com/kunchenguid/firstmate/issues/7995

* no-mistakes(ci): The guard now allows a home `cd` only when the target resolves to the home under both rules. The logical rule uses `fs.realpathSync`, which collapses `..` first. The physical rule uses `fs.realpathSync.native`, which follows symlinks per component, as `set -P` does. If either resolution fails, the guard denies. I changed `bin/fm-cd-command-policy.mjs` and updated its header comment and the home-exemption paragraph in `docs/cd-guard.md`. I added H16 to `tests/fm-cd-pretool-check.test.sh`. It puts `escape-link` inside the primary fixture, pointing outside it, and expects `cd <primary>/escape-link/..` to be denied. With the policy change stashed, H16 failed (it was allowed, exit 0). With the change applied, `tests/fm-cd-pretool-check.test.sh` has 0 failures, and H01-H07 still pass

* feat(pi): surface opted-in model-stream silence for Pi workers (#7212)

* feat(pi): record opt-in foreground stream activity

* feat(watch): inspect opt-in Pi stream silence

* test(pi): verify worker stream phases with the real SDK

* fix(review): harden Pi stream observation lifecycle

* fix(review): reject stale inspection before recovery publication

* no-mistakes(document): Clarify Pi stream observation and busy-age documentation

* no-mistakes(ci): Fixed both lint failures by explicitly discarding unused stream-record fields in fm-busy-event.sh and fm-watch.sh. Source-aware lint, normal lint, workflow/docs checks, and focused writer/watcher behavior tests passed. Behavior portable parallel 1 remains blocked by pre-existing TS2339 errors in two unchanged primary Pi extensions explicitly outside scope. Local type-check verification skipped because tsc is unavailable

* no-mistakes(test): Validation blocked by conflicting authentic Git metadata access requirements

* no-mistakes(test): Preserve gate identity in isolated Pi stream tests

* no-mistakes(document): Correct Pi stream close ordering documentation

* no-mistakes(ci): Captain, fixed S1 with an exact identity allowlist and SDK environment assertions. Corrected E1 by separating read-only launcher controls from writable output. Real Pi SDK, focused suites, CLI inspection, six race cases, and fallback checks passed. Signed Pi remains unavailable. Evidence: /home/art/.no-mistakes/evidence/01M4SVYM577RRP7SBS7M9Y8NFN/ci-S1-E1-0lj00bwx/output/REPORT.md

* test(pi): give each live stream case its own spawn world

The rebased base's fake tmux now records the window it created, so the three
live Pi cases that share one fakebin are refused as a duplicate window after
the first case. Give every case its own fakebin, like every other spawn suite
in this repository. No assertion changes.

* no-mistakes(document): Classify Pi stream-silence plan

* fix(pi): accept any Pi release at or above the stream floor

CI installs the latest published Pi, so the exact 1.2.0 gate disabled the
new instrumentation on 1.3.0 and the live guard failed instead of exercising
it. Move the version contract into the busy library as a floor, have spawn
and the real-SDK guard share it, and print the release actually verified.
The guard still exercises the installed SDK every run, and prerelease or
unreadable versions keep the gate closed behind the general busy bound.

* fix(test): restart a superseded remote-reply listener inside the bound

Handling a generation re-arms the source, which supersedes the live runner's
launch floor: that runner exits without a result. The wait sampled the owner
once, so a claim observed just before release suppressed the replacement and
the next generation waited out the full 40s bound with nothing listening.
Re-check the owner on a one-second cadence and start a replacement only while
nothing owns the source; the total bound and every assertion are unchanged.

* no-mistakes(review): Restore Pi verification boundary and fix terminal publication guards

* no-mistakes(review): Clear stream episode caps and fix uncapped test launch

* no-mistakes(lint): Fix ShellCheck single-iteration version loop

* no-mistakes(ci): Fixed the failing Pi stream-version regression: only verified Pi 1.2.0 is accepted; newer versions are checked as rejected, matching the production gate and the unverified-version requirement. `tests/fm-busy-state.test.sh` and `git diff --check` pass. The recorded request to accept newer versions conflicts with the verified-only invariant, so the test now reflects the verified-only behavior

* no-mistakes(review): Cover stream counter failures and clarify verified-version test

* no-mistakes(review): Isolate terminal publication fixtures from regular regression cases

* test(pi): make the live stream guard prove the unverified-version path

The live Pi guard passed on an unverified Pi version while checking nothing
about that version: the unverified case replaced the enabled/disabled/stalled
cases and the script still reported the verified-lifecycle pass line, so a
widened version gate or a dropped spawn warning would have gone unnoticed on
any host without Pi 1.2.0 installed.

The unverified case now asserts the load-bearing invariants instead: the exact
spawn warning text, that the generated worker extension registers none of the
model-stream handlers, and that the retained busy bound still works, which the
real-SDK run proves with state=busy and state=idle written by pi-ext while
stream evidence stays empty. The pass line names the behavior actually proved,
so an unverified host no longer reads as a verified one.

Verified by mutation: altering the warning wording fails with "missing exact
unverified-version warning", and forcing streamMonitoring on for an unverified
version fails with "unverified worker installed stream handlers".

Documentation states the same boundary in one place: stream observation stays
off on every unverified version until that version is verified, with a warning
and the general busy bound retained. The verification record gains the dated
Pi 1.4.0 run and its exact output for the inert path, alongside the existing
Pi 1.2.0 evidence for the verified path.

The version gate itself is unchanged and still accepts only Pi 1.2.0.

* test(pi): name the harness and version when the inert-path guard fails

The unverified-version assertions failed as bare "missing exact unverified-version warning" and "unverified worker installed stream handlers".
That is precisely the case where the harness and version are the diagnosis, because the guard only reaches those assertions on a Pi release the version gate has not verified.
Every other failure in the guard already names both.
Both messages now read "Pi <version>: ...", the final pass line branches on an explicit verified flag instead of comparing the case-list string, and the header states what an unverified host proves.
The version gate is unchanged and still accepts only Pi 1.2.0.
Verified on installed Pi 1.4.0 with Node v24.22.1: the guard passes with "ok - real Pi 1.4.0 unverified-version warning, inert stream observation, and existing busy/idle behavior".
Both mutations fail by name: rewriting the spawn warning yields "not ok - Pi 1.4.0: missing exact unverified-version warning", and forcing streamMonitoring on for an unverified version yields "not ok - Pi 1.4.0: unverified worker installed stream handlers".

* no-mistakes(document): Document Pi stream cap ordering and state files

* test(pi): name the version gate for what it checks

The gate accepts only the verified Pi release and rejects every other
version, so the old name (accepts verified and newer) described the
opposite of the assertion it holds.

* no-mistakes(document): Document Pi stream option must reach spawn and watcher

* no-mistakes(document): Document Pi stream revalidation, lib ownership, extension scope

* no-mistakes(document): Clarify Pi stream writer contract in header and prose

* feat(dispatch): bind a profile to an explicit quota_scope row (#8020)

* feat(dispatch): bind a profile to an explicit quota_scope row

Antigravity reports tier scopes (gemini, claude_gpt) that the resolver never matched,
so every agy candidate stayed unranked even when its tier was exhausted (#5602).
An optional profile quota_scope names the exact quota row to bind; profiles without
it resolve as before. Follows the explicit-declaration rule of #5319.

* no-mistakes(ci): Fixed ci-2: both quota_scope checks in bin/fm-dispatch-resolve.sh (use and default) now require an object entry before has("quota_scope"), so "use":["codex"] and "default":["codex"] get the malformed-profile error, not "not JSON". Added tests for both shapes. Fixed ci-3: the code already blocks a declared 0% row; added a test with 0% remaining and runway through_reset that asserts "not eligible" and no profile emitted. ci-1 needs no code change, because it is the maintainer full-ci label gate and nothing ran. The tests/fm-dispatch-resolve.test.sh suite fails here at an openai assertion, and it fails the same way without my changes (so likely environment-specific). With a non-fatal `fail` override in a temp copy, only the 7 openai assertions failed; the new quota_scope and malformed-profile cases passed. I did not run the mutation check on the ci-3 test

* fix(herdr): read pane foreground processes in one jq pass (#8029)

The watcher classifies every busy Herdr pane on every poll. Each sample ran
four jq processes per foreground process, and the "other" verdict resamples up
to ten times, so with a large fleet one stale-scan pass outran the 300-second
beacon grace and the watcher read as dead while it was still working.

fm_backend_herdr_pane_process_state_sample now validates the process-info
response and emits every process's pid, name, argv0 and args as NUL-separated
fields from a single jq call. Verdicts and field values are unchanged. The
stale scan already refreshes the beacon per window through beat.

Tests pin multi-process parsing, args with spaces and tabs, missing and
malformed fields, the shell verdict, and that jq calls do not grow with the
process count.

* fix(bin): refuse captain-hold release while the away record exists (#8028)

* fix(bin): refuse captain-hold release while the away record exists

`fm-captain-hold.sh answer --release` checked nothing about who answers,
so the away session could release a captain hold with its own words and
then steer the held work past the fm-send guard. A script cannot prove
the words are the captain's; this closes the unattended path instead.

While the away posture record (state/.afk-contract) or the away daemon
flag (state/.afk) reads away, `answer --release` and a `release` line on
the keyed-answer intake are refused before any write, naming the
attended-session requirement. A quiet record is a present captain and no
record is attended, so both still release. A closing answer without
--release is unchanged.

* no-mistakes(ci): Fixed the release race in bin/fm-captain-hold.sh: after taking the task control lock, answer --release takes the away-record lock (fm_afk_contract_lock_hold), rechecks posture under it, and holds it through the release write. The cleanup trap releases the lock. The keyed-answer intake reaches the same path through `answer --release`. Added test_release_rechecks_away_after_waiting_on_task_lock; it passes with the fix and goes red with the recheck removed. Only the three release tests were run, because the full lifecycle suite takes over 10 minutes here and was killed at the time limit. ci-1 (missing full-ci label) was declined, so no code change applies to it

* fix: harden herdr-core compatibility and message submission (#8037)

* feat(bin): add experimental herdr-core runtime backend

Herdr Core (the hc CLI, 0.1.x) is a separate product line from the
stable herdr TUI - persistent terminals in flat named sessions with
OSC 7501 status - so it gets its own adapter rather than changing
backend=herdr, which keeps driving the TUI unchanged.

The adapter maps the fm_backend_* contract onto hc: version/protocol
gates (hc x.y.z floor 0.1.14, hello generation 1), per-home sessions
fm-<hometag> with ambient HC_* markers stripped, task terminals as
labeled `hc run` shells (<session>:<tN>), a pending-buffer send model
because hc send is atomic paste+Enter, structured verdicts from its
exit codes, and kill+rm with ownership re-reads. Poll-only this stage;
no auto-detection, no secondmates, no supervisor/afk/relaunch claims.

Ships with an isolated lab helper (scratch XDG roots, pinned socket,
fleet tripwire, session-process teardown), a pinned installer, a
portable fake-hc suite, and a gated real-hc smoke.

* hc: consolidate Stage-1 onto the upstream hc backend

Upstream's bin/backends/hc.sh already owns the Herdr Core adapter, so the
parallel herdr-core backend world (adapter, docs, tests, lab, installer,
ci-cleanup) is removed. The Stage-1 capabilities it carried are ported onto
hc: a binary gate (FM_HC_BIN, then herdr-core, then hc; `hc x.y.z` version
shape with a 0.1.14 floor), a protocol-generation-1 hello handshake in
container_ensure, `--` delimiters on send/keys, and send_text_submit driven
by `hc send --wait` (native started/working proof, exit-9 blocked is a hard
stop, conservative composer fallback).

The lab world lands as fm-hc-lab.sh with a fleet-state tripwire and a
serve/hold daemon sweep that excludes the caller's process tree by process
group (an exported HC_SESSION otherwise self-matches forever). The smoke
and the default-on liveness e2e run inside lab sessions; fm-install-hc.sh
pins 0.1.14 with SHA-256 verification; a required tests-hc CI lane mirrors
tests-herdr with snapshot/cleanup around a serial `--family hc` run.

* no-mistakes(review): Pin hc test binary, resolver, stat, lab XDG roots

* no-mistakes(document): Correct hc setup and verification documentation

* no-mistakes(ci): Fixed all three findings: private validated lab/socket roots and exclusive sessions, cleanup in both live-test EXIT handlers, and fail-closed fleet snapshot reads. Added behavioral regressions; confirmed they reject the original implementation. Adapter tests (16), targeted regressions, injected cleanup failures, shell syntax, ShellCheck, and diff checks passed. Real-Core live tests skipped because hc/herdr-core is unavailable

* no-mistakes(document): Correct hc setup and cleanup documentation

* Fix host mirror deduplication before text capping (#7914)

* test: clear inherited launcher environment in shared fixtures (#7589)

* fix(tests): start suites from CI's environment, not the launching terminal's

A suite run directly from a terminal hosted by herdr inherited that launcher's
identity (HERDR_ENV, HERDR_PANE_ID, HERDR_SOCKET_PATH and siblings), its
TERM_PROGRAM marker, the FM_BACKEND selector bin/fm-spawn.sh exports into task
panes, and any home/state override (FM_HOME, FM_*_OVERRIDE) a supervisor shell
exports. Spawn and backend fixtures then bound to the host's real herdr session
instead of the isolated one their case creates: several suites failed with
`herdr launcher pane '...' belongs to the server at ... not session 'default'`,
and fm-spawn-worktree-settle recorded a real workspace's pane path as a fixture
worktree, while the same suites passed in CI. The effect only appears on a
herdr-hosted machine.

Clear that inherited environment o…
@babbarc
babbarc deleted the fm/offer-fleet-env-leak-fixes-upstream branch November 22, 2026 17:14
joergoss pushed a commit to joergoss/firstmate that referenced this pull request Nov 23, 2026
…nguid#7589)

* fix(tests): start suites from CI's environment, not the launching terminal's

A suite run directly from a terminal hosted by herdr inherited that launcher's
identity (HERDR_ENV, HERDR_PANE_ID, HERDR_SOCKET_PATH and siblings), its
TERM_PROGRAM marker, the FM_BACKEND selector bin/fm-spawn.sh exports into task
panes, and any home/state override (FM_HOME, FM_*_OVERRIDE) a supervisor shell
exports. Spawn and backend fixtures then bound to the host's real herdr session
instead of the isolated one their case creates: several suites failed with
`herdr launcher pane '...' belongs to the server at ... not session 'default'`,
and fm-spawn-worktree-settle recorded a real workspace's pane path as a fixture
worktree, while the same suites passed in CI. The effect only appears on a
herdr-hosted machine.

Clear that inherited environment once in tests/lib.sh, the shared fixture
layer. bin/fm-test-run.sh already cleared the overrides and FM_BACKEND per
worker, but not the herdr identity, and a direct `bash tests/x.test.sh` run got
neither. A case that deliberately exercises a launcher identity, a backend, or a
home/state override still exports its own value after sourcing the library.

* no-mistakes(review): Remove unneeded HERDR_CONTAINER_RAW and TERM_PROGRAM_VERSION from test unset list

* no-mistakes(review): Add launcher environment regression test and correct lib comments

* no-mistakes(review): Preserve operator config override in T3 live suites

* no-mistakes(test): Accept subreaper adoption in session-lock recycled-chain test

* test: keep the session-lock subreaper fix out of this offer

The reparent assertion in fm-session-lock-ancestry fails the same way on
untouched upstream under a child subreaper, so it is a pre-existing host
portability issue this change did not cause. Restore the file so the offer
carries only what the launcher-environment fix requires.

---------

Co-authored-by: yeti <yeti@alps>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

full-ci Maintainer go-ahead: run the full CI suite on this outside pull request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants