Skip to content

feat(bin): add session handover at 250k tokens and helm takeover from an idle holder - #5

Merged
uayyagari merged 7 commits into
mainfrom
feat/session-handover
Aug 5, 2026
Merged

uayyagari merged 7 commits into
mainfrom
feat/session-handover

Conversation

@uayyagari

Copy link
Copy Markdown

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:

  • Threshold is a FLAT 250,000 tokens, never a percentage of the context window: a percentage of a 1M window would park a session at 700k, deep inside the degradation being avoided. Thinking-quality ceiling, not a capacity one.
  • Past the threshold firstmate KEEPS WORKING and reports once. The turn-end pulse never blocks and always exits 0, deliberately unlike bin/fm-turnend-guard.sh which does block.
  • The handover is CAPTAIN-TRIGGERED, never automatic; a watcher cannot respawn the interactive session in his terminal.
  • The handover record POINTS, it does not ASSERT: explicitly advisory, durable records win every conflict, carrying only the next step and each worker's mid-point, and living in data/ never a temp dir.
  • The release REFUSAL is the most important behaviour and re-verifies everything even right after prepare passed. Nothing is discarded, forced, or stashed, and the wake queue is never drained.
  • Answered decisions are SEARCHABLE, not preloaded, with one startup line; both list surfaces cap output and say what they dropped.
  • The context measurement is lifted VERBATIM from the parked feat/context-budget-guardrail branch so there is one owner rather than a second formula.
  • The single transcript pass is deliberately NOT optimized to a tail read: a tail window that cuts the only assistant entry degrades to unmeasurable and would silently disable the notice.
    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:

  • The takeover is now FAIL-CLOSED on evidence. state/.lock's mtime is deliberately NOT an evidence source, because it is written once at acquisition and nothing refreshes it, so it measures session AGE not quietness - a live busy holder measured as 7200s silent through it. Silence is measured only from a readable, non-empty, pid-matched state/.helm-activity and the transcript it names. No marker means UNMEASURABLE means the holder keeps the helm. The captain explicitly accepted the cost: a holder that cannot prove it is working keeps the helm, and the fallback is the printed refusal plus the one clearing command.
  • Consequence he accepted: on a primary harness that does not stamp the marker (every harness except claude today) an automatic takeover simply never happens. Giving those harnesses the stamp is a SEPARATE follow-up slice he has filed; it is deliberately NOT in this branch, and neither is adopting fm_pid_identity for the session lock.
  • The activity stamp is atomic (temp file plus mv) because a truncating redirect left the marker zero-length for the width of a fork, and an empty marker reads as "cannot prove it is working" - a takeover decided on a race.
  • bin/fm-backlog-record-lib.sh is a deliberate extraction so the captain-hold predicate and the recorded-PR read have ONE owner. bin/fm-fleet-snapshot.sh shrank by ~176 lines because it now consumes that shared model rather than carrying its own copy; bin/fm-awaiting-captain.sh consumes it instead of a second inline awk. fm_recorded_pr calls fm_meta_get on purpose to keep the owner's last-wins semantics.
  • In bin/fm-awaiting-captain.sh, "a failed read must never render as absence" is a deliberate FILE-WIDE property: an unreadable record source or meta prints an explicit marker rather than an empty list, because a silent empty result reads as "nothing is waiting".
  • live_ids in bin/fm-handover.sh treats "has a state/*.meta" as a live worker deliberately, erring toward demanding more accounting rather than less.

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

  • Added a turn-end context pulse (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 in bin/fm-handover.sh (prepare, check, release, consume) that writes an advisory pointer record under data/ and refuses release while any worker is unaccounted for.
  • Made the session lock evidence-driven instead of liveness-only: bin/fm-helm-lib.sh and bin/fm-lock.sh grant a takeover only from a readable, pid-matched state/.helm-activity marker 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.
  • Surfaced answered work at session start: bin/fm-decided.sh makes decisions searchable behind one startup line, bin/fm-awaiting-captain.sh lists held decisions and recorded PRs with capped output and an explicit marker when a read fails, and both it and bin/fm-fleet-snapshot.sh (~176 lines smaller) now consume the shared bin/fm-backlog-record-lib.sh model.

Covered by new suites tests/fm-helm-takeover.test.sh (18 cases) and tests/fm-session-handover.test.sh (29 cases) plus additions to tests/fm-session-start.test.sh; the pipeline's test, lint, and document gates all passed, and review closed with informational notes only.

Risk Assessment

⚠️ Medium: The helm evidence rule is now enforced on the read side with failure-mode tests that bypass the stamp and with the docs corrected, leaving only one diagnostics-level follow-up; medium rather than low because the branch is broad and changes who may hold the fleet session lock, and three prior rounds show this surface is subtle.

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
=== firstmate session handover, end to end ===
home: (throwaway)  outgoing session pid: 79549  replacement pid: 79550

1. The outgoing session takes the helm.

$ bin/fm-lock.sh status
lock: held by live harness pid 79549
holder: pid 79549 (claude), terminal ?? (unattended), no recorded activity
takeover: not applicable - this session holds the helm

2. Its turn ends past 250,000 tokens. The pulse reports ONCE and never blocks.

$ echo "$stop_payload" | bin/fm-session-pulse.sh --claude   # turn 1
{
  "systemMessage": "firstmate handover due: this session measures 262144 tokens, over the 250000 threshold, so it is past the point where it reasons well. Keep working - nothing is blocked - and tell the captain a handover is due. Load the handover skill to prepare and verify one; the captain runs the one command it prints."
}
exit=0

$ echo "$stop_payload" | bin/fm-session-pulse.sh --claude   # turn 2: no nagging
(no output above)  exit=0

$ cat state/.helm-activity   # the turn end also stamped the activity marker
pid=79549
epoch=1785902849
transcript=<tmp>/session.jsonl

3. A live worker appears, so prepare REFUSES until it is accounted for.

$ bin/fm-handover.sh prepare --next "land the pulse slice"
fm-handover: refusing to prepare - these live workers have no --worker note:
  beta-task (what is it mid-way through?)
exit=1

4. With the worker noted and its thread durably recorded, prepare writes the record.

$ bin/fm-handover.sh prepare --next "..." --worker beta-task=... --record data/captain.md=...
handover prepared: data/handover.md
handover check: complete - a release is allowed
exit=0

$ cat data/handover.md
# Handover - prepared 2026-08-05T09:37:29+0530

ADVISORY, NOT AUTHORITATIVE.
This was written by a session past its thinking-quality threshold, so the durable
records below win on every disagreement with it. Where this file and a record
differ, the record is right and this file is stale. Do not act on a claim here
that a record does not also support.

Next step: land the pulse slice, then re-read data/backlog.md

## Live work - what each worker is mid-way through

- worker beta-task: mid-way through the awaiting-captain block; tests written, none run

## Records to read

- record data/backlog.md - the durable queue: what is under way, queued, and on hold
- record data/captain.md - the captain's preferences and working style - read before reporting anything to them
- record data/stripe-decision-log.md - the billing answers already settled

## Deliberately not carried

Live fleet state is absent on purpose: run bin/fm-session-start.sh, which prints
it fresh and is authoritative. Reconcile anything above against that digest
before acting on it.

5. The pointer is then emptied behind the record. check REFUSES.

$ bin/fm-handover.sh check
handover check: INCOMPLETE - a release is refused until every line below is fixed
MISSING: the record points at data/stripe-decision-log.md, which is empty
exit=1

6. release re-verifies everything even though prepare passed, and refuses.

$ bin/fm-handover.sh release   # a task appeared AND the pointer is still empty
fm-handover: REFUSING to release the helm - the handover is incomplete.
MISSING: live worker gamma-task has no note saying what it is mid-way through
MISSING: live worker gamma-task has no backlog item, so its thread is not durably recorded
MISSING: the record points at data/stripe-decision-log.md, which is empty
Nothing was released and nothing was discarded. Fix each line above, then run "fm-handover.sh release" again.
exit=1

$ cat state/.lock   # a refused release keeps the helm, discards nothing
79549

7. Both problems fixed, and a wake is queued. release frees the helm and reports the gap.

$ bin/fm-handover.sh release
lock released: this session no longer holds the helm
handover released: data/handover.md
queued notifications waiting for the replacement: 1 (none were dropped)
This session is now read-only: it must not spawn, steer, merge, or repair fleet state.
Start the replacement, which will pick this up at session start.
exit=0

$ cat state/.wake-queue   # the queue was never drained
wake=beta-task reason=review-ready

8. Now the other failure: a fresh session against a holder that is alive but idle.

$ bin/fm-lock.sh   # holder is at a terminal: the captain is using it
error: another live firstmate session holds the lock (pid 79549); operate read-only until resolved
holder: pid 79549 (claude), terminal ttys005 (attended), last sign of work 0s ago (marker)
refused to take the helm: it is attended on terminal ttys005
clear it with: /Users/uayyagari/.no-mistakes/worktrees/c5d69c01912a/01KZ7Y1JVY5Q0Y0EVXKSA1361Y/bin/fm-lock.sh clear --pid 79549
  That drops the recorded helm without touching the other session, so quit that session too.
exit=1

9. Unattended, but with no proof it is working: fail-closed, the holder keeps the helm.

$ bin/fm-lock.sh   # the 2-hour-old lock is NOT evidence
error: another live firstmate session holds the lock (pid 79549); operate read-only until resolved
holder: pid 79549 (claude), terminal ?? (unattended), no recorded activity
refused to take the helm: it has not proved it is doing any work (no readable turn-end activity marker of its own), so it keeps the helm
clear it with: /Users/uayyagari/.no-mistakes/worktrees/c5d69c01912a/01KZ7Y1JVY5Q0Y0EVXKSA1361Y/bin/fm-lock.sh clear --pid 79549
  That drops the recorded helm without touching the other session, so quit that session too.
exit=1

10. A marker that names a transcript now gone is not evidence either.

$ bin/fm-lock.sh
error: another live firstmate session holds the lock (pid 79549); operate read-only until resolved
holder: pid 79549 (claude), terminal ?? (unattended), no recorded activity
refused to take the helm: it has not proved it is doing any work (its activity marker names the transcript /var/folders/vr/_90lw3_s0bs_nw2f7b6t9yrm0000gn/T//fm-handover-demo.XxvJ2M/gone.jsonl, which no longer exists), so it keeps the helm
clear it with: /Users/uayyagari/.no-mistakes/worktrees/c5d69c01912a/01KZ7Y1JVY5Q0Y0EVXKSA1361Y/bin/fm-lock.sh clear --pid 79549
  That drops the recorded helm without touching the other session, so quit that session too.
exit=1

11. Positive evidence, and it is old: unattended + measurably silent. The helm transfers.

$ bin/fm-lock.sh
lock acquired: harness pid 79550
HELM TAKEN OVER: pid 79549 held it and it has no terminal and has been silent for 5400s (threshold 1800s, newest evidence: marker).
That session was NOT stopped. Quit it if it is still open, so two sessions do not work the same fleet.
exit=0

$ cat state/.helm-takeover   # auditable
helm-takeover 2026-08-05T09:37:30+0530 from=79549 to=79550 reason=it has no terminal and has been silent for 5400s (threshold 1800s, newest evidence: marker)

12. What the replacement sees first: the short awaiting-captain block.

$ bin/fm-awaiting-captain.sh
HANDOVER WAITING: a previous session prepared and released one. Read data/handover.md,
  reconcile it against the durable records it points at, then run bin/fm-handover.sh consume.
Decisions held for you:
- pricing-tiers - keep the annual discount?
Recorded pull requests waiting to land (recorded locally, not verified against the forge):
- https://github.com/x/y/pull/42 (beta-task, recorded in meta)
0 answered decision(s) indexed in data/decided.md, plus 1 decision log(s) in data.
Search before escalating anything: bin/fm-decided.sh search <terms>
The captain's standing preferences are in data/captain.md - read them before reporting anything.
exit=0

12b. A record it cannot read is NAMED, never rendered as nothing waiting.

$ chmod 000 state/beta-task.meta; bin/fm-awaiting-captain.sh
HANDOVER WAITING: a previous session prepared and released one. Read data/handover.md,
  reconcile it against the durable records it points at, then run bin/fm-handover.sh consume.
Decisions held for you:
- pricing-tiers - keep the annual discount?
Recorded pull requests waiting to land (recorded locally, not verified against the forge):
- beta-task: UNREAD - its records could not be read, so whether it has a pull request waiting is unknown, not no
0 answered decision(s) indexed in data/decided.md, plus 1 decision log(s) in data.
Search before escalating anything: bin/fm-decided.sh search <terms>
The captain's standing preferences are in data/captain.md - read them before reporting anything.
exit=0

13. And the answered question it would otherwise escalate again.

$ bin/fm-decided.sh count
0 answered decision(s) indexed in data/decided.md, plus 1 decision log(s) in data.
Search before escalating anything: bin/fm-decided.sh search <terms>

$ bin/fm-decided.sh search "duplicate customer"
data/stripe-decision-log.md:3:**D35. Leave the existing duplicate customer records alone.** Stripe cannot merge customers; dedupe at write time only. 2026-07-29.
exit=0

14. And the handover the outgoing session left, consumed by the session that now holds the helm.

$ bin/fm-handover.sh consume
handover picked up. Records it expects you to have read:
  data/backlog.md
  data/captain.md
  data/stripe-decision-log.md
exit=0

=== end ===
Evidence: The walkthrough script that produced the transcript (hermetic, throwaway home, real bin/ scripts)
#!/usr/bin/env bash
# End-to-end walkthrough of the session-handover feature as the captain meets it.
# Drives the real bin/ scripts over a throwaway primary-shaped home.
# ps is faked so the harness ancestry and the controlling terminal are controlled;
# holder pids are real live processes, so every liveness check is genuine.
set -u

ROOT=${FM_DEMO_ROOT:?set FM_DEMO_ROOT to the firstmate checkout}
WORK=$(mktemp -d "${TMPDIR:-/tmp}/fm-handover-demo.XXXXXX")
HOME_DIR="$WORK/home"
FAKEBIN="$WORK/fakebin"
BG=()
cleanup() { local p; for p in "${BG[@]:-}"; do [ -n "$p" ] && kill "$p" 2>/dev/null; done; rm -rf "$WORK"; }
trap cleanup EXIT

mkdir -p "$HOME_DIR/state" "$HOME_DIR/data" "$HOME_DIR/bin" "$FAKEBIN"
git init -q "$HOME_DIR"; git -C "$HOME_DIR" commit -q --allow-empty -m init
: > "$HOME_DIR/AGENTS.md"
printf '# Backlog\n\n## In flight\n' > "$HOME_DIR/data/backlog.md"
printf 'Report format: one line, no mechanics.\n' > "$HOME_DIR/data/captain.md"
printf '# Stripe decisions\n\n**D35. Leave the existing duplicate customer records alone.** Stripe cannot merge customers; dedupe at write time only. 2026-07-29.\n' \
  > "$HOME_DIR/data/stripe-decision-log.md"

start_proc() { sleep 600 >/dev/null 2>&1 & PROC_PID=$!; BG+=("$PROC_PID"); }
start_proc; OLD_PID=$PROC_PID     # the outgoing session
start_proc; NEW_PID=$PROC_PID     # the replacement session

cat > "$FAKEBIN/ps" <<SH
#!/usr/bin/env bash
set -u
pid=""; prev=""
for arg in "\$@"; do [ "\$prev" = "-p" ] && pid="\$arg"; prev="\$arg"; done
case "\$*" in
  *"tty="*) if [ -f "$FAKEBIN/.tty-\$pid" ]; then cat "$FAKEBIN/.tty-\$pid"; else printf '??\n'; fi; exit 0 ;;
  *"comm="*) case "\$pid" in $OLD_PID|$NEW_PID) printf '/usr/local/bin/claude\n' ;; *) printf '/bin/zsh\n' ;; esac; exit 0 ;;
  *"args="*) case "\$pid" in $OLD_PID|$NEW_PID) printf 'claude\n' ;; *) printf 'zsh\n' ;; esac; exit 0 ;;
  *"ppid="*) case "\$pid" in $OLD_PID) printf '1\n' ;; $NEW_PID) printf '1\n' ;; *) printf '%s\n' "\$FM_DEMO_SESSION" ;; esac; exit 0 ;;
esac
exit 1
SH
chmod +x "$FAKEBIN/ps"

backdate() {
  local f=$1 secs=$2 stamp
  stamp=$(date -v-"${secs}"S +%Y%m%d%H%M.%S 2>/dev/null) || stamp=$(date -d "-${secs} seconds" +%Y%m%d%H%M.%S)
  touch -t "$stamp" "$f"
}

# as <session-pid> <script> [args...]: run a real script as that session.
as() {
  local pid=$1; shift
  env PATH="$FAKEBIN:$PATH" FM_DEMO_SESSION="$pid" FM_ROOT_OVERRIDE="$HOME_DIR" \
    bash "$ROOT/bin/$@" 2>&1
}
say() { printf '\n\033[1m%s\033[0m\n' "$*"; }
run() { printf '\n$ %s\n' "$*"; }

# One assistant transcript line whose four usage fields sum to $2.
transcript() {
  printf '{"type":"assistant","isSidechain":false,"requestId":"r1","message":{"usage":{"input_tokens":2,"cache_creation_input_tokens":8,"cache_read_input_tokens":%s,"output_tokens":10}}}\n' \
    "$(( $2 - 20 ))" > "$1"
}

printf '=== firstmate session handover, end to end ===\n'
printf 'home: (throwaway)  outgoing session pid: %s  replacement pid: %s\n' "$OLD_PID" "$NEW_PID"

say '1. The outgoing session takes the helm.'
printf '%s\n' "$OLD_PID" > "$HOME_DIR/state/.lock"
run 'bin/fm-lock.sh status'
as "$OLD_PID" fm-lock.sh status

say '2. Its turn ends past 250,000 tokens. The pulse reports ONCE and never blocks.'
transcript "$WORK/session.jsonl" 262144
run 'echo "$stop_payload" | bin/fm-session-pulse.sh --claude   # turn 1'
printf '{"session_id":"sess-old","stop_hook_active":false,"transcript_path":"%s"}' "$WORK/session.jsonl" \
  | env PATH="$FAKEBIN:$PATH" FM_DEMO_SESSION="$OLD_PID" CLAUDECODE=1 FM_ROOT_OVERRIDE="$HOME_DIR" \
    bash "$ROOT/bin/fm-session-pulse.sh" --claude 2>&1
printf 'exit=%s\n' "$?"
run 'echo "$stop_payload" | bin/fm-session-pulse.sh --claude   # turn 2: no nagging'
printf '{"session_id":"sess-old","stop_hook_active":false,"transcript_path":"%s"}' "$WORK/session.jsonl" \
  | env PATH="$FAKEBIN:$PATH" FM_DEMO_SESSION="$OLD_PID" CLAUDECODE=1 FM_ROOT_OVERRIDE="$HOME_DIR" \
    bash "$ROOT/bin/fm-session-pulse.sh" --claude 2>&1
