Repository navigation
feat(bin): guard stale local steers against prompt-cache expiry - #35
Merged
Merged
Conversation
fm-send now refuses an ordinary local steer once state/<id>.turn-ended shows the session idle past the prompt-cache TTL (default 3600s, overridable via config/cache-ttl-seconds), printing the exact relaunch command instead; --steer-stale opts into a deliberate resume, and resolve-key answers, typed-plane sends, and remote sends are untouched. The guard fails open whenever the idle marker is missing or unreadable. fm-fleet-snapshot.sh and fm-fleet-view.sh surface the same idle age per local task so the watcher's heartbeat fleet review flags a session as "cache expiring" at 50 minutes idle, ahead of the hour.
…resolve-key exemption
sKeLe100
added a commit
that referenced
this pull request
Sep 7, 2026
…fleet snapshot The upstream merge took upstream's fm-fleet-snapshot.sh wholesale, which dropped the fork-only prompt-cache expiry surfacing added in #35: the fm-cache-ttl-lib.sh source, the CACHE_TTL_SECONDS/CACHE_NEAR_EXPIRY_SECONDS knobs, the per-task idle-age fold, and the endpoint.idle_seconds / endpoint.cache_expiring JSON fields. bin/fm-fleet-view.sh still consumed endpoint.cache_expiring, so the fleet view's "cache expiring" flag silently went dead and tests/fm-fleet-snapshot-view.test.sh failed on "the default 3600s TTL must not flag a 550s-idle task". Reapplied on top of upstream's restructured task_json_lines, using the fork's later three-argument fm_cache_activity_age_seconds call so the fold still reads the snapshot's own epoch rather than wall clock. Verified: tests/fm-fleet-snapshot-view.test.sh and tests/fm-send-cache-stale-guard.test.sh pass; the failure does not reproduce on pre-merge bases 4e4caf5 or 4b946de, so it is a merge integration defect, not pre-existing. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JLQqvjgkJ4AqSMwxLHvhNj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Intent
Prompt-cache enforcement guard: (1) Steer guard in bin/fm-send.sh - before delivering an ordinary steer to a LOCAL worker, read the worker session's idle age from a cheap already-available signal (last-activity/turn-ended mtime), skipping refusal when the endpoint is actively busy (warm cache by definition). If idle exceeds the cache TTL threshold (default 3600s, overridable via optional config/cache-ttl-seconds; absent=3600; TTL<=0 means guard disabled, steers always allowed), REFUSE the steer with a one-line explanation and print the exact bin/fm-control.sh relaunch --note ... command. Provide an explicit override flag (--steer-stale) for deliberate resumes. Typed-plane carve-outs, --resolve-key answers to open decisions, and remote sends keep working unchanged - only ordinary local steers are guarded. Fail open if the idle signal is unreadable. (2) Near-expiry surfacing: in the watcher's heartbeat fleet view, flag any live worker idle beyond ~83% of the configured TTL as 'cache expiring', suppressed on dead endpoints, so the value derives from and propagates with the TTL config override. Acceptance: guard refuses >TTL-idle local steer with relaunch command and override hint; override flag works; resolve-key/lifecycle/remote paths untouched; heartbeat flags near-expiry workers; colocated tests for refuse/override/fail-open behavior; docs/configuration.md documents the optional config knob including TTL<=0 disabling the guard. Keep it small, no new daemons/polling, shellcheck-clean, one-owner rule (policy documented only in docs/configuration.md, not in gitignored data/).
What Changed
bin/fm-cache-ttl-lib.shas the single owner of the prompt-cache TTL knob (default 3600s, overridable via the optional localconfig/cache-ttl-seconds,<= 0disables the guard), its ~83% near-expiry lead, and the shared activity-age fold overstate/<id>.meta,.status, and.turn-ended;bin/fm-inactive-reconcile.shnow reuses that fold instead of its own copy.bin/fm-send.shrefuses an ordinary local text steer whose target session has been idle past the TTL, printing the exactfm-control.sh <task> relaunch --note ...command and a--steer-staleoverride hint (new flag added). The guard skips endpoints classified busy,--resolve-keyanswers,--fire-and-forgetandFM_SEND_INTERNAL=1callers (set now in bootstrap nudges, backlog handoff wakes, config re-read pointers, and pending-reply recovery), remote sends, and the typed plane; it fails open when idle markers are unreadable.bin/fm-fleet-snapshot.shemitsendpoint.idle_seconds/endpoint.cache_expiringfor local tasks andbin/fm-fleet-view.shrenders a(cache expiring)suffix on live endpoints; docs (configuration.md,architecture.md,scripts.md) document the policy and knob, with new tests intests/fm-send-cache-stale-guard.test.shandtests/fm-fleet-snapshot-view.test.sh.Risk Assessment
✅ Low: The guard is well-bounded and fails open on every unreadable signal, all internal/automated, resolve-key, typed-plane, and remote callers are verifiably exempt, the TTL knob and activity-age fold now have one owner with discriminating colocated tests, and the only residual item is a per-task process fork in the heartbeat path.
Testing
Ran the two colocated suites for this change (fm-send cache-stale guard, fleet snapshot/view near-expiry) plus the backlog-handoff suite that exercises one of the internal-wake exemption call sites — all green. Because passing unit tests alone do not show the captain-facing behavior, I also drove the real binaries against a scratch Firstmate home and captured a CLI transcript: the refusal message with its relaunch command and override hint on a 4001s-idle local worker (with the inbox verifiably untouched), the successful
--steer-staleresume, theconfig/cache-ttl-seconds=0disable path, and the rendered fleet-view row showingpresent (cache expiring)for the near-expiry worker while the dead endpoint stays unflagged and a past-TTL worker correctly falls back out of the expiring window. No source or test changes were needed; the worktree is clean.Evidence: Cache steer guard + heartbeat near-expiry CLI transcript
Source: Cache steer guard + heartbeat near-expiry CLI transcript
=== 1. Captain steers a local worker idle 4000s (default TTL 3600s) === $ bin/fm-send.sh t1 'any update on the migration?' error: steer refused for t1: its session has been idle 4001s (> 3600s prompt-cache TTL), so resuming it now would burn a full context reload instead of hitting the warm cache. Relaunch it fresh instead: .../bin/fm-control.sh t1 relaunch --note '<why>' To steer the stale session anyway, re-run with --steer-stale. [exit 1] inbox records written by the refused steer: 0 === 2. Same steer with --steer-stale === [exit 0] inbox records now: 2 === 3. config/cache-ttl-seconds = 0 (guard disabled) === [exit 0] inbox records now: 3 === 4. Watcher heartbeat fleet view (TTL=600 -> near-expiry mark 500s) === | gone-task | ... | cmux | absent | ... | | warm-task | ... | tmux | present (cache expiring) | ... | {"id":"gone-task","endpoint":{"exists":false,"cache_expiring":false}} {"id":"warm-task","endpoint":{"exists":true,"cache_expiring":true}} === 5. warm-task idle 5000s (past TTL) - guard territory, not 'expiring' === {"id":"warm-task","cache_expiring":false}Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
🔧 **Rebase** - 1 issue found → auto-fixed ✅
bin/fm-send.sh- merge conflict rebasing onto origin/main🔧 Fix applied.
✅ Re-checked - no issues remain.
bin/fm-secondmate-reconcile.sh:305- The round-3 decision required every internal/automated fm-send caller to be exempt from the steer guard, and docs/configuration.md now states "any programmatic caller sets FM_SEND_INTERNAL=1". Three call sites were updated (fm-backlog-handoff.sh:458, fm-config-inherit-lib.sh:885, fm-pending-reply-lib.sh:917) but bin/fm-secondmate-reconcile.sh:305 was not. Concrete path: a LOCAL secondmate s1 (no remote_host in meta, so TARGET_BACKEND != remote and the remote branch at fm-send.sh:758 is skipped) has been idle 2h — exactly the population fm-secondmate-reconcile targets. The reconciler runsFM_TASK_INBOX_LOCK_WAIT_SECS=0 ... fm-send.sh "$id" --fire-and-forget "$did" "$(reconcile_text)". --fire-and-forget forces INBOX_PLANE=1 (fm-send.sh:748) but is not one of the guard's exemptions at fm-send.sh:864 (RESOLVE_KEYS empty, STEER_STALE=0, FM_SEND_INTERNAL unset), fm_busy_classify_meta returns idle, and the steer is refused with exit 1. Since 1 is neither 0 nor the tolerated 3, the reconciler recordsfailed: <id> <kind>and rc=1 for every long-idle local secondmate — a permanent failure, since a rerun hits the identical refusal, and no human reads the printed relaunch hint. Fix by setting FM_SEND_INTERNAL=1 at that call site (or, more robustly, treating a non-empty FIRE_AND_FORGET_ID as internal in fm-send.sh's exemption test, since that plane is purely programmatic), and make the docs sentence true.bin/fm-send.sh:875- The guard treats the busy probe as fail-CLOSED while the intent promises fail-open on an unreadable signal.[ "${busy_verdict%% *}" != busy ]refuses onunknownas well asidle, and fm_busy_classify_meta returnsunknown <reason>whenever the backend probe cannot answer (unsupported harness, an ungated Kimi version, a capture that returns nothing). Concrete case: a worker on a harness with no trusted busy source is genuinely mid-turn on a 90-minute run; its .meta/.status/.turn-ended have not been touched for 4000s (nothing writes them during a turn), so idle_secs=4000 > 3600, the verdict isunknown, and the human's steer to a live, warm-cache session is refused with advice torelaunch, which would tear down in-flight work. The idle-age signal fails open (fm-cache-ttl-lib.sh returns nonzero and the && chain short-circuits) but the busy signal that is meant to protect exactly this case does not. Whetherunknownshould count as not-guarded is the author's call, since for a dead/target-less endpoint refusing is the right answer — distinguishingunknown missing/unknown no-target(refuse) from a probe that simply could not read (allow) would preserve both.🔧 Fix: exempt fire-and-forget deliveries from cache steer guard
1 error still open:
bin/fm-bootstrap.sh:380- bin/fm-bootstrap.sh's local secondmate nudge is an automated internal fm-send caller that was NOT exempted from the new steer guard, unlike the four call sites the fix rounds updated (fm-backlog-handoff.sh:458, fm-config-inherit-lib.sh:885, fm-pending-reply-lib.sh:917, and fm-secondmate-reconcile.sh:305 via the --fire-and-forget carve-out). Concrete path: a LOCAL secondmate s1 (no remote_host, so fm-send.sh:758's remote branch is skipped) has been idle 2h — the normal waiting state for a secondmate, and exactly the population this nudge targets. Firstmate updates and fm_ff_after_instruction_update calls secondmate_send_nudge, which runsFM_HOME=... FM_STATE_OVERRIDE=... fm-send.sh fm-s1 "$SECOND_MATE_NUDGE_MESSAGE". That message (bin/fm-secondmate-nudge-lib.sh:8, 'firstmate was updated to the latest - please re-read your AGENTS.md...') is plain text with no leading / or $, so INBOX_PLANE=1; RESOLVE_KEYS is empty, STEER_STALE=0, FM_SEND_INTERNAL is unset and FIRE_AND_FORGET_ID is empty, so every exemption at fm-send.sh:864 fails. fm_busy_classify_meta returns idle, idle_secs=7200 > 3600, and the guard refuses with exit 1. bin/fm-bootstrap.sh then prints 'NUDGE_SECONDMATES: secondmate s1: send failed: ...' and retains the retry marker — and the retry path at bin/fm-bootstrap.sh:453 issues the identical unexempted send, so it hits the same refusal on every subsequent bootstrap. The secondmate permanently never learns its AGENTS.md changed, and no human reads the printed relaunch hint. This also makes docs/configuration.md's new sentence ('any other programmatic caller, which sets FM_SEND_INTERNAL=1') false. Fix by setting FM_SEND_INTERNAL=1 on both fm-send invocations in bin/fm-bootstrap.sh (lines 380 and 453); bin/fm-config-push.sh:156 is already safe because it targets the remote route.🔧 Fix: exempt bootstrap secondmate nudges from cache steer guard
2 issues (1 warning, 1 info) still open:
bin/fm-cache-ttl-lib.sh:43- fm_cache_near_expiry_seconds evaluates the raw TTL string inside arithmetic expansion, applying bash's octal rule, while fm-send.sh compares the same string with [ -gt ] (base 10). config/cache-ttl-seconds=0600 gives the steer guard a 600s threshold but the heartbeat a near-expiry threshold of 320 instead of 500, so fm-fleet-snapshot labels cache_expiring from 320s idle - a wrong value with no error, and exactly the guard/heartbeat drift this shared lib exists to prevent. A value of 08 or 09 is worse: the expansion aborts with 'value too great for base', the function prints nothing, CACHE_NEAR_EXPIRY_SECONDS is empty, and fm-fleet-snapshot.sh:629's numeric test then emits 'integer expression expected' to stderr once per task while silently disabling the flag. Normalize once in the reader (strip leading zeros, or force base 10) so every consumer sees one value.tests/fm-send-cache-stale-guard.test.sh:229- test_resolve_key_answer_ignores_guard never reaches the guard. The fixture has no open decision, so fm-send.sh rejects the unknown key at line 596 ('no open decision or blocker with that key ...') and exits long before the INBOX_PLANE guard block at line 858; the test's case arm matches that message and passes. Removing the RESOLVE_KEYS emptiness check from the exemption at fm-send.sh:864 would not fail this test, so the intent's '--resolve-key answers to open decisions keep working unchanged' has no real coverage. Seed a genuinely open decision with activity markers aged past the TTL and assert the answer is delivered.🔧 Fix: normalize leading-zero TTL, cover open-decision resolve-key exemption
1 info still open:
bin/fm-fleet-snapshot.sh:628- fm_cache_activity_age_seconds is called without its optional now-epoch argument, so it forksdate +%sonce per local task (on top of the 3 marker stats). bin/fm-inactive-reconcile.sh:236 already passes reconcile_now for exactly this reason, and the lib accepts the parameter. On a 30-task fleet that is 30 extra process spawns per heartbeat snapshot, the same class of avoidable fork the previous round removed from fm_cache_marker_mtime. Resolve one epoch alongside SNAPSHOT_NOW (bin/fm-fleet-snapshot.sh:83) and pass it in; it also makes every task in a single snapshot measure its idle age against the same instant instead of a drifting clock.✅ **Test** - passed
✅ No issues found.
bash tests/fm-send-cache-stale-guard.test.sh— 12/12 pass (fail-open, fresh, refuse, --steer-stale override, TTL config override incl. blank/comment lines, TTL=0 disable, turn-ended fold, busy exemption, FM_SEND_INTERNAL/--fire-and-forget/--resolve-key exemptions)bash tests/fm-fleet-snapshot-view.test.sh— 23/23 pass, incl.test_cache_expiring_follows_configured_ttl(capped window, leading-zero TTL, dead-endpoint suppression)bash tests/fm-backlog-handoff.test.sh— ALL TESTS PASSED (covers the fm-backlog-handoff.sh internal-wake call site)Manual end-to-end CLI run against a scratch FM_HOME driving the realbin/fm-send.sh,bin/fm-fleet-snapshot.sh --json, andbin/fm-fleet-view.shbinaries; transcript captured to the evidence directory✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.