Skip to content

feat(bin): automatically refresh Claude primary sessions at a context-token budget - #2606

Open
Parsunic wants to merge 3 commits into
kunchenguid:mainfrom
Parsunic:fm/fm-context-restart-handoff
Open

Parsunic wants to merge 3 commits into
kunchenguid:mainfrom
Parsunic:fm/fm-context-restart-handoff

Conversation

@Parsunic

Copy link
Copy Markdown

Intent

Build automatic context refresh for Firstmate primary sessions, initially Claude Code. At a configurable completed-turn threshold defaulting to about 400,000 tokens, emit one durable handoff directive, run the existing stow-equivalent persistence contract, exit cleanly, release only the exiting session's lock, and automatically start a fresh session that resumes work solely from the native session-start digest rather than restoring prior conversation content. Configuration must reject malformed or unsafe files instead of guessing. Compose with existing synchronous Stop guards and asynchronous watcher behavior without changing under-threshold behavior or spending model tokens there. Document that unsupported primary harnesses are graceful no-ops and that plain Claude launch is a manual fallback. Add deterministic colocated tests plus opt-in live Claude evidence, commit the change, and deliver it through no-mistakes to a fork PR. The selected successor design is a terminal-parent wrapper rather than hook-driven relaunch because a Stop hook cannot safely own the terminal or avoid overlapping the old lock owner; Claude secondmates use the same wrapper after guarded sync, and an older unsynced home retains its existing plain-Claude launch. Token accounting uses the latest valid assistant transcript usage, and a fresh successor receives only one typed instruction to reconcile its new native startup digest.

What Changed

  • Added a third Claude Stop hook, bin/fm-context-restart-claude-hook.sh (registered in .claude/settings.json), that reads the latest assistant usage from the transcript and, when context tokens cross the validated config/context-restart-budget (bootstrap materializes a 400,000-token default on primary homes and rejects malformed or unsafe files), publishes a durable crossing record and emits exactly one typed context-refresh directive to run /stow and then bin/fm-context-restart.sh handoff; under threshold it stays silent and spends no tokens.
  • Added a terminal-parent wrapper bin/fm-primary.sh plus bin/fm-context-restart.sh and bin/fm-context-restart-lib.sh: after the reset-safe ready sentinel carries the wrapper's private token, the handoff verifies lock ownership, terminates the exiting Claude session, releases only that dead owner's session lock, and relaunches a fresh session in the same terminal with a single typed instruction to resume from the native session-start digest; without the wrapper the handoff stays durable and returns a manual exit-and-relaunch fallback.
  • Wired the feature through the fleet: context-restart-budget joins the inheritable config set with strict source/destination validation in bin/fm-config-inherit-lib.sh, bin/fm-spawn.sh launches Claude secondmates through the wrapper while unsynced older homes fall back to plain Claude with a warning, and the flow is covered by deterministic tests (tests/fm-context-restart.test.sh, harness and bootstrap test updates), an opt-in live Claude e2e (tests/fm-context-restart-claude-live-e2e.test.sh), and new docs/context-refresh.md documentation.

Risk Assessment

✅ Low: The fix round consists of three small, surgical corrections that were each verified against the current code (lock inventory now matches the real on-disk path, usage output includes the syntax line, and the registration test keeps only the semantic jq assertion), and a full re-pass over the feature diff confirmed intent conformance with no new reachable defects.

Testing

