Skip to content
This repository was archived by the owner on Nov 5, 2026. It is now read-only.

feat(bin): automatic main-session handover on context and quota exhaustion - #4

Merged
auss merged 24 commits into
mainfrom
fm/fm-primary-resource-guard-r2
Sep 13, 2026
Merged

auss merged 24 commits into
mainfrom
fm/fm-primary-resource-guard-r2

Conversation

@auss

@auss auss commented Sep 13, 2026 •

Copy link
Copy Markdown
Owner

Intent

Protect the main Firstmate session from context and quota exhaustion by handing over automatically. At a reliable 175K-token context reading, stow durable state and hand supervision to a same-agent successor. At 97% use of a relevant 5-hour or weekly window, stow and hand over to an agent on an independent provider. Quota wins when both triggers apply. An unavailable or uncertain context reading alerts only and never closes the session. An immutable incident receipt caps the guard at one automatic action per incident and is the only exit authority. Reuse the existing watcher/stow/quota machinery, keep scope to the main session rather than workers, capture launch argv only from NUL-delimited /proc//cmdline and alert unparseable-launch-argv where no unambiguous source exists, and cover Herdr both with a portable mock regression and a live lab-scoped e2e behind fm_live_gate driven through bin/fm-herdr-lab.sh.

This run fixes two CI failures on PR #4, both in tests/fm-primary-resource.test.sh, neither in product code.

(1) Lint: SC2031 x17 around lines 947-959. CI runs full ShellCheck extended analysis, which local changed-file mode does not, so it only appears in CI. The locked-outcome fixture reads $home, $!, $holder and $helper_pid across a subshell boundary. Restructure so those values are not read across it, while still exercising a real concurrent lock holder and still asserting the locked outcome write. No blanket file-level disable; a narrow per-line disable with a justifying comment is acceptable only where restructuring would destroy the concurrency under test.

(2) Behavior portable serial 5: exit=1 on 'emitted line must not be MISSING:' because the runner legitimately emits an unrelated 'MISSING: treehouse'. The assertion is over-broad. Its real purpose is to prove the arm failure is reported as 'PRIMARY_RESOURCE: not armed - ' and not as a MISSING: line, since MISSING: routes to tool-install consent. Narrow it: assert the PRIMARY_RESOURCE line is present and that no MISSING: line referring to this guard is emitted. Do not assert on unrelated tools, do not delete the case, do not install treehouse.

Bash 3.2 compatible. Do not weaken or delete regression coverage to make CI pass.

What Changed

  • Added bin/fm-primary-resource.sh, a main-session-only guard that observes the bound session's context and provider quota and, at 175K context tokens or 97% window use, stows durable state and hands supervision to a same-agent or independent-provider successor (quota wins when both apply); unknown or unsupported readings alert only and never close the session, and an immutable no-clobber incident receipt caps the guard at one automatic action per incident.
  • Wired the guard into the fleet: fm-bootstrap.sh arms it as a seventh mutating sweep in the locked main home (one PRIMARY_RESOURCE: not armed - <reason> line on failure), fm-turnend-guard.sh best-effort observes the session binding at turn end, and a new primary-resource-handover skill plus AGENTS.md and docs updates define the stow-attestation/commit wake flow, state schema, and verification grades.
  • Added regression coverage: a portable suite (tests/fm-primary-resource.test.sh) over thresholds, receipts, quota episodes, Herdr guards, and a live isolated tmux helper exit->shell->successor path, plus a live lab-scoped Herdr end-to-end test (tests/fm-primary-resource-herdr-lab-e2e.test.sh) behind fm_live_gate, with both registered in fm-test-run.sh.

Risk Assessment

✅ Low: The fix round implements the three authorized remedies exactly and minimally — SC2031 fully resolved via restructure with real concurrency and all assertions preserved, the MISSING assertion narrowed as prescribed, and hints documented with honest provenance — with no new machinery, no weakened coverage, and all prior authorized safety invariants verified intact at HEAD.

Testing

Reproduced both CI failures against the pre-fix commit (17 SC2031 under the CI ShellCheck posture; exit 1 on the over-broad MISSING assertion under a faithfully reproduced treehouse-absent CI host driving the real bin/fm-bootstrap.sh), then drove the post-fix change green across every targeted scenario: lint owner script exit 0, the restructured lock-serialization case passing on both pre- and post-fix versions with its real concurrent fm-wake-lib lock holder and locked-outcome assertions intact, the narrowed assertion passing the CI shape while still failing a guard-referring MISSING line, the full 49-case suite green through the real bin/fm-test-run.sh runner (exit 0, 184s, timing artifact recorded), the coverage guard and shard scheduler consuming the corrected 36781 hint (suite reassigned shard 5 to 2, partition still complete), and the live Herdr lab e2e passing behind fm_live_gate with the default Herdr session untouched and no lab leak. Note: the coverage guard needs LC_ALL=C on this host because pre-existing base comm calls compare C-sorted files under the ambient locale; zero comm lines changed on this branch and CI runs under the C locale, so this is not a regression. No UI surface exists in this change, so no screenshot was applicable; evidence is CLI transcripts, command output, a runner timing JSON, and before/after comparisons in the evidence directory. Worktree left clean; all transient driver files removed.

  • Live validation: ✅ go - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
CI lint gate passes on the restructured suite: ShellCheck extended analysis reports zero SC2031 (was 17) with no blanket disable ✅ pass live Pre-fix repro: 17 SC2031 on b916cab; post-fix: shellcheck --norc --external-sources exit 0 and bin/fm-lint.sh (CI posture, pinned 0.11.0) exit 0; evidence/sc2031-before-after.txt
Restructured lock-holder fixture still exercises a real concurrent fm-wake-lib lock holder and still asserts the locked outcome write (concurrency not weakened to satisfy the linter) ✅ pass live test_outcome_writers_serialize_under_resource_lock ran green post-fix and pre-fix (behavior-preserving): helper outcome write blocked while the separate holder script holds the real resource lock, end…
Bootstrap arm-failure diagnostic test passes on a CI-shaped host (unrelated leading 'MISSING: treehouse') while still asserting the PRIMARY_RESOURCE line and still failing on a guard-referring MISSING… ✅ pass live Real bin/fm-bootstrap.sh driven under treehouse-absent PATH: leading MISSING: treehouse + PRIMARY_RESOURCE: not armed, exit 0; targeted case pre-fix exit 1 / post-fix exit 0; teeth check fails on 'MIS…
Entire changed suite (49 cases incl. Herdr mock regressions and live tmux successor path) passes through the real CI runner bin/fm-test-run.sh ✅ pass live FM_TEST_SUMMARY total=1 failed=0 skipped_gate=0; tests/fm-primary-resource.test.sh exit=0 gate_skip=false duration_ms=183928; evidence/fm-primary-resource-full-suite-timing.json
Corrected 36781 ms serial weight hint is consumed by the real shard scheduler and the portable-serial partition stays complete and disjoint ✅ pass live --list-scheduled across portable-serial-1of5..5of5: suite assigned exactly once, now to shard 2 (was shard 5 under stale 8000); LC_ALL=C bin/fm-test-run.sh --check-coverage: FM_TEST_COVERAGE ok serial…
Branch intent: live lab-scoped Herdr e2e behind fm_live_gate passes, default Herdr session untouched, lab fully torn down ✅ pass live FM_PRIMARY_RESOURCE_HERDR_LAB_E2E=1 bash tests/fm-primary-resource-herdr-lab-e2e.test.sh: ok, exit 0; independent herdr session list identical before/after; evidence/live-herdr-lab-e2e-transcript.txt
Evidence: CI-shape bootstrap output (real product)

