Repository navigation
feat(bin): automatic main-session handover on context and quota exhaustion - #4
Conversation
…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.
…itional helper pane cleanup
…ert terminal failures once
…urce schema header
…writes, fail malformed source windows closed, stage-specific stalled-successor bound, drop redundant force-owner guard
…er argv guard, add live Herdr lab e2e
…arrow adapter claims
There was a problem hiding this comment.
Devin Review found 3 potential issues.
2 flags not posted on this PR by your GitHub settings — view them in Devin Review. (Configure)
| 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 |
There was a problem hiding this comment.
🔴 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
| if [ -n "$old_session" ] && [ "$old_session" != "$session_id" ]; then | ||
| if [ -n "$old_pid" ] && kill -0 "$old_pid" 2>/dev/null; then | ||
| return 0 | ||
| fi |
There was a problem hiding this comment.
🟡 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.
Was this helpful? React with 👍 or 👎 to provide feedback.
| if local_phase \ | ||
| && [ ! -e "$FM_HOME/.fm-secondmate-home" ] \ | ||
| && [ ! -L "$FM_HOME/.fm-secondmate-home" ] \ | ||
| && [ -x "$SCRIPT_DIR/fm-primary-resource.sh" ]; then |
There was a problem hiding this comment.
🟡 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.
| 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 |
Was this helpful? React with 👍 or 👎 to provide feedback.
…assertion, fix serial hint
…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
…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]>
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
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.fm-bootstrap.sharms it as a seventh mutating sweep in the locked main home (onePRIMARY_RESOURCE: not armed - <reason>line on failure),fm-turnend-guard.shbest-effort observes the session binding at turn end, and a newprimary-resource-handoverskill plusAGENTS.mdand docs updates define the stow-attestation/commit wake flow, state schema, and verification grades.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) behindfm_live_gate, with both registered infm-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.
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)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)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> positionallyEvidence: 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)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-* leakPipeline
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 readingtests/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.
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 0bin/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-preservingreal 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.txttargeted 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 0teeth 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 runsbin/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=183928LC_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 downdocs/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.