printf '(no output above)  exit=%s\n' "$?"
run 'cat state/.helm-activity   # the turn end also stamped the activity marker'
sed -e 's|/.*/|<tmp>/|' "$HOME_DIR/state/.helm-activity"

say '3. A live worker appears, so prepare REFUSES until it is accounted for.'
printf 'window=fm:beta-task\nworktree=%s/wt-beta\nproject=alpha\n' "$HOME_DIR" > "$HOME_DIR/state/beta-task.meta"
run 'bin/fm-handover.sh prepare --next "land the pulse slice"'
as "$OLD_PID" fm-handover.sh prepare --next "land the pulse slice"
printf 'exit=%s\n' "$?"

say '4. With the worker noted and its thread durably recorded, prepare writes the record.'
printf -- '- [ ] beta-task - the awaiting block (repo: alpha) (kind: ship)\n' >> "$HOME_DIR/data/backlog.md"
run 'bin/fm-handover.sh prepare --next "..." --worker beta-task=... --record data/captain.md=...'
as "$OLD_PID" fm-handover.sh prepare \
  --next "land the pulse slice, then re-read data/backlog.md" \
  --worker "beta-task=mid-way through the awaiting-captain block; tests written, none run" \
  --record "data/stripe-decision-log.md=the billing answers already settled"