Source: CI-shape bootstrap output (real product)

MISSING: treehouse (install: ...) [line 1 of 7 unrelated MISSING lines] PRIMARY_RESOURCE: not armed - arm failed (python3/check-register/state path); automatic main-session resource protection is off [line 10] bootstrap exit code: 0 (non-fatal)

MISSING: treehouse (install: curl -fsSL https://kunchenguid.github.io/treehouse/install.sh | sh)
MISSING: gh (install: brew install gh  # or the platform's package manager)
MISSING: no-mistakes (install: curl -fsSL https://raw.githubusercontent.com/kunchenguid/no-mistakes/main/docs/install.sh | sh)
MISSING: gh-axi (install: npm install -g gh-axi && gh-axi setup hooks)
MISSING: chrome-devtools-axi (install: npm install -g chrome-devtools-axi && chrome-devtools-axi setup hooks)
MISSING: tasks-axi (install: npm install -g tasks-axi)
MISSING: quota-axi (install: npm install -g quota-axi)
PRESENTATION_UNAVAILABLE: lavish-axi (requires >=0.1.46; install: npm install -g lavish-axi && lavish-axi setup hooks) - nonvisual work may proceed with plain-text decisions and reports; install or upgrade before using Lavish
fm-primary-resource: python3 required for argv admission (install python3)
PRIMARY_RESOURCE: not armed - arm failed (python3/check-register/state path); automatic main-session resource protection is off
Evidence: MISSING assertion before/after under CI host shape

Source: MISSING assertion before/after under CI host shape

pre-fix (b916cab): not ok - emitted line must not be MISSING: (got: MISSING: treehouse ...) -> exit 1 post-fix (9529d1a): ok - bootstrap arm failure diagnostic -> exit 0 lock-serialization case: ok on both pre- and post-fix (restructure behavior-preserving)

CI host shape reproduced (PATH without treehouse/gh-axi/quota-axi/tasks-axi/no-mistakes;
python3 stubbed to exit 127 like the fixture). Real product bin/fm-bootstrap.sh output:
line 1  MISSING: treehouse (...)          <- unrelated leading line, the CI trigger
line 10 PRIMARY_RESOURCE: not armed - arm failed (python3/check-register/state path)...
exit code 0 (non-fatal). Full output: bootstrap-output-ci-shape.txt

Targeted test_bootstrap_arm_failure_diagnostic runs:
pre-fix  (b916cab): not ok - emitted line must not be MISSING: (got: MISSING: treehouse ...)  -> exit 1
post-fix (9529d1a): ok - bootstrap arm failure diagnostic                                     -> exit 0

test_outcome_writers_serialize_under_resource_lock:
pre-fix  (b916cab) and post-fix (9529d1a): both ok (restructure is behavior-preserving)
Evidence: SC2031 before/after under CI lint posture

Source: SC2031 before/after under CI lint posture

pre-fix (b916cab): SC2031 count 17, shellcheck exit 1 post-fix (9529d1a): SC2031 count 0, zero findings, bin/fm-lint.sh exit 0 (full extended analysis, pinned 0.11.0) no blanket or SC2031-specific disable added; holder now a separate script taking <root> <lock> <ready> positionally

CI lint posture = shellcheck 0.11.0 --norc --external-sources (full dataflow), as bin/fm-lint.sh runs in CI.

Pre-fix  (b916cab version of tests/fm-primary-resource.test.sh):
  SC2031 note count: 17  (exit 1)  - matches the CI lint failure in the intent
Post-fix (9529d1a, checked-out worktree):
  SC2031 note count: 0; shellcheck exit 0 (zero findings of any code)
  bin/fm-lint.sh tests/fm-primary-resource.test.sh bin/fm-test-run.sh -> exit 0
  ("full ShellCheck extended analysis enabled", pinned 0.11.0)

No blanket file-level disable and no SC2031-specific disable directive added:
the only disable in the file is a pre-existing SC2016 on an unrelated heredoc.
Restructure: the lock holder now runs as a separate script receiving
<repo-root> <lock> <ready> as positional parameters, driving the real
fm-wake-lib.sh lock protocol in its own process; values are no longer read
across the subshell boundary.
Evidence: Full-suite green timing artifact from the real CI runner

Source: Full-suite green timing artifact from the real CI runner

tests/fm-primary-resource.test.sh exit=0 gate_skip=false duration_ms=183928 (all 49 cases, incl. live tmux exit->shell->successor)

{
  "families": [
    {
      "count": 1,
      "duration_ms": 183928,
      "failed": 0,
      "name": "watcher-wake-lock"
    }
  ],
  "finished_at": "2026-09-13T11:38:08Z",
  "run_id": "fm-test-run-1789299304089-701154",
  "scripts": [
    {
      "duration_ms": 183928,
      "exit": 0,
      "expected_gate_skip": "none",
      "family": "watcher-wake-lock",
      "gate_skip": false,
      "gate_skip_reason": "",
      "path": "tests/fm-primary-resource.test.sh"
    }
  ],
  "selection": "scripts;jobs=1",
  "started_at": "2026-09-13T11:35:04Z",
  "summary": {
    "duration_ms": 184117,
    "failed": 0,
    "skipped_gate": 0,
    "total": 1
  }
}
Evidence: Live Herdr lab e2e transcript

Source: Live Herdr lab e2e transcript

FM_PRIMARY_RESOURCE_HERDR_LAB_E2E=1 ... ok - live Herdr lab handover: check->commit->helper->successor, default untouched; exit=0; herdr session list identical before/after, no fm-pr-resource-* leak

Invocation: FM_PRIMARY_RESOURCE_HERDR_LAB_E2E=1 bash tests/fm-primary-resource-herdr-lab-e2e.test.sh
Host: herdr 0.9.0 present; gate policy opt-in via fm_live_gate (tests/lib.sh).
Output:
ok - live Herdr lab handover: check->commit->helper->successor, default untouched
exit=0

Default-session safety (independent 'herdr session list' before vs after):
identical - default session still 'running', no fm-pr-resource-* lab leaked.
(The two stopped fm-lab-fmpralert/fmtlive entries predate this phase and are
unchanged by it; this run's lab is fully torn down.)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 3 issues found → auto-fixed ✅
  • 🚨 tests/fm-primary-resource.test.sh:947 - The intent's required CI fix (1) is not implemented anywhere in the reviewed range (e3692df..b916cab): 'Restructure so those values are not read across it [the subshell boundary], while still exercising a real concurrent lock holder and still asserting the locked outcome write. No blanket file-level disable.' ShellCheck 0.11.0 -x still reports exactly 17 SC2031 notes, matching the CI lint failure: lines 947, 949, 950, 951(x3), 953, 957, 959, 967, 971, 976, 977, 978 in test_outcome_writers_serialize_under_resource_lock (the locked-outcome fixture reading $home/$!/$holder/$helper_pid across the command-substitution/background-subshell boundary), plus line 1012 in test_terminal_outcome_stage_not_resurrected and line 1628 in the Herdr helper-success fixture. CI runs full extended ShellCheck, so the lint gate keeps failing. The restructure must cover all 17 (including 1012 and 1628, not only 947-959) while keeping the real concurrent lock holder and the locked-outcome assertions intact.
  • 🚨 tests/fm-primary-resource.test.sh:1818 - The intent's required CI fix (2) is not implemented: test_bootstrap_arm_failure_diagnostic still carries the over-broad assertion 'case "$out" in MISSING:*) fail "emitted line must not be MISSING: (got: $out)"' (lines 1817-1818). The intent requires: 'Narrow it: assert the PRIMARY_RESOURCE line is present and that no MISSING: line referring to this guard is emitted. Do not assert on unrelated tools, do not delete the case, do not install treehouse.' Concrete failing sequence in CI: the fixture's FAKEBIN python3 stub (exit 127) and the CI host's absent treehouse make bin/fm-bootstrap.sh emit a leading 'MISSING: ...' line (bin/fm-bootstrap.sh:894/1055/1436), so the case matches output unrelated to this guard and the test exits 1 even though the correct 'PRIMARY_RESOURCE: not armed' diagnostic is present. The behavior-portable CI failure therefore reproduces unchanged.
  • ⚠️ bin/fm-test-run.sh:731 - The new portable-serial weight hint 'tests/fm-primary-resource.test.sh 8000' understates the suite's real duration by ~26x: the branch's own maintainer-verification record (docs/verification/runtime-backends.md, commit b916cab) shows a green run at duration_ms=209330, and docs/fm-test-portable-shards.md - the documented owner of these hints and their refresh procedure - has no entry for either new test file. The table's header scopes hints to shard balance only ('a stale hint costs balance rather than coverage'), so nothing is lost, but one CI serial shard will carry ~3.4 minutes of unbalanced load from this branch's heaviest new suite. Remedy: correct the hint to the recorded measurement (209330) or record it through the shards doc's refresh procedure once CI timing exists.

🔧 Fix applied.
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
CI lint gate passes on the restructured suite: ShellCheck extended analysis reports zero SC2031 (was 17) with no blanket disable ✅ pass live Pre-fix repro: 17 SC2031 on b916cab; post-fix: shellcheck --norc --external-sources exit 0 and bin/fm-lint.sh (CI posture, pinned 0.11.0) exit 0; evidence/sc2031-before-after.txt
Restructured lock-holder fixture still exercises a real concurrent fm-wake-lib lock holder and still asserts the locked outcome write (concurrency not weakened to satisfy the linter) ✅ pass live test_outcome_writers_serialize_under_resource_lock ran green post-fix and pre-fix (behavior-preserving): helper outcome write blocked while the separate holder script holds the real resource lock, end…
Bootstrap arm-failure diagnostic test passes on a CI-shaped host (unrelated leading 'MISSING: treehouse') while still asserting the PRIMARY_RESOURCE line and still failing on a guard-referring MISSING… ✅ pass live Real bin/fm-bootstrap.sh driven under treehouse-absent PATH: leading MISSING: treehouse + PRIMARY_RESOURCE: not armed, exit 0; targeted case pre-fix exit 1 / post-fix exit 0; teeth check fails on 'MIS…
Entire changed suite (49 cases incl. Herdr mock regressions and live tmux successor path) passes through the real CI runner bin/fm-test-run.sh ✅ pass live FM_TEST_SUMMARY total=1 failed=0 skipped_gate=0; tests/fm-primary-resource.test.sh exit=0 gate_skip=false duration_ms=183928; evidence/fm-primary-resource-full-suite-timing.json
Corrected 36781 ms serial weight hint is consumed by the real shard scheduler and the portable-serial partition stays complete and disjoint ✅ pass live --list-scheduled across portable-serial-1of5..5of5: suite assigned exactly once, now to shard 2 (was shard 5 under stale 8000); LC_ALL=C bin/fm-test-run.sh --check-coverage: FM_TEST_COVERAGE ok serial…
Branch intent: live lab-scoped Herdr e2e behind fm_live_gate passes, default Herdr session untouched, lab fully torn down ✅ pass live FM_PRIMARY_RESOURCE_HERDR_LAB_E2E=1 bash tests/fm-primary-resource-herdr-lab-e2e.test.sh: ok, exit 0; independent herdr session list identical before/after; evidence/live-herdr-lab-e2e-transcript.txt
  • shellcheck --norc --external-sources on b916cab's tests/fm-primary-resource.test.sh: 17 SC2031 notes, exit 1 (pre-fix CI failure reproduced)
  • shellcheck --norc --external-sources -- tests/fm-primary-resource.test.sh (post-fix): zero findings, exit 0
  • bin/fm-lint.sh tests/fm-primary-resource.test.sh bin/fm-test-run.sh: exit 0 under CI posture (pinned ShellCheck 0.11.0, full extended analysis)
  • targeted run of test_outcome_writers_serialize_under_resource_lock post-fix (ok) and pre-fix b916cab version (ok) - restructure is behavior-preserving
  • real bin/fm-bootstrap.sh driven under a reproduced CI host shape (PATH without treehouse/gh-axi/quota-axi/tasks-axi/no-mistakes, python3 stubbed to 127): leading 'MISSING: treehouse', 'PRIMARY_RESOURCE: not armed' at line 10, exit 0 - captured in evidence/bootstrap-output-ci-shape.txt
  • targeted test_bootstrap_arm_failure_diagnostic under the CI host shape: pre-fix exits 1 on 'emitted line must not be MISSING: (got: MISSING: treehouse...)', post-fix exits 0
  • teeth check driving the exact narrowed assertion block: unrelated 'MISSING: treehouse' passes, 'MISSING: primary-resource guard' fails (exit 1), and the PRIMARY_RESOURCE-not-armed positive assertion still runs
  • bin/fm-test-run.sh tests/fm-primary-resource.test.sh --json <evidence>/fm-primary-resource-full-suite-timing.json: all primary-resource tests passed, exit=0, gate_skip=false, duration_ms=183928
  • LC_ALL=C bin/fm-test-run.sh --check-coverage: FM_TEST_COVERAGE ok (serial=167, serial_shards=5, complete disjoint partition including both new files)
  • bin/fm-test-run.sh --lane portable-serial-{1..5}of5 --list-scheduled: corrected 36781 hint assigns the suite to shard 2 of 5 (moved from shard 5 under the stale 8000 hint; balance-only effect)
  • FM_PRIMARY_RESOURCE_HERDR_LAB_E2E=1 bash tests/fm-primary-resource-herdr-lab-e2e.test.sh: ok, exit 0; independent herdr session list before/after identical, default session running and untouched, fm-pr-resource lab fully torn down
⚠️ **Document** - 1 info
  • ℹ️ docs/fm-test-portable-shards.md:60 - The serial-shard aggregate prose and estimate table no longer match bin/fm-test-run.sh, but the drift predates this branch, so I left it untouched per scope discipline. Actual state at target: 149 hint entries summing 4369987 ms (doc says "145 current hints" totaling 4312606 ms), a 164-script serial lane with 16 unhinted scripts and 4782987 ms assignment weight (doc says a "154-script lane" with "nine such scripts" at 4555606 ms), and shards of 32/33/33/33/33 scripts at ~956.6k ms (doc table says 30/31/32/31/30 at 911111/911128 ms, imbalance 17 ms). At the base commit e3692df the doc was already stale (147 hint entries, serial=162, serial_unhinted=16 per --check-coverage), so this is main-side drift that the branch only extended by its two authorized, correctly documented hint entries. Fixing it honestly needs a full hint-refresh pass through this doc's own procedure (green CI timing artifacts supply the provenance the aggregate sentence asserts), not hand-edited numbers; balance-only impact per the doc's own "a stale hint costs balance rather than coverage".
✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

auss added 23 commits September 13, 2026 00:25
…ver skill

fm-primary-resource.sh owns observe/arm/check/decide/commit/helper for the
main Firstmate session: a reliable context reading at or above 175000 tokens
hands over to the same harness, and a provider quota window at or above 97
percent used hands over to an independent provider, with quota taking
precedence. An unavailable or uncertain reading alerts and never closes the
session, and one immutable receipt per incident is reserved before any
terminal action so a successor cannot repeat it.

The primary agent runs stow itself and passes a structured reset-safe
attestation bound to the incident and generation; commit revalidates the
binding, context, and quota under the resource lock before reserving. A
bounded helper in a backend-owned terminal proves the pane occupant is the
recorded session, sends the exit command once, and launches the successor
only into a proven shell. Herdr stays alert-only until a guarded live lab
proves that transaction end to end.
…nding

Bootstrap arms the standing check in the locked main-home path only, never in
a secondmate home, and reports an arm failure as PRIMARY_RESOURCE: not armed
rather than silently continuing without the protection. The turn-end guard
passes its already-read payload to observe so the reading is bound to the
lock-owning session; it never changes the guard's exit status or output.

AGENTS.md records the new private state directory and the handover skill
trigger, bootstrap-diagnostics owns the new prefix, and the test inventory
maps the new suite to the watcher family.
The repository documentation audience check refuses an unclassified surface,
so the new skill left bin/fm-doc-audience-check.sh failing and with it
tests/fm-documentation-audiences.test.sh. Classify it beside the other
agent-loaded skills.
The captain's decision removes the tmux-only narrowing: a main session running
on Herdr must hand over, not merely alert. pr_launch_helper now creates the
bounded helper's own non-focused workspace pane through the session-scoped CLI
wrapper, the same shape bin/fm-afk-launch.sh uses, and reclaims that endpoint
if the helper command cannot start. The three sites that converted a valid
handover into an alert are gone.

Commit-time revalidation also recomputes the launch-reconstruction guard
instead of assuming it: a session whose launch command cannot be rebuilt is
refused at the moment of acting, not only during the periodic check, and the
refusal names that concrete cause rather than reporting a generic mismatch.

Verified live on herdr 0.9.0 inside isolated fm-lab-* sessions created by
bin/fm-herdr-lab.sh, with teardown installed before provisioning: the real
launch path built its own workspace distinct from the stand-in primary pane,
the exit command left that pane shell-only, and a successor ran there. The
default session was untouched and no lab session leaked. The pane-level
sequence is proven; a full-fidelity run with a Herdr-recognised agent in the
lab pane is not, and the accompanying report says so.

Three test corrections, none of which weaken the guard: a case asserted a
codex binding while running under another harness, which is impossible since
codex is detected by process ancestry rather than a marker; a wall-clock
budget was tuned to the removed quota cache; and the new Herdr case needed a
reconstructable launch argv for the probe to read.
…writes, fail malformed source windows closed, stage-specific stalled-successor bound, drop redundant force-owner guard

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 3 potential issues.

2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)

Devin Review

Comment on lines +1063 to +1075
receipts_json='[]'
if [ -d "$PR_DIR/receipts" ] && [ -n "$(ls -A "$PR_DIR/receipts" 2>/dev/null || true)" ]; then
receipts_json=$(jq -nc '[inputs.incidentId] | unique' "$PR_DIR"/receipts/*.json 2>/dev/null || printf '[]')
fi
# Treat per-window claims and active episodes as receipt coverage.
if [ "$episode_blocks" = true ] && [ -n "$id_quota" ] && [ "$id_quota" != "quota-none" ]; then
receipts_json=$(printf '%s' "$receipts_json" | jq -c --arg id "$id_quota" '. + [$id] | unique')
fi
if [ -d "$PR_DIR/claims" ]; then
local claim_ids
claim_ids=$(pr_directory_filenames_json "$PR_DIR/claims")
receipts_json=$(jq -nc --argjson a "$receipts_json" --argjson b "$claim_ids" '$a + $b | unique')
fi

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Crash recovery loses quota aliases

After a quota commit crashes before alias claims, receipts_json reloads only the primary incident ID. Another receipted window can trigger a second handover.

Learn more

A quota receipt is durable before any terminal action. It records every exhausted window in windowClaims, but the next check builds suppression state from each receipt's incidentId only. The alias files and provider episode are created later in action_commit, and those writes ignore failures. A crash or write failure in that gap leaves the receipt as the only durable record of the additional windows. Once the primary window drops below threshold, another receipted window becomes the new primary incident and passes suppression.

Example: Five-hour and weekly windows are both exhausted. The receipt uses the five-hour hash as incidentId and stores both hashes in windowClaims. The process dies before creating claims. After five-hour quota resets, weekly quota remains exhausted and triggers another automatic handover.

Recommended fix: Include every validated receipt windowClaims entry in receipts_json, alongside incidentId. Treat malformed receipt data conservatively. Add a regression that stops after receipt creation, removes claims and the episode marker, changes which receipted window is primary, and confirms the next check stays silent.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +842 to +845
if [ -n "$old_session" ] && [ "$old_session" != "$session_id" ]; then
if [ -n "$old_pid" ] && kill -0 "$old_pid" 2>/dev/null; then
return 0
fi

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Context resets retain stale binding

When an in-process reset changes session ID, action_observe rejects it because the existing PID remains live. Protection keeps reading the previous conversation.

Learn more

Turn-end payloads identify the current vendor conversation by session ID and transcript path. A context reset can replace that conversation without replacing the long-lived CLI process. The old and new payloads therefore share a PID, which currently makes the new payload indistinguishable from a competing session and rejects it. The binding then never advances to the new transcript while that process remains alive.

Example: Claude runs session A, then /clear starts session B in the same process. The first turn end for B sees the live PID recorded for A and returns without updating binding.json. A later 175,000-token reading in B is never observed.

Recommended fix: Admit a changed session when the payload comes from the current session-lock owner, while still rejecting payloads from another live process. Bind the update atomically under the resource lock and add an in-process session-reset regression.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment thread bin/fm-bootstrap.sh
Comment on lines +1621 to +1624
if local_phase \
&& [ ! -e "$FM_HOME/.fm-secondmate-home" ] \
&& [ ! -L "$FM_HOME/.fm-secondmate-home" ] \
&& [ -x "$SCRIPT_DIR/fm-primary-resource.sh" ]; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Malformed marker disables resource protection

Bootstrap skips arm when any non-symlink marker exists, while pr_is_main_home rejects only valid markers. A malformed marker silently disables protection.

Learn more

The shared marker parser treats only a regular file containing a valid secondmate ID as a secondmate marker. A malformed marker in a plain checkout falls through to main-home scope. Bootstrap uses a broader existence test and never calls the script, so it also emits no failure diagnostic.

Example: A main home contains an empty .fm-secondmate-home. Other primary-scope checks treat the plain checkout as primary, but bootstrap skips resource arming and reports nothing.

Recommended fix: Delegate scope classification to action_arm and its pr_is_main_home check instead of duplicating a broader marker predicate in bootstrap.

Suggested change
if local_phase \
&& [ ! -e "$FM_HOME/.fm-secondmate-home" ] \
&& [ ! -L "$FM_HOME/.fm-secondmate-home" ] \
&& [ -x "$SCRIPT_DIR/fm-primary-resource.sh" ]; then
if local_phase && [ -x "$SCRIPT_DIR/fm-primary-resource.sh" ]; then
Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

@auss auss changed the title feat(bin): protect the main session from context and quota exhaustion via automatic handover feat(bin): automatic main-session handover on context and quota exhaustion Sep 13, 2026
@auss
auss merged commit 439251e into main Sep 13, 2026
15 checks passed
auss added a commit that referenced this pull request Sep 14, 2026
…stion (#4)

* feat(bin): add main-session resource protection command and its handover skill

fm-primary-resource.sh owns observe/arm/check/decide/commit/helper for the
main Firstmate session: a reliable context reading at or above 175000 tokens
hands over to the same harness, and a provider quota window at or above 97
percent used hands over to an independent provider, with quota taking
precedence. An unavailable or uncertain reading alerts and never closes the
session, and one immutable receipt per incident is reserved before any
terminal action so a successor cannot repeat it.

The primary agent runs stow itself and passes a structured reset-safe
attestation bound to the incident and generation; commit revalidates the
binding, context, and quota under the resource lock before reserving. A
bounded helper in a backend-owned terminal proves the pane occupant is the
recorded session, sends the exit command once, and launches the successor
only into a proven shell. Herdr stays alert-only until a guarded live lab
proves that transaction end to end.

* feat: arm main-session resource protection and observe its context binding

Bootstrap arms the standing check in the locked main-home path only, never in
a secondmate home, and reports an arm failure as PRIMARY_RESOURCE: not armed
rather than silently continuing without the protection. The turn-end guard
passes its already-read payload to observe so the reading is bound to the
lock-owning session; it never changes the guard's exit status or output.

AGENTS.md records the new private state directory and the handover skill
trigger, bootstrap-diagnostics owns the new prefix, and the test inventory
maps the new suite to the watcher family.

* docs: classify the main-session handover skill as agent-runtime

The repository documentation audience check refuses an unclassified surface,
so the new skill left bin/fm-doc-audience-check.sh failing and with it
tests/fm-documentation-audiences.test.sh. Classify it beside the other
agent-loaded skills.

* no-mistakes(review): Fix primary resource review findings

* no-mistakes(review): Narrow resource handovers to verified adapters

* no-mistakes(review): Remove stale decide command documentation

* no-mistakes(review): Always refresh quota and reconcile successor generations

* no-mistakes(review): Validate incident IDs before resource state writes

* no-mistakes(review): Preserve spawned Codex bypass flag

* no-mistakes(review): Reject malformed destination quota ranges

* no-mistakes(review): Gate handovers on validated live prerequisites

* feat(bin): hand over the main session on Herdr, not just tmux

The captain's decision removes the tmux-only narrowing: a main session running
on Herdr must hand over, not merely alert. pr_launch_helper now creates the
bounded helper's own non-focused workspace pane through the session-scoped CLI
wrapper, the same shape bin/fm-afk-launch.sh uses, and reclaims that endpoint
if the helper command cannot start. The three sites that converted a valid
handover into an alert are gone.

Commit-time revalidation also recomputes the launch-reconstruction guard
instead of assuming it: a session whose launch command cannot be rebuilt is
refused at the moment of acting, not only during the periodic check, and the
refusal names that concrete cause rather than reporting a generic mismatch.

Verified live on herdr 0.9.0 inside isolated fm-lab-* sessions created by
bin/fm-herdr-lab.sh, with teardown installed before provisioning: the real
launch path built its own workspace distinct from the stand-in primary pane,
the exit command left that pane shell-only, and a successor ran there. The
default session was untouched and no lab session leaked. The pane-level
sequence is proven; a full-fidelity run with a Herdr-recognised agent in the
lab pane is not, and the accompanying report says so.

Three test corrections, none of which weaken the guard: a case asserted a
codex binding while running under another harness, which is impossible since
codex is detected by process ancestry rather than a marker; a wall-clock
budget was tuned to the removed quota cache; and the new Herdr case needed a
reconstructable launch argv for the probe to read.

* no-mistakes(review): Harden Herdr handover ownership and helper cleanup

* no-mistakes(review): Authority exit PID via immutable receipt; unconditional helper pane cleanup

* no-mistakes(review): Delete launch files before helper pane close; alert terminal failures once

* no-mistakes(document): Document seven bootstrap sweeps; complete resource schema header

* no-mistakes(review): Clear stale episodes per provider, lock outcome writes, fail malformed source windows closed, stage-specific stalled-successor bound, drop redundant force-owner guard

* no-mistakes(review): Quote arm shim paths with printf %q for bash 3.2

* no-mistakes(document): Fix stale sweep counts and quota schema docs

* no-mistakes(review): repair portable resource handover paths

* no-mistakes(review): fail argv capture closed to /proc, quota wins over argv guard, add live Herdr lab e2e

* no-mistakes(document): Correct stale test-seam facts in primary-resource header

* no-mistakes(document): Record primary-resource verification grades; narrow adapter claims

* no-mistakes(review): restructure lock-holder fixture, narrow MISSING assertion, fix serial hint
auss added a commit that referenced this pull request Sep 14, 2026
…etection (#8)

* feat(bin): add Antigravity CLI (agy) as third worker/scout adapter (kunchenguid#4200)

* feat(agy): verify Antigravity CLI as third worker/scout adapter

Detection by anchored ancestry in fm-harness.sh (no marker of its own);
bootstrap harness and effort validation; launch template with model and
effort mapping plus reachable-catalog model validation; rendered-tail
busy fallback in fm-busy-lib.sh with delivery footer in fm-composer-lib.sh;
control mechanics with crewmate/scout-only refusal; tmux liveness naming;
router entry with concise adapter reference; dated verification record;
portable regression plus opt-in live drift guard.

Verified live on agy 1.2.0: supervised spawn, durable steering,
same-copy relaunch, and exit, with Herdr-native busy agreement.

* no-mistakes(review): bound agy model probe, gate trust dialog, narrow busy signature

* no-mistakes(review): pre-register agy workspace trust, make readiness gate strict

* no-mistakes(review): Close Orca terminal on gate failure; isolate live-guard HOME; tighten agy matching

* no-mistakes(document): Document agy adapter in stale harness enumerations

* no-mistakes(review): Clamp non-positive FM_AGY_MODELS_TIMEOUT to the default bound

* no-mistakes(document): Fix stale test-shard snapshots after agy lane additions

* no-mistakes(ci): Fixed ci-3 (tests/fm-agy-harness.test.sh:519). Root cause: the agy spawn fixture's default base PATH (/usr/bin:/bin:/usr/sbin:/sbin) omits node's directory, but the spawn drives the real bin/fm-agy-trust.sh (which hard-requires node to record trust) and the fixture's fake tmux trust lookup (node -e) under that PATH. On the ubuntu-latest CI runner node lives in the toolcache (/usr/local/bin), so trust pre-registration failed on portable serial 2; on typical Arch hosts node is in /usr/bin, masking the defect. Fix (smallest, following the existing tests/fm-kimi-harness.test.sh precedent of carrying the interpreter's resolved directory): resolve node from the invoking environment (failing the test with 'test needs node' if absent, as kimi does for python3) and prepend its directory to the fixture's default base PATH; the FM_TEST_BASE_PATH override contract is untouched. Verified locally: (1) pre-fix reproduction with a CI-shaped base PATH (system bins minus node) produced exactly the reported failure — 'node is required to record workspace trust and was not found on PATH' plus the fake tmux 'node: command not found'; (2) post-fix, all 29 tests in the file pass both with node available only via a leading non-standard dir in the base PATH (CI's shape) and with the default base PATH on this host. bash -n clean; ShellCheck is not installed in this worktree (previously recorded as environmental)

* no-mistakes(test): Give agy typed sends a longer submit-confirm budget

* no-mistakes(document): Document agy send budget, trust gate, and control coverage

* no-mistakes(document): Document agy busy fallback inventory and send-timing evidence

* feat(afk): add quiet supervision mode for a present captain (kunchenguid#4337)

* feat(afk): add quiet supervision mode for a present captain

Adds a first-class quiet supervision mode alongside /afk for
kunchenguid#2356: the same away-mode daemon, injection,
busy/composer guards, classification policy, and reliability
properties, but the captain staying present and chatting no longer
exits it - only an explicit /quiet off does.

state/.afk's first line now declares its mode (away, the default, or
quiet); fm_afk_mode() in bin/fm-wake-lib.sh is the single reader,
falling back to away for missing/empty/unreadable/unrecognized
content (including the legacy bare-epoch-timestamp format written
before mode existed) so nothing regresses. fm_afk_flag_write()
preserves the on-disk mode on a bare refresh (no explicit mode given)
rather than defaulting to away, which is what keeps the daemon's own
redundant terminal-side re-write from silently resetting a captain's
quiet mode back to away underneath them.

New .agents/skills/quiet/SKILL.md is a thin wrapper cross-referencing
/afk for every shared mechanism, per the one-owner rule. AGENTS.md
gains the state/.afk table entry and section 8's exit-trigger line.
bin/fm-supervision-instructions.sh, bin/fm-session-start.sh, and
bin/fm-guard.sh's stale-watcher banner all become mode-aware so a
quiet-mode captain is never misdirected to /afk in captain-facing
text.

Closes kunchenguid#2356

* no-mistakes(review): Fix AFK epoch parsing and quiet-mode digest wording for two-line flag

* no-mistakes(document): Fix turnend-guard.md daemon-ownership contract for quiet mode

---------

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

* fix(bin): let verified harness ancestry outrank retained markers (#3) (kunchenguid#3578)

* fix(bin): let verified harness ancestry outrank retained markers (#3)

* fix(bin): let a structural harness ancestor outrank a retained marker

bin/fm-harness.sh treated a verified environment marker as unconditionally
authoritative, so a Codex session started from an environment that had retained
CLAUDECODE=1 detected as claude. Session start then emitted Claude's Stop-owned
supervision protocol to a Codex primary, and every turn end was blocked for
missing Claude recovery.

The defect is the precedence boundary, not any one harness. codex, opencode,
kimi, and muse publish no identity marker at all, so with markers winning
outright any retained CLAUDECODE renamed them; the Cursor-before-Claude ordering
was a point patch on the same class of problem, and the launch-time marker
clearing only ever covered sessions fm-spawn started.

Markers and ancestry are now separate evidence layers that detect_own arbitrates:

- no ancestry match, or no marker: the single available layer answers, unchanged;
- same harness family: the marker's finer verdict stands, so a launch-selected
  pi-signed is not flattened to pi by an ancestry walk that can only see the
  shared launcher name;
- different harness with a structural (command-name) ancestor: ancestry wins,
  because only ancestry proves who owns the process tree;
- different harness with only a bare-interpreter script-path match: the marker
  wins, since a harness-shaped path in some node process's arguments is weaker
  evidence than a harness publishing its own identity.

The correction is symmetric: a retained CURSOR_AGENT no longer renames a claude
worker nested under cursor either.

Adds fm-harness.sh ancestry [<pid>], ancestry evidence with no marker layer, so
a real harness process can be asked what the walk makes of it.

tests/fm-harness-precedence.test.sh is the portable regression, built from real
renamed processes with no harness installed. Every case drives the two layers
apart and asserts each alone as well as the combination, so no case can pass
vacuously; it also pins Codex's real two-process install topology, since the fix
depends on the native binary being what a tool subprocess meets first. The
opt-in drift guard gains the matching live half: each installed harness's real
running process must still be identified by the ancestry walk, and it fails
naming the harness and version when a release changes that name.

Documentation follows the corrected contract in the script header, the
harness-adapters detection section, the codex, opencode, kimi, and cursor
references, and a dated verification record.

* fix(tests): drop the unused argument pass-through in the shim-topology helper

bin/fm-lint.sh refused the branch: run_shim declared a `[ancestry]` argument and
forwarded "$@", but every call site that varies the environment or passes the
ancestry subcommand invokes the shim entry point directly, so the helper is only
ever called with no arguments (ShellCheck SC2120/SC2119).

Behavior is unchanged: with no arguments "$@" expanded to nothing.

* fix(bin): examine the top of the process chain instead of assuming init

harness_ancestry stopped as soon as the next pid was 1, on the assumption that
pid 1 is always init and can never be a harness.
Inside a PID namespace that assumption inverts: the harness itself is pid 1, so
the walk never examined the one process that proves who owns the tree, reported
no ancestry at all, and handed the verdict straight back to a retained marker.

A real Codex session under `codex sandbox`, holding CLAUDECODE=1 and
CLAUDE_CODE_ENTRYPOINT=cli, is exactly that shape: it resolved claude and
rendered Claude's Stop-owned supervision protocol even with the marker-vs-ancestry
precedence boundary in place.
The same probe now resolves codex and renders the Codex foreground checkpoint.

A host's real pid 1 (init, systemd, launchd) matches no harness name, so
examining it costs one ps call and can introduce no false positive; the walk
still stops once that top process has been read, and a non-numeric or zero ppid
still ends it.

tests/fm-harness-precedence.test.sh pins the namespace shape with a fake ps that
reports every process as bash with ppid 1 and pid 1 as the harness.
The case asserts the marker still answers alone when pid 1 is host-shaped, so it
cannot pass vacuously, and it fails against the previous stop condition.

* docs(verification): record the real-Codex retained-marker evidence

The existing record proved the precedence boundary with the portable regression
and recorded each installed harness's process name behind the ancestry walk, but
it had no evidence from a real Codex process actually holding a retained Claude
marker, which is the failure the boundary exists for.

Adds the dated before/after result from codex-cli 0.152.0 under `codex sandbox`,
with the exact command and the decisive verdict and rendered protocol on each
side, and records the second boundary that shape exposed: the walk must examine
the top of the process chain, because inside a PID namespace the harness is pid 1.
Refreshes the portable regression's observed output for the case it gained.

* no-mistakes(review): blind ancestry in marker-pinned harness tests

* no-mistakes(review): blind ancestry in the Pi guard-routing test

* no-mistakes(review): classify precedence suite, dedupe ps stub, soften claims

* no-mistakes(review): model the spawn-and-wait Codex shim topology

* no-mistakes(document): correct stale muse marker-clearing detection claims

* no-mistakes: apply CI fixes

* fix(bin): examine the top of the chain in the lock and nudge walks too

The pid-1 defect corrected in bin/fm-harness.sh survived unchanged in the two
other harness-ancestry walks, on the exact topology the branch verified against
a real Codex process.

bin/fm-session-lock-lib.sh's fm_harness_ancestry_pids stopped as soon as the next
pid was 1, so a firstmate whose harness is pid 1 of its own PID namespace could
not find that harness at all and did not recognize its own session lock.
bin/fm-sessionstart-nudge.sh carried the same stop plus a blanket rejection of a
lock pid of 1, so the same session was told to run session start again on every
turn.

Both walks now compare the top process before stopping, matching the shape used
in bin/fm-harness.sh.
For the lock walk this is safe because fm_harness_process_matches rejects a
host's real pid 1.
For the nudge, `kill -0` still gates the lock pid, and on a host an unprivileged
`kill -0 1` fails, so a lock file that wrongly names pid 1 leaves the hook silent
rather than acting on init.

Each walk gains one regression case. The lock case drives a deterministic process
table whose pid 1 is the harness and asserts a host-shaped pid 1 still finds
nothing, so it cannot pass vacuously. The nudge case needs a real PID namespace,
because the builtin `kill -0` gate cannot be reached through a fake ps, and it
first proves the same fixture nudges with no lock present; it skips explicitly
where unprivileged namespaces are unavailable.

* no-mistakes(review): assert comm-strength detection from subprocess vantage in drift guard

* fix(bin): verify the live harness guard at the strength the guarantee needs

The marker-versus-ancestry boundary this branch ships is a strength claim:
detect_own hands an args-strength verdict straight back to a retained foreign
marker, so a harness is only protected where the ancestry walk reaches it at
comm strength.

The installed-harness drift guard probed the pane process alone. Under an
interpreter shim the pane process IS the shim, whose own script path is args
strength, while the native binary that carries comm strength is its child. The
guard therefore observed args for Codex, passed, and would have kept passing if
a release stopped spawning that native child at all, while real sessions
silently regressed to the original bug.

fm-harness.sh gains `ancestry-subtree`, which asks the walk from the pane
process and every descendant of it, the vantage a tool subprocess actually
occupies. The guard now requires comm strength somewhere in that set and
requires every vantage to name the same harness.

This supersedes the preceding commit's in-guard leaf walk, which reached the
same vantage but left the logic inside the test file, where CI could not pin it
and nothing else could reuse it. A harness-dependent check needs both halves:
`tests/fm-harness-precedence.test.sh` now carries a portable case proving the
subtree probe reaches a strength the top-of-session probe cannot, mutation
checked twice, once against the pre-change script and once by disabling
descendant enumeration. The subtree walk also avoids depending on tty and
process-group semantics that differ between Linux and macOS.

Verified live: codex-cli 0.152.0 reports [args codex;comm codex] and Claude Code
2.1.257 reports [comm claude].

* no-mistakes(review): narrow drift guard to the upward vantage path

* no-mistakes(review): judge only comm-strength vantages in drift guard

* no-mistakes(document): drop duplicated rationale in detection precedence evidence

* no-mistakes(review): fix pid-1 nudge case vacuity and descent no-arg expansion

* no-mistakes(document): drop branch-relative phrasing in detection precedence evidence

* no-mistakes(review): guard remaining empty positional expansions in fm-harness

* no-mistakes(document): scope cursor marker-ordering claim to the marker layer

* no-mistakes(review): Prefer comm-strength leaves in equal-depth descent ties

* no-mistakes(document): Document comm-strength descent tie-break

---------

* no-mistakes(review): Blind ancestry in stale gemini/rovo marker-precedence tests

* no-mistakes(document): Add missing equal-depth-tie test line to precedence evidence transcript

* no-mistakes(review): Fix stale/vacuous agy precedence test, add agy to precedence suite and docs

* no-mistakes(document): Fix stale kimi.md marker doc missed by ancestry-precedence fix

---------

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

* fix(bin): pre-approve external CLAUDE.md import dialog for spawned workers (kunchenguid#3944)

Claude Code's external-imports check (hasClaudeMdExternalIncludesApproved)
reads only the canonical git-root project entry in ~/.claude.json, which its
own worktree-to-primary-checkout canonicalization means is never the task
worktree fm-claude-trust.sh registered. The trust dialog kept working
previously only because its check has an ancestor-walk fallback that happens
to reach the worktree entry; the external-imports check has no such
fallback.

Verified by disassembling the installed claude binary and reproducing in an
isolated three-way tmux launch: identical flags registered only at the
worktree key still showed the external-imports dialog, and registering them
at the primary checkout key suppressed both dialogs.

fm-claude-trust.sh now registers all three flags on both the worktree entry
and the primary-checkout entry in one atomic write, and refuses when the
<project> argument is not itself a primary checkout (its own write target
would then be wrong). Extends the harness-adapters Claude reference and the
trust test suite.

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

* fix(afk-return): treat an acked watcher-down marker as no gap (kunchenguid#4355)

The marker lifecycle (fm-wake-lib.sh _fm_recovery_marker_ack) leaves
state/.watcher-down behind in an acked:* state after a downtime episode
is handled. health_snapshot's presence check reported that as an open
gap on every later return, so a handled episode kept surfacing as a
false GAP forever.

* fix(bin): rebind fm-procevent-when trust bindings after a self-update (kunchenguid#4361)

* fix(update): rebind fm-procevent-when watches after a self-update

A self-update fast-forwards bin/ in place, changing an armed watch's
action executable bytes with no tampering involved. The watch's trust
binding was hashed at arm time, so the very next fire was refused as
not matching the registered binding and the watch died silently.

Add fm-procevent-when.sh rebind-all: it re-hashes and republishes the
trust binding for every watch whose action executable lives under
FM_ROOT, using the same spec/trust validation as an ordinary fire, and
leaves any watch whose action lives outside FM_ROOT untouched. Wire it
into fm-update.sh right after a successful fast-forward, for both the
primary home and any local secondmate home that advances.

* no-mistakes(review): Canonicalize FM_ROOT for rebind-all's containment check

* no-mistakes(document): Document fm-update.sh's automatic watch rebind and its verification evidence

* no-mistakes(lint): fix(tests): double-quote printf scripts to satisfy shellcheck SC2016

* no-mistakes(review): Reload trust binding from disk before firing to reach live pollers

* no-mistakes(review): Lock the fire-time trust reload against rebind_one's publish race

* no-mistakes(document): Document rebind-all's self-update guarantee and its two review-round test rows

---------

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

* feat(brief): require poteto-mode in generated worker briefs by default

Ship and scout briefs now carry a Poteto mode section instructing the
worker to run the task under the poteto-mode skill. config/poteto-mode
gates it: absence or "on" enables, "off" omits, and any other value
refuses the scaffold so a typo cannot silently drop the requirement.
Secondmate charters never receive the section and never read the file.

The unguarded section authorizes exactly the skill's own lifecycle -
renaming the worker's own pane, one run tab, splits inside it, and role
and watchdog panes it started - and forbids touching another run's or
the fleet's panes, so the brief no longer tells a worker to perform and
avoid the same step. A --herdr-lab brief runs the playbook in-host
instead, because its lab contract governs every Herdr call. Where the
skill's playbook duplicates a review, validation, or shipping step the
delivery path already covers, the delivery path satisfies it, keeping
AGENTS.md section 7's prohibition on stacked reviews intact.

The setting is inherited into secondmate homes. B21's concurrent-push
wait now ends on the marker or the child's exit instead of a wall-clock
bound that failed under load.

* feat(bin): automatic main-session handover on context and quota exhaustion (#4)

* feat(bin): add main-session resource protection command and its handover skill

fm-primary-resource.sh owns observe/arm/check/decide/commit/helper for the
main Firstmate session: a reliable context reading at or above 175000 tokens
hands over to the same harness, and a provider quota window at or above 97
percent used hands over to an independent provider, with quota taking
precedence. An unavailable or uncertain reading alerts and never closes the
session, and one immutable receipt per incident is reserved before any
terminal action so a successor cannot repeat it.

The primary agent runs stow itself and passes a structured reset-safe
attestation bound to the incident and generation; commit revalidates the
binding, context, and quota under the resource lock before reserving. A
bounded helper in a backend-owned terminal proves the pane occupant is the
recorded session, sends the exit command once, and launches the successor
only into a proven shell. Herdr stays alert-only until a guarded live lab
proves that transaction end to end.

* feat: arm main-session resource protection and observe its context binding

Bootstrap arms the standing check in the locked main-home path only, never in
a secondmate home, and reports an arm failure as PRIMARY_RESOURCE: not armed
rather than silently continuing without the protection. The turn-end guard
passes its already-read payload to observe so the reading is bound to the
lock-owning session; it never changes the guard's exit status or output.

AGENTS.md records the new private state directory and the handover skill
trigger, bootstrap-diagnostics owns the new prefix, and the test inventory
maps the new suite to the watcher family.

* docs: classify the main-session handover skill as agent-runtime

The repository documentation audience check refuses an unclassified surface,
so the new skill left bin/fm-doc-audience-check.sh failing and with it
tests/fm-documentation-audiences.test.sh. Classify it beside the other
agent-loaded skills.

* no-mistakes(review): Fix primary resource review findings

* no-mistakes(review): Narrow resource handovers to verified adapters

* no-mistakes(review): Remove stale decide command documentation

* no-mistakes(review): Always refresh quota and reconcile successor generations

* no-mistakes(review): Validate incident IDs before resource state writes

* no-mistakes(review): Preserve spawned Codex bypass flag

* no-mistakes(review): Reject malformed destination quota ranges

* no-mistakes(review): Gate handovers on validated live prerequisites

* feat(bin): hand over the main session on Herdr, not just tmux

The captain's decision removes the tmux-only narrowing: a main session running
on Herdr must hand over, not merely alert. pr_launch_helper now creates the
bounded helper's own non-focused workspace pane through the session-scoped CLI
wrapper, the same shape bin/fm-afk-launch.sh uses, and reclaims that endpoint
if the helper command cannot start. The three sites that converted a valid
handover into an alert are gone.

Commit-time revalidation also recomputes the launch-reconstruction guard
instead of assuming it: a session whose launch command cannot be rebuilt is
refused at the moment of acting, not only during the periodic check, and the
refusal names that concrete cause rather than reporting a generic mismatch.

Verified live on herdr 0.9.0 inside isolated fm-lab-* sessions created by
bin/fm-herdr-lab.sh, with teardown installed before provisioning: the real
launch path built its own workspace distinct from the stand-in primary pane,
the exit command left that pane shell-only, and a successor ran there. The
default session was untouched and no lab session leaked. The pane-level
sequence is proven; a full-fidelity run with a Herdr-recognised agent in the
lab pane is not, and the accompanying report says so.

Three test corrections, none of which weaken the guard: a case asserted a
codex binding while running under another harness, which is impossible since
codex is detected by process ancestry rather than a marker; a wall-clock
budget was tuned to the removed quota cache; and the new Herdr case needed a
reconstructable launch argv for the probe to read.

* no-mistakes(review): Harden Herdr handover ownership and helper cleanup

* no-mistakes(review): Authority exit PID via immutable receipt; unconditional helper pane cleanup

* no-mistakes(review): Delete launch files before helper pane close; alert terminal failures once

* no-mistakes(document): Document seven bootstrap sweeps; complete resource schema header

* no-mistakes(review): Clear stale episodes per provider, lock outcome writes, fail malformed source windows closed, stage-specific stalled-successor bound, drop redundant force-owner guard

* no-mistakes(review): Quote arm shim paths with printf %q for bash 3.2

* no-mistakes(document): Fix stale sweep counts and quota schema docs

* no-mistakes(review): repair portable resource handover paths

* no-mistakes(review): fail argv capture closed to /proc, quota wins over argv guard, add live Herdr lab e2e

* no-mistakes(document): Correct stale test-seam facts in primary-resource header

* no-mistakes(document): Record primary-resource verification grades; narrow adapter claims

* no-mistakes(review): restructure lock-holder fixture, narrow MISSING assertion, fix serial hint

* no-mistakes(document): fix stale agy session-lock vocabulary claims in docs

* fix(bin): layer approved agy fixes onto the auss-main-based rebase lineage

Carry the captain-approved deltas from the upstream-based validation lineage
onto the auss:main-based rebase (e6dc1e0) so the branch descends from
auss/firstmate:main and PR #8 is a clean fast-forward: the restored agy
composer-verdict subsystem with its palette-8 ghost stripper and Herdr
separated-pair admission, the agy 1.2.2 spinner status-row signature fix,
their tests, and the rebase-doc verification updates.

* no-mistakes(review): Fix stale usage() header range in fm-procevent-when.sh

* no-mistakes(document): fix stale skill cross-references and restore dropped rovo

* no-mistakes(ci): CI Lint failed on two ShellCheck SC2100 warnings in bin/fm-pending-reply-lib.sh lines 1081/1084: unquoted assignments token=pending-reply-missed and token=pending-reply-delivery-unknown, whose hyphenated bare values parse as arithmetic under full extended analysis (--external-sources). Fixed by quoting both values, matching the already-quoted recovery-delivery branch. Verified: reproduced both warnings locally with pinned ShellCheck 0.11.0 in the exact CI mode before the edit; after the fix shellcheck --norc --external-sources on the file exits 0 with no findings, and bin/fm-lint.sh bin/fm-pending-reply-lib.sh (full extended analysis plus backend-purity check) exits 0. These were the only findings in the CI Lint log (actionlint reported all 3 workflow files valid), so no other root is affected

---------

Co-authored-by: AnPod <[email protected]>
Co-authored-by: NewAiCoder-bot <[email protected]>
Co-authored-by: NewAiCoder <[email protected]>
Co-authored-by: NewAiCoder <[email protected]>
Co-authored-by: NewAiCoder <[email protected]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant