Repository navigation
feat(bin): add session handover at 250k tokens and helm takeover from an idle holder - #5
Merged
Merged
Conversation
…dle holder Two failures this closes. A session keeps working long past the point where it reasons well, because nothing measures that or offers a clean replacement. And a fresh session cannot take over from a holder that is alive but doing nothing: the lock tested liveness only, so a forked background window held the helm for hours while supervision stayed dead, and the only thing a new session could say was "another session holds the lock". The threshold is a flat 250,000 tokens, never a share of the context window: a percentage of a one-million-token window would park a session around 700,000, deep inside the degradation being avoided. Crossing it reports once and blocks nothing, because a stalled fleet is worse than a slower one. bin/fm-context-measure-lib.sh is the single owner of the measurement. The formula is lifted verbatim from the unlanded feat/context-budget-guardrail branch rather than re-derived, so the two converge on one owner when that parked work resumes; the verification record proves both produce the same number on a real transcript. The handover record points, it does not assert. Durable records win every disagreement with it, and the only content it carries is what exists nowhere else: the concrete next step and what each live worker is mid-way through. It lives in data/, never a temp directory. bin/fm-handover.sh release refuses until every open thread is backed by a durable record and every pointer still resolves, because once the outgoing session is gone a bad handover cannot be redone. It never stops a session, never touches unlanded work, and never drains the wake queue, so events queued during the gap survive for the replacement. Taking the helm needs two independent proofs, and a timer alone is never enough: measurable silence, from a turn-end activity marker that also watches the transcript so a long single turn reads as busy, and an unattended holder with no controlling terminal at all. An attended holder keeps the helm however long it has been quiet, and the refusal now names what holds it plus the one command that clears it. Session start leads with what waits on the captain and any released handover, because the answers that got re-asked were sitting hundreds of lines down. Answered decisions are searchable rather than preloaded: a preloaded list never shrinks and rebuilds the same wall of text, so startup carries one line and bin/fm-decided.sh search makes the lookup at the moment of asking cheap. It covers the decision logs already in data/ with no migration. Both list surfaces cap their output and say what they dropped; silent truncation would read as "nothing else is waiting". Not built here, deliberately: crewmate respawn, cross-provider handoff, and wedged agents that never end a turn.
…p only with a transcript
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
Close two failures the captain hit repeatedly: (1) a firstmate session keeps working long past the point where it reasons well, with nothing measuring that or offering a clean replacement; (2) a fresh session cannot take over when the previous holder is alive but idle - the session lock tested only liveness, so a forked background window held the helm for hours while supervision stayed dead, and a new session could only report 'another session holds the lock'. The captain also gets asked questions already answered, because the answers sat hundreds of lines down in the session-start digest.
Settled in a grill-with-docs session, so these are deliberate choices, not oversights:
Out of scope and not to be built speculatively: crewmate respawn, cross-provider quota handoff, and wedged agents that never end a turn.
ALREADY RULED ON AND APPLIED in the three fix commits on this branch (a5e9779, 29bcc86, 683d1fe) after a review gate found a real safety class. Treat all of this as deliberate and settled; a prior run's review already accepted the reasoning:
This is firstmate's own shared tracked material, so .agents/skills/firstmate-coding-guidelines applies: one owner per contract, AGENTS.md size discipline with only triggers and safety facts inline, one sentence per line in markdown, plain dashes never em dashes, shellcheck-clean bin scripts via bin/fm-lint.sh, bash 3.2 floor, and colocated tests in tests/.
A previous run of this pipeline reached its review step, applied three gate-fix rounds, and then its review agent exited 1 mid-re-review; custody of those commits was recovered with the guarded axi sync --recover. Locally verified at this head: bin/fm-lint.sh clean, bin/fm-doc-audience-check.sh ok, --check-coverage ok, and tests/fm-helm-takeover.test.sh, tests/fm-session-handover.test.sh, tests/fm-fleet-snapshot-view.test.sh and tests/fm-bearings-snapshot.test.sh all green.
What Changed
bin/fm-session-pulse.sh,bin/fm-context-measure-lib.sh) that measures the session transcript against a flat 250,000-token threshold and reports once without ever blocking, plus a captain-triggered handover lifecycle inbin/fm-handover.sh(prepare, check, release, consume) that writes an advisory pointer record underdata/and refuses release while any worker is unaccounted for.bin/fm-helm-lib.shandbin/fm-lock.shgrant a takeover only from a readable, pid-matchedstate/.helm-activitymarker and the transcript it names, atomically stamped and fail-closed, so an unmeasurable holder keeps the helm and gets a printed refusal with the clearing command.bin/fm-decided.shmakes decisions searchable behind one startup line,bin/fm-awaiting-captain.shlists held decisions and recorded PRs with capped output and an explicit marker when a read fails, and both it andbin/fm-fleet-snapshot.sh(~176 lines smaller) now consume the sharedbin/fm-backlog-record-lib.shmodel.Covered by new suites
tests/fm-helm-takeover.test.sh(18 cases) andtests/fm-session-handover.test.sh(29 cases) plus additions totests/fm-session-start.test.sh; the pipeline's test, lint, and document gates all passed, and review closed with informational notes only.Risk Assessment
Testing
Ran the six suites that own this change (fm-helm-takeover, fm-session-handover, fm-session-start, fm-fleet-snapshot-view, fm-bearings-snapshot) and all are green, then built an end-to-end captain walkthrough that drives the real scripts over a throwaway primary home so the behaviour is shown rather than asserted: the pulse reports a due handover once at 262,144 tokens against the flat 250,000 threshold and exits 0 both turns while stamping the activity marker; prepare refuses an unaccounted worker; check refuses a pointer emptied behind the record; release re-verifies after prepare passed, refuses a newly appeared task, leaves state/.lock and the wake queue untouched, then releases cleanly and reports the one queued wake; and acquisition from a fresh session refuses an attended holder, refuses with no marker even against a two-hour-old lock, refuses a marker naming a deleted transcript, and only transfers the helm against an unattended holder measurably silent for 5400s, writing the audit line and saying plainly the other session was not stopped. The replacement's first surface then shows the waiting handover, the captain's held decision, an UNREAD marker instead of an empty list for a record it cannot read, and one search surfacing the nine-day-old billing answer. This is a shell/CLI feature with no rendered UI, so the reviewer-visible artifact is the full CLI transcript rather than a screenshot. Worktree is clean and the demo temp homes were removed.
Evidence: End-to-end CLI transcript: handover lifecycle, helm takeover verdicts, awaiting block, answered-decision search
Evidence: The walkthrough script that produced the transcript (hermetic, throwaway home, real bin/ scripts)
Evidence: The 250,000-token notice, once, non-blocking
Evidence: The release refusal: re-verified after prepare passed, nothing discarded
Evidence: Fail-closed takeover: three refusals, then the one grant
Evidence: What the replacement sees first, and the failed read that never renders as absence
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-decided.sh:99-indexed=$(grep -c '^- \[' "$INDEX" 2>/dev/null || printf '0')double-counts the zero case:grep -calready prints0and then exits 1, so the||fallback appends a second0. Reproduced: with adata/decided.mdthat exists but holds no- [key]lines,indexedbecomes the two-line value0\n0andcmd_countprints a garbled digest line - a bare0on its own line followed by0 answered decision(s) indexed in data/decided.md, .... This is the single startup line the whole searchable-decisions design rests on, and it is whatbin/fm-awaiting-captain.sh:144prints at every session start. Reachable whenever the index exists with no entries (hand-created or hand-pruned - it is a local gitignored markdown record). Fix: drop the|| printf '0'and use|| true, or pipe throughhead -1. Note the sibling uses at fm-decided.sh:141 and fm-handover.sh:354 are safe only because both are guarded to a non-zero count.bin/fm-session-start.sh:342- A lock-refused (read-only) session is shown the released handover and told toconsumeit, andcmd_consume(bin/fm-handover.sh:392) has no helm-ownership check - unlikecmd_release, which routes throughfm-lock.sh release. Section 3b and the "HANDOVER FROM THE PREVIOUS SESSION" block at lines 337-343 are both unconditional, outside theREAD_ONLYbranch. Failing sequence: session A releases the helm; a second window C starts first, is refused the lock, prints the handover, and follows the printed instruction to runbin/fm-handover.sh consume;state/.handovergetsconsumed=; the session that actually takes the helm then starts,cmd_pendingreturns non-zero, and the digest reports nothing waiting - so the replacement never reads the record it was supposed to act on. This violates the invariant AGENTS.md states for a lock-refused session (it must not mutate durable session state) and defeats the surfacing half of the feature. Suggest gating either the consume instruction orcmd_consumeitself onfm_session_lock_owned_by_self, keeping the record printed in read-only mode but not consumable there.bin/fm-awaiting-captain.sh:130- "Recorded pull requests waiting to land" iterates everystate/*.metaand lists any recorded PR, with no local check of whether that PR already landed. A task's meta survives from merge untilbin/fm-teardown.sh:1229removes it, so a PR the captain already merged is reported back to him as still waiting to land - a false positive in the one block that exists to be short and always-actionable. This needs no forge call to fix:RECORDS_JSONis already computed a few lines above and carries each record'sstateandcompletion, so a locally-recordeddone/mergeditem could be filtered or labelled as landed. Flagging rather than changing it because the block's contents are a deliberate product decision.bin/fm-lock.sh:68-fm-lock.sh statusrunsholder_descriptionandfm_helm_takeover_allowedagainst the recorded holder without checking whether that holder is the calling session. The usual caller is the holder, so status now prints a takeover verdict about its own helm: "takeover: refused - it is attended on terminal ttys005", or, for an unattended session quiet past the threshold, "takeover: available" - which reads as an invitation to take the helm from itself. Suggest comparing the holder againstfm_harness_ancestry_pidand saying "this session holds it" instead of a takeover verdict when they match.bin/fm-helm-lib.sh:145-fm_helm_silence_secondsreturns a measurable silence from the marker's mtime alone when the marker records no transcript, so the "transcript grows during a turn" protection is absent on that path while the takeover stays enabled.fm_helm_stampwrites an emptytranscript=wheneverfm_context_payload_transcriptfails - notably whenjqis missing, since the pulse resolves the path before checking for jq's other uses. An unattended holder that is genuinely working through one turn longer thanFM_HELM_IDLE_TAKEOVER(1800s) would then measure as silent and lose the helm mid-turn, giving two sessions on one fleet - the harm the loud takeover notice warns about. Narrow (jq is a hard repo dependency, so a transcript is normally recorded) and it sits inside the settled evidence rules, so raising it rather than changing it: the strictly fail-closed reading would be to treat a marker with no usable transcript as unmeasurable.bin/fm-handover.sh:89-meta_fieldis a private meta reader with FIRST-wins semantics (sed -n "s/^$field=//p" | head -1), whilebin/fm-backlog-record-lib.sh:18-21namesfm_meta_getthe single owner of that read precisely because its LAST-wins tie-break matters for append-oriented meta files - and commit 29bcc86 consolidated the other caller onto it. No reachable failure today: the only rewriter ofkind=,bin/fm-promote.sh:44-45, strips every existing line before appending, sois_secondmatecan never see a duplicate key. Recording it as a divergence in a contract this branch otherwise unified, not as a live bug; nothing needs to change for correctness.🔧 Fix: gate the handover lifecycle on the helm and stamp only with a transcript
3 issues (2 warnings, 1 info) still open:
bin/fm-helm-lib.sh:204- The new gate is write-side only, so the failure it closes is still reachable through the reader.fm_helm_silence_secondssetsnewestfrom the marker's own mtime first (line 202) and only upgrades it from the transcript when[ -n "$transcript" ] && [ -f "$transcript" ]holds, so a marker whosetranscript=field is empty or names a file that no longer exists still yields a measurable silence from the marker mtime alone - exactly the marker-only measurement the fix and docs/session-handover.md:101-104 say cannot happen. The branch's own fixture proves the reader accepts it:tests/fm-helm-takeover.test.sh:349callsstamp_marker 7200with no transcript argument (writing a baretranscript=) andtest_takes_the_helm_from_a_silent_unattended_holderasserts the takeover is GRANTED. Two production paths reach the same state: (a) upgrading in place, sincestate/is not reset and any marker written by the pre-acc6007 stamp carries an empty transcript field; (b) the named transcript being deleted or moved after the last successful stamp (Claude Code's own transcript retention cleanup, a/clear, or a moved project directory). Combine either with an unattended holder working through one turn longer thanFM_HELM_IDLE_TAKEOVER(1800s) and the holder loses the helm mid-turn, giving two sessions on one fleet. The invariant "a marker always names a resolvable transcript" cannot be established at write time alone, because the marker is a persisted claim that outlives the file it names. Earliest supported shared boundary, in this same file and with no new owner: havefm_helm_silence_secondsreturn non-zero (unmeasurable) when the marker'stranscript=is empty or does not resolve, instead of falling back to the marker mtime - the write-side gate then stays as the cheap fast path rather than the only enforcement. Flagging rather than changing it because the commit states the single-definition-at-the-write choice deliberately.bin/fm-lock.sh:69-print_declination_notetakes the holder pid but never compares it against the pid recorded instate/.helm-activity-declined;fm_helm_declination_notereads whatever record is there. The record is cleared only by a successful stamp (bin/fm-helm-lib.sh:164) and by nothing on takeover,clear, orrelease, so it outlives the session that wrote it. Failing sequence: holder A's pulse cannot resolve a transcript and recordspid=A, reason=jq is unavailable...; A exits; session B acquires the now-free lock and never ends a turn, so it writes neither marker nor declination; session C attempts acquisition, is correctly refused because B's silence is unmeasurable, and then prints "no activity marker exists because pid A declined to stamp one at <stale time>: jq is unavailable" - a reason belonging to a dead session, on the exact surface requirement 1c added so the operator would not have to guess. An operator would go fix jq for a holder that has no such problem. Fix: pass the holder pid down and only print the note when the recorded pid matches, otherwise stay silent. The refusal outcome itself is unaffected.bin/fm-session-pulse.sh:90-fm_context_payload_transcriptalready rejects a path that is not a readable regular file, so the pulse passes an empty string in that case andfm_helm_stamp'selif [ ! -f "$transcript" ]branch (bin/fm-helm-lib.sh:142) is unreachable from the only production caller. Every real declination therefore reads "the turn-end payload carried no transcript path", even when the payload named one and the file was simply gone - which points a person debugging at the harness payload instead of at the missing transcript. docs/session-handover.md:102 advertises the three reasons as distinguishable, and only two ever occur in practice. Fix without adding a second rule: have the pulse handfm_helm_stampthe rawtranscript_pathfrom the payload and let the existence check (already the single owner of admissible evidence) produce the accurate reason.🔧 Fix: make the helm evidence read decide, not the stamp
1 info still open:
bin/fm-session-pulse.sh:108- The declination clear is keyed on[ -n "$TRANSCRIPT" ]rather than on whetherfm_helm_stampactually wrote, and the stamp's exit status is discarded on line 107. Sequence: turn 1 resolves no transcript, so a declination is recorded and the marker is written with an emptytranscript=; turn 2 resolves a transcript but the marker write fails (unwritable state dir, full disk), sofm_helm_stampreturns non-zero whilefm_helm_clear_declinationstill runs. The marker on disk is still turn 1's, so a later takeover attempt is correctly refused with "its activity marker names no transcript" - but the record that would have explained why is gone, losing exactly the discoverability requirement 1c added. Fix: gate the clear on the stamp succeeding (if fm_helm_stamp ...; then ... fi), leaving the previous explanation in place when this turn could not replace the marker. Diagnostics only - the refusal outcome is unaffected, and the underlying write failure is not something this script can recover from.✅ **Test** - passed
✅ No issues found.
bash tests/fm-helm-takeover.test.sh- 18 cases, all ok (attended refusal, lock mtime not evidence, empty/foreign/transcript-gone markers not evidence, atomic stamp, long-turn holder kept, granted takeover, clear/release/status)bash tests/fm-session-handover.test.sh- 29 cases, all ok (pulse once/re-arm/flat 250000/sidechain exclusion/worktree inertness/silent degradation/stamp only by helm holder, handover prepare-check-release-consume refusals, decided search + cap, awaiting-captain cap and failed-read marker)bash tests/fm-session-start.test.sh- 28 cases, all ok, including "session start leads with the handover and the captain's open items, and the helm transfers"bash tests/fm-fleet-snapshot-view.test.sh- 15 cases, all ok (fleet snapshot after the ~176-line reduction onto the shared record lib)bash tests/fm-bearings-snapshot.test.sh- 24 cases, all ok (captain-hold predicate through the same shared model)Manual end-to-end walkthrough:FM_DEMO_ROOT=$PWD bash handover-e2e-demo.sh- drives bin/fm-session-pulse.sh, bin/fm-handover.sh (prepare/check/release/consume), bin/fm-lock.sh (status/acquire/takeover), bin/fm-awaiting-captain.sh and bin/fm-decided.sh (count/search) over a throwaway primary home with real live holder pidsbin/fm-session-pulse.sh --claudefed a Stop payload naming a 262,144-token transcript: notice on turn 1, silence on turn 2, exit 0 both times, state/.helm-activity stampedbin/fm-lock.shas a fresh session against four holder states: attended, no marker, marker naming a deleted transcript, and unattended + 5400s silentbin/fm-handover.sh releasewith a newly appeared task and an emptied pointer, then again after both were fixed with a wake queuedbin/fm-awaiting-captain.shwith a captain hold, a blocked hold, a recorded PR, and the same PR meta at chmod 000git status --porcelain- worktree clean, demo temp homes removed✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.