printf 'exit=%s\n' "$?"
run 'cat data/handover.md'
sed -e "s|$HOME_DIR|<home>|g" "$HOME_DIR/data/handover.md"

say '5. The pointer is then emptied behind the record. check REFUSES.'
: > "$HOME_DIR/data/stripe-decision-log.md"
run 'bin/fm-handover.sh check'
as "$OLD_PID" fm-handover.sh check
printf 'exit=%s\n' "$?"

say '6. release re-verifies everything even though prepare passed, and refuses.'
printf 'window=fm:gamma-task\nworktree=%s/wt-gamma\nproject=alpha\n' "$HOME_DIR" > "$HOME_DIR/state/gamma-task.meta"
run 'bin/fm-handover.sh release   # a task appeared AND the pointer is still empty'
as "$OLD_PID" fm-handover.sh release
printf 'exit=%s\n' "$?"
run 'cat state/.lock   # a refused release keeps the helm, discards nothing'
cat "$HOME_DIR/state/.lock"

say '7. Both problems fixed, and a wake is queued. release frees the helm and reports the gap.'
printf '# Stripe decisions\n\n**D35. Leave the existing duplicate customer records alone.** Stripe cannot merge customers; dedupe at write time only. 2026-07-29.\n' \
  > "$HOME_DIR/data/stripe-decision-log.md"
