Repository navigation
feat(bin): add a claude turn-end context budget guard with a 180k ceiling - #4
Merged
Merged
Conversation
Firstmate sessions balloon toward roughly 800,000 tokens before Claude's own auto-compaction fires. This adds a turn-end guardrail that measures the live session and blocks the turn end at an absolute 180,000 tokens, far earlier than anything the harness does on its own. It is a cost and reasoning-quality policy, not overflow prevention. bin/fm-context-budget.sh is the whole owner, registered as a third sibling Stop hook rather than folded into the turn-end supervision guard, which keeps owning exactly one predicate. Measurement reads transcript_path from the hook payload and never derives it from $HOME, because a non-default config directory puts the transcript where $HOME cannot predict. The total sums the four usage fields on the last non-sidechain assistant entry, and keeps three correctness rules: dedupe a multi-block turn by requestId, take last rather than max so compaction cannot disable the guard, and exclude sidechains. The ceiling is the only policy number; the advisory notice is derived as ceiling minus headroom so there is no second threshold to keep in sync. There is one valve: run /stow, write a handoff note, and clear. It is built on tracked /stow rather than the untracked personal /handoff skill. The guard only instructs; it never types into a pane, injects a command, or spawns an agent. A session cannot clear itself, so with no captain present the valve cannot close. The guard still gets the handoff written and then degrades to a visible allow once the block budget is spent. docs/context-budget.md records this limit rather than working around it with keystroke injection. Every measurement failure is a silent exit 0 and blocking is bounded, so the guard can never wedge a session. Scope binds primary and secondmate primary sessions and stays inert for crew subagent turns. Verified live end to end in a throwaway project: the block fired at a real 32,633 tokens against an overridden ceiling and named the valve. Claude Code 2.1.220 writes subagent turns to a separate subagents/agent-<id>.jsonl file carrying isSidechain, so a subagent's 24,461 tokens never reached the primary's 33,217 measurement. A marked secondmate home blocked while the same linked worktree without the marker stayed silent. docs/verification/context-budget.md records the commands and output. This slice supports claude only; per-harness fan-out lands separately.
…ect re-arm claims
Carries out the batched decision on the notice-record stage class, plus two corrections that were already outstanding against this branch. The count-not-recorded degrade now has its own notice key. The record's single stage field stood for two different messages, so whichever fired first silenced the other for the whole episode: a ceiling notice already shown made the guard go quiet about its own malfunction from the very first occurrence. The record now carries independent flags rather than one field, and the degrade still prints once per episode instead of at every turn end. An unparseable block record is read as no record, leaving the guard active, and the parse failure is traced once. Reading it as a spent stand-down conflated unknown with dismissed and let a corrupt file impersonate a dismissal. The retention bias still protects a stand-down the session was actually told about. Leaving the guard armed does not cost the block bound: a writable record is rewritten on the first blocked turn, and an unwritable one degrades to the visible warning. The trip record now writes one line per crossing rather than one per turn end above the advisory. It answered how long a session lingered instead of how often the guard fired; 12 turn ends at a steady 160,000 wrote 12 lines. The line is written where the stage is recorded, and the enforcing path records its crossing separately because it prints on every blocked turn. The ceiling straddle is left unfixed on purpose and recorded in the code with the numbers. Replayed twice over real transcripts, across 41,244 and then 41,353 measured turns, it occurred zero times, and the obvious fixes would make the independent-key case strictly worse. A test pins the current behavior so it is not fixed in passing. Also corrects two stale claims: the single-condition re-arm claims in the test file, one of which printed into test output, and the unqualified whole-session claim about staying out of the harness's consecutive-block accounting, which is false because the stand-down clears mid-session. A new assertion found a real defect: every record write suppressed its own failure with a trailing 2>/dev/null, which bash applies too late, so an unwritable record leaked the shell's "Permission denied" onto the same stderr the blocking path uses to reach the model. All five writes now suppress first. Enforcement stays opt-in and no behavior outside this component changes.
…er for a durable trip line
…s in context-budget docs
…ception The verification record required a clean bin/fm-test-run.sh --all, which cannot hold on this host: tests/fm-kimi-harness.test.sh fails because the machine's python3 is an asdf shim that exits 126 under the overridden HOME that test uses. Records the suites this change is actually required to keep green, names the failing assertion and its cause, and states that it is pre-existing and reproduced on untouched base 1672d95 by two workers on two dates. Points at fm-kimi-harness-test-env as the thread that owns it, so the narrower bar reads as an evidenced exception rather than a shortcut. The failure is deliberately not repaired here: a change that also fixes an unrelated machine-local environment failure stops being reviewable.
…cedence The rebase brought this branch alongside the 250,000 handover threshold, and the two contracts contradicted each other. This guard told a session to stop and ask the captain to clear before continuing; the handover rule forbids stalling the fleet for the captain's answer. It also asserted that a session cannot clear itself, which was measured and true when written but is retired by bin/fm-handover.sh release, a helm, and a successor session. Three changes, the minimum that makes the contract coherent: - The ceiling no longer stalls. It reports, the session keeps working, and the captain hears at the next natural reply. - The false premise is deleted rather than hedged. Clearing is still something a session cannot do, and that no longer constrains anything, because a handover does not clear a context - it releases the helm. - AGENTS.md now states the precedence that neither side stated: which threshold fires first, that above 250,000 every threshold applies at once, and that the handover mechanism owns the valve in every case. The emitted valve text is re-pointed to match, so the one model-facing message this guard can send no longer instructs a session to do what the contract just retired. docs/context-budget.md drops the stall-and-ask claim everywhere, not only in the section that conflicted. Structural unification of the two thresholds is deliberately not attempted here and is tracked as fm-context-budget-handover-unification. Also from the rebase: the Stop array now carries four siblings, and the registration test pins the exact set and the auto-arm staying last, so a future rebase cannot silently drop either context hook.
A review asked this branch to source bin/fm-context-measure-lib.sh and delete its inline measure_context, since the lib's header names this branch and docs/scripts.md calls it the single owner. That was declined by standing decision. This records the refusal with its evidence so a later reader sees a reasoned decision rather than a finding that was quietly skipped. The adoption is not refused in principle; one owner is the agreed end state. A straight swap today would delete working behavior, in four ways, the fourth found by that review: the lib slurps where this streams, it has no compaction-boundary tally that genuine-reset detection depends on, it dedupes multi-block turns by requestId, and it does not drop synthetic zero-usage entries. That fourth difference makes the lib's own caller wrong rather than merely different. On a transcript of one 300,010-token turn followed by the synthetic zero-usage entry written when a turn ends abnormally, the lib returns 0 with exit status 0, so a caller reads it as a real measurement. bin/fm-session-pulse.sh then takes its under-threshold branch and removes the once-per-session handover-due marker, so an interrupted turn makes that session forget a handover was due. Reproduced end to end. That is a defect in the sibling hook, is not repaired here, and is tracked as fm-session-pulse-false-zero. The agreed end state is the reverse move: put this streaming implementation, with rule 3 and the compaction tally, into the lib and have both callers adopt it, under its own tests and review as fm-context-measure-lib-adoption.
uayyagari
force-pushed
the
feat/context-budget-guardrail
branch
from
August 5, 2026 09:49
197715d to
42ff7fd
Compare
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 the claude reference slice of firstmate's context-budget guardrail: a Stop-hook turn-end mechanism that measures the live session's context from the transcript the hook payload points at, warns as it approaches an absolute 180,000-token ceiling, and (only when enforcement is explicitly switched on) blocks the turn end and requires the session to run /stow, write a handoff note, and clear.
This commit is the fifth fix round on an existing branch. It carries out a batched decision on one defect class - a single notice-record field standing for several distinct messages - plus two corrections that were already outstanding. Four rulings, decided deliberately and NOT all the same way:
The ceiling straddle (a session oscillating across the ceiling re-notices every turn end) is DELIBERATELY NOT FIXED. This is the important one for review: the defect is real in code and was measured as unreachable in practice - replayed twice over real transcripts across 41,244 and then 41,353 measured turns, it occurred zero times, and the measurement is effectively monotonic inside an episode by arithmetic. The obvious fixes (monotonic stage, or highest-stage-reached) would close it while making the shared-key instances strictly worse, because a recorded
ceilingcould then never be superseded by the count-not-recorded degrade. It is recorded in bin/fm-context-budget.sh as a KNOWN UNFIXED case with the numbers, and a test pins the current behavior so a later reader does not "fix it while they are here". Do NOT propose making the stage monotonic or otherwise closing the straddle; that was considered and declined on evidence.The count-not-recorded degrade gets its OWN notice key. It previously shared the
stagefield with the ceiling notice, so a ceiling notice already shown made the guard silent about its own malfunction from the first occurrence. Deliberately kept deduped per episode rather than made unconditional, because an unconditional variant would repeat at every turn end while the record stays unwritable.An unparseable block record is now read as NO record, leaving the guard active, and the parse failure is traced once. Reading it as a spent stand-down conflated "unknown" with "dismissed" and let a corrupt file impersonate a dismissal. This is a deliberate narrowing of the file's retention bias, not a reversal: retention still protects a stand-down the session was actually told about. The asymmetry is the argument - this guard only ever warns, so a spurious warning costs one printed line while a suppressed one costs a session blown past the ceiling with nothing explaining why.
The trip record now writes one line per CROSSING rather than one per turn end above the advisory. Measured: 12 turn ends at a steady 160,000 wrote 12 lines, which answered how long a session lingered instead of how often the guard fired. No dwell field was added on purpose (YAGNI; it was not asked for).
Also folded in, both previously outstanding: two stale single-condition re-arm claims in the test file (one of which printed into test output), and an unqualified whole-session claim about staying out of the harness's consecutive-block accounting, now false because the stand-down clears mid-session.
While adding the new assertions I found and fixed a real defect: every record write suppressed its own failure with a TRAILING 2>/dev/null, which bash applies left to right and therefore too late, so an unwritable record leaked the shell's "Permission denied" onto the same stderr the blocking path uses to deliver its banner to the model. All five writes now suppress first.
Deliberate constraints a reviewer should not flag as oversights:
Known pre-existing failure, NOT caused by this branch: tests/fm-kimi-harness.test.sh fails on this machine because the asdf python3 shim exits 126 under the overridden HOME that test uses. Reproduced identically on untouched base 1672d95. Everything else in bin/fm-test-run.sh --all passes (102 files, that one failure), and tests/fm-context-budget.test.sh is 73/73 green with bin/fm-lint.sh and bin/fm-doc-audience-check.sh clean.
FOLLOW-UP COMMIT IN THIS RUN (37cd52b): the verification record claimed a clean bin/fm-test-run.sh --all, which cannot hold on this host. Per an explicit scope ruling, the test bar is narrowed to the suites this change actually touches, and the exception is now stated where a reader meets it: tests/fm-kimi-harness.test.sh fails because the machine's python3 is an asdf shim exiting 126 under the overridden HOME that test uses, it is pre-existing and reproduced on untouched base 1672d95 by two workers on two dates, and it is tracked as fm-kimi-harness-test-env. Repairing it inside this branch was explicitly ruled out as making the branch unreviewable, so do not propose fixing it here.
Also in this run: the previous round's review findings were fixed by the pipeline and are already on the branch - notice_once was collapsed into stage_enter so both the parse failure and the unwritable-count degrade leave a durable trip line, since the systemMessage channel is measured at zero renders. Those are resolved, not open.
REBASED ONTO NEW MAIN (78407d1) AND ONE COHERENCE FIX ADDED (acb99c3). feat/session-handover landed as PR 5, bringing a 250,000-token non-blocking handover threshold, a helm, bin/fm-handover.sh, and a fm-session-pulse.sh Stop hook. Five files overlapped and were resolved BY HAND, neither side winning wholesale: .claude/settings.json now stacks four Stop hooks (turn-end guard, session pulse, context budget, auto-arm last with asyncRewake/timeout intact); docs/documentation-audiences.json carries both verification docs; docs/turnend-guard.md names both sibling hooks.
AGENTS.md was escalated rather than guessed, because the two sides contradicted each other, and the resolution is a ruled decision I am carrying out, not my own call. This guard used to order a session to stop and ask the captain to clear before continuing other work; the handover rule forbids stalling the fleet for the captain's answer. It also asserted a session cannot clear itself - measured and true when written, retired by bin/fm-handover.sh release plus a successor session. So: the ceiling is now NON-BLOCKING in its instruction, the false premise is DELETED rather than hedged, and AGENTS.md now carries the precedence sentence neither side had - which threshold fires first, that above 250,000 every threshold applies at once, and that the handover mechanism OWNS THE VALVE in every case. The emitted valve text and every stall-and-ask claim in docs/context-budget.md were re-pointed to match, so the one model-facing message this guard can send does not instruct a session to do what the contract just retired.
FOR THE PR BODY, state plainly: the shipped default is warning-only and captain-facing, and THAT is what made this minimum fix sufficient rather than requiring structural unification of the two thresholds. Name fm-context-budget-handover-unification as the follow-up task that owns the end state, so a reviewer sees the contradiction was closed deliberately and the deeper cleanup was scheduled rather than missed.
Do NOT propose folding the 180,000 ceiling into the handover mechanism in this round - that is exactly fm-context-budget-handover-unification and was refused for this round on the grounds that it would make this PR unreviewable. Do NOT propose adopting bin/fm-context-measure-lib.sh; that is separately deferred and the lib is not behaviourally equivalent (it slurps, and it has no compaction-boundary tally that record_predates_a_compaction depends on).
STILL UNRULED AND CARRIED FORWARD, not self-answered: standdown-write-failure-unhandled (the exhausted-budget branch ignores budget_record's return status, so a readable-but-unwritable record at the budget makes it re-emit "stands down for the rest of the session" every turn without persisting standdown=1) and trip-line-dedupe-depends-on-notice-write (stage_enter's one-line-per-crossing guarantee rests on notice_record, which swallows its write failure). Both were reproduced. Raise them again if they still stand.
Verification on the rebased head: tests/fm-context-budget.test.sh 73/73 green, bin/fm-lint.sh clean, bin/fm-doc-audience-check.sh clean, and main's own suites still green after the rebase - fm-turnend-guard 50, fm-session-handover 29, fm-helm-takeover 18, fm-documentation-audiences 5, fm-instruction-owners 11.
TWO MORE COMMITS AND THREE DECISIONS SINCE THE LAST RUN. Commit 42ff7fd records, in docs/verification/context-budget.md, WHY bin/fm-context-measure-lib.sh is not adopted here. A previous review raised that as an ask-user finding; it was DECLINED BY STANDING DECISION, made twice, and the record exists so the refusal reads as reasoned rather than quietly skipped. Do not raise it again: the requested action is refused, and the evidence strengthens the refusal rather than weakening it. Four ways the lib is behind this implementation, the fourth found by that review: it slurps where this streams, it has no compaction-boundary tally that record_predates_a_compaction needs, it dedupes multi-block turns by requestId, and it does NOT drop synthetic zero-usage entries. That fourth one makes the lib's own caller wrong: on one 300,010-token turn followed by the synthetic zero entry an abnormal turn end writes, the lib returns 0 with exit status 0, so bin/fm-session-pulse.sh takes its under-threshold branch and deletes the once-per-session state/.handover-due marker. Reproduced end to end. That is a defect in the SIBLING hook, not in this branch, it is deliberately not repaired here, and it is filed at priority 1 as fm-session-pulse-false-zero, blocked on this PR landing.
THE TWO PREVIOUSLY UNRULED FINDINGS ARE NOW DECIDED, and the decision is that they go to FOLLOW-UP tasks rather than into this round, filed and blocked on this PR landing so they rebase onto it rather than fight it: standdown-write-failure-unhandled as fm-context-budget-standdown-write-trace at priority 1, and trip-line-dedupe-depends-on-notice-write as fm-context-budget-trip-dedupe-notice-write at ordinary priority. Both carry the reproductions. They are real and they are scheduled, not dismissed. Do not ask for them to be fixed in this round.
The previous run failed on a transient API 529 that killed the fix agent mid-round; nothing partial landed. The only outstanding approved fix is the docs/scripts.md toolbelt row for bin/fm-context-budget.sh, which is a genuine oversight in this change and is approved for fixing. NOTHING ELSE JOINS THIS ROUND - take it to a PR with no further changes.
What Changed
bin/fm-context-budget.sh, a claude Stop hook that measures the live session's context from the transcript the hook payload points at and warns as it approaches an absolute 180,000-token ceiling; enforcement (blocking the turn end) is opt-in viaFM_CONTEXT_BUDGET_ENFORCE=1, so the shipped default only warns and is captain-facing. That warning-only, captain-facing default is what makes this a sufficient minimum fix rather than requiring structural unification of the two thresholds; the deeper cleanup is scheduled as follow-upfm-context-budget-handover-unification..claude/settings.jsonalongside the existing Stop hooks, re-point the model-facing valve text and precedence inAGENTS.mdanddocs/context-budget.mdso the guard is non-blocking and the handover mechanism owns the valve, and adddocs/verification/context-budget.md, adocs/scripts.mdtoolbelt row, audience metadata, andtests/fm-context-budget.test.sh(73 cases).Risk Assessment
✅ Low: The change is a well-bounded, opt-in, warning-only guard whose every notable design decision is deliberately documented and evidence-backed in the authoritative intent; the only remaining gap is a mechanical documentation row the author already approved fixing.
Testing
Ran the smallest relevant automated suite (tests/fm-context-budget.test.sh, 73/73 green) and then produced product-level evidence by driving the Stop hook exactly as the Claude harness does: feeding it JSON payloads over stdin in a plain primary-home checkout and capturing the actual model-facing output at each stage. This is a CLI/hook feature with no rendered UI surface, so the reviewer-visible evidence is CLI transcripts of the guard's real stdout systemMessage channel, stderr blocking banner, exit codes, and the on-disk write-only trip record — no screenshot applies. The transcripts confirm warning-only-by-default, opt-in enforcement with a bounded-then-sticky stand-down, the handover-owning valve text, the three measurement correctness rules, and one-trip-line-per-crossing. Working tree left clean; evidence written to the dedicated evidence directory. I did not run the full repository suite per the targeted-validation boundary; the intent's noted pre-existing tests/fm-kimi-harness.test.sh failure is unrelated to this component and outside the tested scope.
Evidence: End-to-end CLI transcript (all stages, measurement rules, trip record)
Evidence: Write-only trip record showing one line per crossing
Evidence: Enforcement-on blocking banner (exit 2, stderr)
/var/folders/vr/_90lw3_s0bs_nw2f7b6t9yrm0000gn/T/no-mistakes-evidence/01KZ8MQW0NVW1PR9W5A55QSYWD/demo-home)Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
.claude/settings.json- merge conflict rebasing onto origin/feat/context-budget-guardrailAGENTS.md- merge conflict rebasing onto origin/feat/context-budget-guardraildocs/documentation-audiences.json- merge conflict rebasing onto origin/feat/context-budget-guardraildocs/turnend-guard.md- merge conflict rebasing onto origin/feat/context-budget-guardraildocs/scripts.md:37- bin/fm-context-budget.sh is added as a tracked Stop hook in this change but has no row in docs/scripts.md, unlike its sibling Stop hooks fm-turnend-guard.sh (line 40), fm-session-pulse.sh (line 37), and fm-handover.sh (line 21), which are all listed. The author's intent explicitly names this as the only outstanding approved fix and a genuine oversight in this change. No test enforces scripts.md coverage, so it will not be caught downstream. Add a row describing the guard, e.g.| fm-context-budget.sh | Claude Stop hook warning at an absolute 180k context ceiling (docs/context-budget.md) |.✅ **Test** - passed
✅ No issues found.
bash tests/fm-context-budget.test.sh— 73/73 ok, no failuresEnd-to-end hook drive across stages A-D with real transcript fixtures +{transcript_path, session_id}stdin payloads, capturing stdout systemMessage / stderr banner / exit codeMeasurement-rule transcript: 900000 sidechain + 300000 earlier turn + 185000 last + trailing synthetic zero -> measured 185000 (sidechain excluded, last-not-max, zero ignored)Inspected state/.context-budget-trips: one crossing line for sessCC (2 turns above ceiling) and one for sessDD (5 turns), confirming one-line-per-crossing✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.