Repository navigation
Conversation
This was referenced Oct 4, 2026
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
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
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 validatedconfig/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 thenbin/fm-context-restart.sh handoff; under threshold it stays silent and spends no tokens.bin/fm-primary.shplusbin/fm-context-restart.shandbin/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.context-restart-budgetjoins the inheritable config set with strict source/destination validation inbin/fm-config-inherit-lib.sh,bin/fm-spawn.shlaunches 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 newdocs/context-refresh.mddocumentation.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)
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 budgetEvidence: 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"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 asstate/.context-restart-crossing.lock, but the code in bin/fm-context-restart-claude-hook.sh:28 and bin/fm-context-restart.sh:26 createsstate/.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 'fm-context-restart-claude-hook.sh'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 withoutrg, 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 <text>] [--] [claude-options...]).-hand 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.
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.shagainst 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 newtest_spawn_unsynced_claude_home_falls_back_to_plain_launch)FM_TEST_BASE_PATH=<node-free path> 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.shthree 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 optionsDirect 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.
✅ **Push** - passed
✅ No issues found.