Ran the new deterministic context-restart suite plus the four modified adjacent suites (operational-input, turn-end guard, secondmate harness, bootstrap) — all pass, with the bootstrap suite needing its documented FM_TEST_BASE_PATH override because this host has a system node its fixture assumes absent. Ran the opt-in live e2e against real Claude Code 2.1.235, proving the installed Stop payload and exact transcript token accounting while the under-budget turn stayed inert. Captured a product-level CLI transcript demonstrating the whole handoff lifecycle (default config, rejection of malformed config, silent under-threshold turns, the one typed directive, manual fallback, and the automatic wrapper relaunch that releases only the dead owner's lock and hands the successor a single digest-reconciliation prompt), verified the pi typed-kind registration by executing the changed modules, and added one focused test for the previously uncovered unsynced-home plain-Claude fallback. The only failure encountered is a pre-existing, change-unrelated pi/tmux TUI flake in the calm-pi suite (different case fails each run, including one that loads none of the changed code). No visual artifact applies: this change has no rendered UI surface — hooks, CLI commands, and terminal wrappers are the end-user surface, and the captured CLI transcripts show it directly.

Evidence: Context-refresh lifecycle CLI transcript (hook directive, manual fallback, automatic wrapper relaunch)

Source: Context-refresh lifecycle CLI transcript (hook directive, manual fallback, automatic wrapper relaunch)


===== 1. Absent config materializes the visible 400000-token default =====
$ fm_context_restart_budget_materialize config/ && fm-context-restart.sh read-budget
400000
-> config/context-restart-budget now contains: 400000

===== 2. Malformed and unsafe config files are rejected, never guessed =====
$ read-budget   # file contains 'about 400k'
context-restart-budget: invalid config/context-restart-budget - value must be one positive decimal integer
exit=1
$ read-budget   # file is a symlink out of config/
context-restart-budget: invalid config/context-restart-budget - file is symlinked
exit=1

===== 3. Under threshold (80 < 100): the Stop hook is silent and durably inert =====
$ Stop fires with latest assistant usage 20+20+20+20 = 80 tokens
hook exit=0  output='<>'
-> no crossing record published

===== 4. Crossing the budget emits the one typed context-refresh directive =====
$ Stop fires with latest assistant usage 30+30+30+10 = 100 tokens (budget 100)
hook exit=2
--- directive Claude receives as its forced continuation ---
⁣FIRSTMATE_OP: v1 context-refresh: Context is 100 tokens at this turn boundary, meeting the 100-token restart budget. Perform the deliberate handoff now: invoke /stow and complete its full pass, including open-record persistence and the secondmate cascade. Continue only when its receipt says the session is reset-safe. Then run bin/fm-context-restart.sh handoff --session demo-session --reset-safe. Do not accept new work or send a captain-facing progress reply before that command. This crossing is durable and this directive will not repeat.
-------------------------------------------------------------
$ the same Stop firing again (still 100 tokens)
hook exit=0  output='<>' (durable crossing prevents a nag loop)

===== 5. Handoff after /stow without the wrapper: durable prep + manual fallback =====
$ bin/fm-context-restart.sh handoff --session demo-session --reset-safe  (plain claude launch)
exit=3
context-restart: handoff is durable, but this session was not launched by bin/fm-primary.sh; exit Claude and relaunch with bin/fm-primary.sh so the fresh session can resume from its session-start digest
-> crossing advanced to phase=ready mode=manual; a manual bin/fm-primary.sh relaunch stays available

===== 6. bin/fm-primary.sh: automatic fresh successor in the same terminal =====
$ bin/fm-primary.sh --firstmate-initial-prompt LAUNCH_BRIEF -- --effort low
[claude generation 1] running with args: --effort low LAUNCH_BRIEF
[claude generation 1] /stow reported reset-safe; running the handoff command
context-restart: reset-safe handoff prepared; ending this Claude session
Terminated                 FM_CONTEXT_RESTART_WRAPPER_TOKEN="$TOKEN" "$CLAUDE_BIN" "${CLAUDE_ARGS[@]}" "$INITIAL_PROMPT"
Firstmate context handoff complete; starting a fresh Claude session.
[claude generation 2] fresh session started with args: --effort low ⁣FIRSTMATE_OP: v1 session-start: A reset-safe context handoff completed. The native SessionStart hook has already run the full digest before this turn. Read that digest as startup and recovery input, reconcile it under AGENTS.md, resume work already under way, then wait silently if no action remains.
[claude generation 2] old session lock is gone; SessionStart can acquire it
wrapper exit=0

generation 1 argv: --effort low LAUNCH_BRIEF

generation 2 argv: --effort low ⁣FIRSTMATE_OP: v1 session-start: A reset-safe context handoff completed. The native SessionStart hook has already run the full digest before this turn. Read that digest as startup and recovery input, reconcile it under AGENTS.md, resume work already under way, then wait silently if no action remains.

-> completed handoff sentinel retired
-> exiting generation's session lock released (only that owner's)