rm -f "$HOME_DIR/state/gamma-task.meta"
printf 'wake=beta-task reason=review-ready\n' > "$HOME_DIR/state/.wake-queue"
run 'bin/fm-handover.sh release'
as "$OLD_PID" fm-handover.sh release
printf 'exit=%s\n' "$?"
run 'cat state/.wake-queue   # the queue was never drained'
cat "$HOME_DIR/state/.wake-queue"

say '8. Now the other failure: a fresh session against a holder that is alive but idle.'
printf '%s\n' "$OLD_PID" > "$HOME_DIR/state/.lock"
printf 'ttys005\n' > "$FAKEBIN/.tty-$OLD_PID"
backdate "$HOME_DIR/state/.lock" 7200
run 'bin/fm-lock.sh   # holder is at a terminal: the captain is using it'
as "$NEW_PID" fm-lock.sh
printf 'exit=%s\n' "$?"

say '9. Unattended, but with no proof it is working: fail-closed, the holder keeps the helm.'
rm -f "$FAKEBIN/.tty-$OLD_PID" "$HOME_DIR/state/.helm-activity"
run 'bin/fm-lock.sh   # the 2-hour-old lock is NOT evidence'
as "$NEW_PID" fm-lock.sh
printf 'exit=%s\n' "$?"

say '10. A marker that names a transcript now gone is not evidence either.'
{ printf 'pid=%s\n' "$OLD_PID"; printf 'epoch=%s\n' "$(date +%s)"; printf 'transcript=%s\n' "$WORK/gone.jsonl"; } \
  > "$HOME_DIR/state/.helm-activity"
backdate "$HOME_DIR/state/.helm-activity" 5400
run 'bin/fm-lock.sh'
as "$NEW_PID" fm-lock.sh
printf 'exit=%s\n' "$?"

say '11. Positive evidence, and it is old: unattended + measurably silent. The helm transfers.'
printf 'a completed turn\n' > "$WORK/old-session.jsonl"
{ printf 'pid=%s\n' "$OLD_PID"; printf 'epoch=%s\n' "$(date +%s)"; printf 'transcript=%s\n' "$WORK/old-session.jsonl"; } \
  > "$HOME_DIR/state/.helm-activity"
backdate "$HOME_DIR/state/.helm-activity" 5400
backdate "$WORK/old-session.jsonl" 5400
run 'bin/fm-lock.sh'
as "$NEW_PID" fm-lock.sh
printf 'exit=%s\n' "$?"
run 'cat state/.helm-takeover   # auditable'
sed -e "s|$WORK|<tmp>|g" "$HOME_DIR/state/.helm-takeover"

say '12. What the replacement sees first: the short awaiting-captain block.'
{
  printf '## Queued\n'
  printf -- '- [ ] pricing-tiers - keep the annual discount? (repo: alpha) (kind: captain) (hold: captain grill first) (hold-kind: captain)\n'
  printf -- '- [ ] blocked-hold - waiting on other work (repo: alpha) (kind: captain) (hold: needs the migration) (hold-kind: captain) blocked-by: beta-task\n'
} >> "$HOME_DIR/data/backlog.md"
printf 'window=fm:beta-task\npr=https://github.com/x/y/pull/42\n' > "$HOME_DIR/state/beta-task.meta"
run 'bin/fm-awaiting-captain.sh'
as "$NEW_PID" fm-awaiting-captain.sh
printf 'exit=%s\n' "$?"

say '12b. A record it cannot read is NAMED, never rendered as nothing waiting.'
chmod 000 "$HOME_DIR/state/beta-task.meta"
run 'chmod 000 state/beta-task.meta; bin/fm-awaiting-captain.sh'
as "$NEW_PID" fm-awaiting-captain.sh
printf 'exit=%s\n' "$?"
chmod 600 "$HOME_DIR/state/beta-task.meta"

say '13. And the answered question it would otherwise escalate again.'
run 'bin/fm-decided.sh count'
as "$NEW_PID" fm-decided.sh count
run 'bin/fm-decided.sh search "duplicate customer"'
as "$NEW_PID" fm-decided.sh search "duplicate customer"
printf 'exit=%s\n' "$?"

say '14. And the handover the outgoing session left, consumed by the session that now holds the helm.'
run 'bin/fm-handover.sh consume'
as "$NEW_PID" fm-handover.sh consume
printf 'exit=%s\n' "$?"

printf '\n=== end ===\n'
Evidence: The 250,000-token notice, once, non-blocking
$ echo "$stop_payload" | bin/fm-session-pulse.sh --claude # turn 1
{
"systemMessage": "firstmate handover due: this session measures 262144 tokens, over the 250000 threshold, so it is past the point where it reasons well. Keep working - nothing is blocked - and tell the captain a handover is due. Load the handover skill to prepare and verify one; the captain runs the one command it prints."
}
exit=0

$ echo "$stop_payload" | bin/fm-session-pulse.sh --claude # turn 2: no nagging
(no output above) exit=0

$ cat state/.helm-activity # the turn end also stamped the activity marker
pid=79549
epoch=1785902849
transcript=<tmp>/session.jsonl
Evidence: The release refusal: re-verified after prepare passed, nothing discarded
$ bin/fm-handover.sh release # a task appeared AND the pointer is still empty
fm-handover: REFUSING to release the helm - the handover is incomplete.
MISSING: live worker gamma-task has no note saying what it is mid-way through
MISSING: live worker gamma-task has no backlog item, so its thread is not durably recorded
MISSING: the record points at data/stripe-decision-log.md, which is empty
Nothing was released and nothing was discarded. Fix each line above, then run "fm-handover.sh release" again.
exit=1

$ cat state/.lock # a refused release keeps the helm
79549

$ bin/fm-handover.sh release # both fixed
lock released: this session no longer holds the helm
handover released: data/handover.md
queued notifications waiting for the replacement: 1 (none were dropped)

$ cat state/.wake-queue # the queue was never drained
wake=beta-task reason=review-ready
Evidence: Fail-closed takeover: three refusals, then the one grant
# holder at a terminal
refused to take the helm: it is attended on terminal ttys005
clear it with: .../bin/fm-lock.sh clear --pid 79549

# unattended, no marker, lock backdated 7200s
refused to take the helm: it has not proved it is doing any work (no readable turn-end activity marker of its own), so it keeps the helm

# marker naming a transcript that is gone
refused to take the helm: it has not proved it is doing any work (its activity marker names the transcript <tmp>/gone.jsonl, which no longer exists), so it keeps the helm

# unattended + measurably silent 5400s
lock acquired: harness pid 79550
HELM TAKEN OVER: pid 79549 held it and it has no terminal and has been silent for 5400s (threshold 1800s, newest evidence: marker).
That session was NOT stopped. Quit it if it is still open, so two sessions do not work the same fleet.

$ cat state/.helm-takeover
helm-takeover 2026-08-05T09:37:30+0530 from=79549 to=79550 reason=it has no terminal and has been silent for 5400s (threshold 1800s, newest evidence: marker)
Evidence: What the replacement sees first, and the failed read that never renders as absence
$ bin/fm-awaiting-captain.sh
HANDOVER WAITING: a previous session prepared and released one. Read data/handover.md,
reconcile it against the durable records it points at, then run bin/fm-handover.sh consume.
Decisions held for you:
- pricing-tiers - keep the annual discount?
Recorded pull requests waiting to land (recorded locally, not verified against the forge):
- https://github.com/x/y/pull/42 (beta-task, recorded in meta)
0 answered decision(s) indexed in data/decided.md, plus 1 decision log(s) in data.
Search before escalating anything: bin/fm-decided.sh search <terms>
The captain's standing preferences are in data/captain.md - read them before reporting anything.

$ chmod 000 state/beta-task.meta; bin/fm-awaiting-captain.sh
- beta-task: UNREAD - its records could not be read, so whether it has a pull request waiting is unknown, not no