===== 7. Resume-restoring Claude options are refused by the fresh-session wrapper =====
$ bin/fm-primary.sh -- --resume abc123
fm-primary: '--resume' would restore prior conversation context; launch it outside this fresh-session wrapper
exit=2
Evidence: Live Claude Code 2.1.235 e2e result (real Stop payload, exact usage match, inert under budget)

Source: Live Claude Code 2.1.235 e2e result (real Stop payload, exact usage match, inert under budget)

ok - Claude 2.1.235 (Claude Code) live Stop payload session=5e5afe68-2926-4996-935b-b475caeb7462 exposed transcript usage=55514 and stayed inert below budget

$ FM_CONTEXT_RESTART_CLAUDE_LIVE_E2E=1 tests/fm-context-restart-claude-live-e2e.test.sh
ok - Claude 2.1.235 (Claude Code) live Stop payload session=5e5afe68-2926-4996-935b-b475caeb7462 exposed transcript usage=55514 and stayed inert below budget
exit=0

What this proves against the real installed Claude Code 2.1.235:
- the registered Stop hook receives a payload carrying session_id and a readable transcript_path
- Firstmate's transcript accounting (latest assistant input + cache_creation + cache_read + output tokens)
  computed 55514, exactly matching Claude's own reported result usage for the turn
- with the budget set far above the observed context, the live session stayed inert:
  no crossing record was published and the ordinary turn completed normally
Evidence: Pi extension modules register and round-trip the context-refresh kind

Source: Pi extension modules register and round-trip the context-refresh kind

ok - pi extension modules register and round-trip the context-refresh kind current kinds: ["session-start","watcher","turn-end-guard","away-supervisor","context-refresh","from-firstmate","launch-brief"] encode -> classify round-trip: "context-refresh\n"

ok - pi extension modules register and round-trip the context-refresh kind
     current kinds: ["session-start","watcher","turn-end-guard","away-supervisor","context-refresh","from-firstmate","launch-brief"]
     encode -> classify round-trip: "context-refresh\n"
- Outcome: ⚠️ 1 warning across 1 run (22m35s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 5 issues found → auto-fixed ✅
  • ⚠️ AGENTS.md:119 - AGENTS.md documents the context-restart single-flight publication lock as state/.context-restart-crossing.lock, but the code in bin/fm-context-restart-claude-hook.sh:28 and bin/fm-context-restart.sh:26 creates state/.context-restart.lock. The 'never touch' state-file inventory therefore names a file that never exists and omits the real lock path. Fix by aligning either side (rename the CLAIM path to .context-restart-crossing.lock, or correct AGENTS.md).
  • ⚠️ tests/fm-context-restart.test.sh:241 - test_registration_is_claude_only asserts non-Claude harnesses are no-ops via ! rg -q &#39;fm-context-restart-claude-hook.sh&#39; over the .codex/.opencode/.pi/.grok/.cursor trees — a raw substring omission check over source/config content, the flagged test anti-pattern. It is also the only ripgrep dependency in the suite: on a host without rg, the negated command exits 127 and the assertion passes vacuously, proving nothing. Keep the adjacent jq semantic registration-count check; remove the rg sweep or replace it with semantic parses of each harness's own hook-registration artifact.
  • ℹ️ bin/fm-primary.sh:40 - usage() uses sed range '2,3', which prints the description and the literal 'Usage:' header but stops before the actual syntax line at file line 4 (fm-primary.sh [--firstmate-initial-prompt &lt;text&gt;] [--] [claude-options...]). -h and argument errors show an empty usage block; the range should be '2,4' (fm-context-restart.sh correctly uses '2,5').
  • ℹ️ bin/fm-context-restart-claude-hook.sh:78 - The crossing record is durably published before the exit-2 directive is emitted, and later Stop firings for the same session stay silent for any phase. If the single directive continuation is lost (user interrupts the continuation turn, encode failure, or the hook's 15s timeout landing in the publish-to-print window), the session continues over budget with no re-emission, and nothing (including the session-start digest) surfaces the lingering 'detected' record. This matches the intent's explicit one-durable-directive design and the header comment documents the ordering deliberately; noting the residual gap — surfacing a stale detected crossing in the startup digest would close it as an optional follow-up.
  • ℹ️ bin/fm-config-inherit-lib.sh:501 - The budget-file primitives in bin/fm-context-restart-lib.sh (config_dir_safe, file_valid, read, materialize, link-count) and the per-item guard block added to propagate_inheritable_config are near-verbatim mirrors of the startup-memory-budget equivalents, differing only in names and error variables (~80 duplicated lines total). This mirrors deliberate existing repo idiom, so it is not a defect; a parameterized shared helper is an optional cleanup if a third scalar budget ever appears.

🔧 Fix: fix lock inventory, usage range, and registration test
✅ Re-checked - no issues remain.

⚠️ **Test** - 1 warning
  • ⚠️ tests/fm-calm-pi-extension.test.sh:1821 - Pre-existing flaky test, not caused by this change: the live pi/tmux operational follow-up e2e in tests/fm-calm-pi-extension.test.sh failed in 3/3 local runs with 'rendered a duplicate captain answer', but on a different case each run (legacy_away, exact_watcher, then absent). The 'absent' case runs pi without the changed Calm visibility extension loaded at all, and cases that failed in one run passed in others, so this is nondeterministic tmux pane-capture timing on this WSL2 host rather than a regression. Because the suite fail-fasts there, its own later context-refresh kind assertions never ran locally; that gap was covered by executing the changed pi modules directly (context-refresh present in both exported kind lists, encode-to-classify round-trip through the canonical shell owner succeeds). CI should arbitrate this suite.
  • tests/fm-context-restart.test.sh (all 6 cases: budget default/validation, one-directive-per-crossing, malformed transcript rejection, concurrent Stop dedup, wrapper relaunch + lock transfer, single hook registration)
  • FM_CONTEXT_RESTART_CLAUDE_LIVE_E2E=1 tests/fm-context-restart-claude-live-e2e.test.sh against real Claude Code 2.1.235 (live Stop payload, exact transcript usage match of 55514 tokens, inert under budget)
  • tests/fm-operational-input.test.sh (context-refresh typed-kind encoding matrix)
  • tests/fm-turnend-guard.test.sh (Stop-hook stack composition; 6 grok-guarded tracked entries)
  • tests/fm-secondmate-harness.test.sh (49 ok: wrapper launch for Claude secondmates, budget default materialization and inheritance, plus new test_spawn_unsynced_claude_home_falls_back_to_plain_launch)
  • FM_TEST_BASE_PATH=&lt;node-free path&gt; tests/fm-bootstrap.test.sh (28 ok after fixing the host-node fixture assumption via the suite's documented override)
  • tests/fm-calm-pi-extension.test.sh three runs (pre-existing pi/tmux TUI flake identified; failing case alternates and reproduces without the changed code loaded)
  • Manual lifecycle demo driving the real hook, handoff command, and fm-primary.sh wrapper with a fake claude harness: default materialization, malformed/symlink config rejection, silent under-threshold Stop, typed context-refresh directive at crossing with no nag repeat, exit-3 manual fallback preserving the ready sentinel, automatic fresh successor with exact-owner lock release and one typed session-start resume prompt, and refusal of --resume/--continue options
  • Direct execution of the changed pi extension modules via node type-stripping: context-refresh registered in FIRSTMATE_CURRENT_OPERATIONAL_KINDS and FIRSTMATE_SYNTHETIC_KINDS, encode-to-classify round-trip through bin/fm-operational-input.sh
✅ **Document** - passed

✅ No issues found.

⚠️ **Lint** - 1 warning
  • ⚠️ linter found issues (exit code 127)
✅ **Push** - passed

✅ No issues found.

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