$ bin/fm-decided.sh search "duplicate customer"
data/stripe-decision-log.md:3:**D35. Leave the existing duplicate customer records alone.** Stripe cannot merge customers; dedupe at write time only. 2026-07-29.

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • ⚠️ bin/fm-decided.sh:99 - indexed=$(grep -c &#39;^- \[&#39; &#34;$INDEX&#34; 2&gt;/dev/null || printf &#39;0&#39;) double-counts the zero case: grep -c already prints 0 and then exits 1, so the || fallback appends a second 0. Reproduced: with a data/decided.md that exists but holds no - [key] lines, indexed becomes the two-line value 0\n0 and cmd_count prints a garbled digest line - a bare 0 on its own line followed by 0 answered decision(s) indexed in data/decided.md, .... This is the single startup line the whole searchable-decisions design rests on, and it is what bin/fm-awaiting-captain.sh:144 prints 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 &#39;0&#39; and use || true, or pipe through head -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 to consume it, and cmd_consume (bin/fm-handover.sh:392) has no helm-ownership check - unlike cmd_release, which routes through fm-lock.sh release. Section 3b and the "HANDOVER FROM THE PREVIOUS SESSION" block at lines 337-343 are both unconditional, outside the READ_ONLY branch. 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 run bin/fm-handover.sh consume; state/.handover gets consumed=; the session that actually takes the helm then starts, cmd_pending returns 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 or cmd_consume itself on fm_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 every state/*.meta and lists any recorded PR, with no local check of whether that PR already landed. A task's meta survives from merge until bin/fm-teardown.sh:1229 removes 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_JSON is already computed a few lines above and carries each record's state and completion, so a locally-recorded done/merged item 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 status runs holder_description and fm_helm_takeover_allowed against 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 against fm_harness_ancestry_pid and saying "this session holds it" instead of a takeover verdict when they match.
  • ℹ️ bin/fm-helm-lib.sh:145 - fm_helm_silence_seconds returns 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_stamp writes an empty transcript= whenever fm_context_payload_transcript fails - notably when jq is 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 than FM_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_field is a private meta reader with FIRST-wins semantics (sed -n &#34;s/^$field=//p&#34; | head -1), while bin/fm-backlog-record-lib.sh:18-21 names fm_meta_get the 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 of kind=, bin/fm-promote.sh:44-45, strips every existing line before appending, so is_secondmate can 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_seconds sets newest from the marker's own mtime first (line 202) and only upgrades it from the transcript when [ -n &#34;$transcript&#34; ] &amp;&amp; [ -f &#34;$transcript&#34; ] holds, so a marker whose transcript= 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:349 calls stamp_marker 7200 with no transcript argument (writing a bare transcript=) and test_takes_the_helm_from_a_silent_unattended_holder asserts the takeover is GRANTED. Two production paths reach the same state: (a) upgrading in place, since state/ 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 than FM_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: have fm_helm_silence_seconds return non-zero (unmeasurable) when the marker's transcript= 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_note takes the holder pid but never compares it against the pid recorded in state/.helm-activity-declined; fm_helm_declination_note reads 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, or release, so it outlives the session that wrote it. Failing sequence: holder A's pulse cannot resolve a transcript and records pid=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_transcript already rejects a path that is not a readable regular file, so the pulse passes an empty string in that case and fm_helm_stamp's elif [ ! -f &#34;$transcript&#34; ] 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 hand fm_helm_stamp the raw transcript_path from 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 &#34;$TRANSCRIPT&#34; ] rather than on whether fm_helm_stamp actually 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 empty transcript=; turn 2 resolves a transcript but the marker write fails (unwritable state dir, full disk), so fm_helm_stamp returns non-zero while fm_helm_clear_declination still 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 pids
  • bin/fm-session-pulse.sh --claude fed a Stop payload naming a 262,144-token transcript: notice on turn 1, silence on turn 2, exit 0 both times, state/.helm-activity stamped
  • bin/fm-lock.sh as a fresh session against four holder states: attended, no marker, marker naming a deleted transcript, and unattended + 5400s silent
  • bin/fm-handover.sh release with a newly appeared task and an emptied pointer, then again after both were fixed with a wake queued
  • bin/fm-awaiting-captain.sh with a captain hold, a blocked hold, a recorded PR, and the same PR meta at chmod 000
  • git status --porcelain - worktree clean, demo temp homes removed
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant