Repository navigation
feat(bin): add context hygiene for long-lived supervising agents - #75
Merged
Merged
Conversation
A home's primary or secondmate agent is long-lived: every supervision wake is another full-context turn, so an agent that never compacts or clears accumulates a very large context. Add context hygiene so the home's own agent compacts at a task boundary and clears while idle, plus the watcher cadence and wake-batching knobs that keep a long supervision session cheap. - bin/fm-context-hygiene-lib.sh owns the config knobs, the verified per-harness compact/clear command table, the durable compact marker, and the idle window. - bin/fm-teardown.sh and bin/fm-pr-merge.sh queue a compact at a merged or torn-down task boundary; bin/fm-watch.sh delivers it at the next idle moment and delivers a clear once the home is fully idle. Delivery runs only into a pane proven idle at an empty prompt, and pauses while away mode owns it. - Wake coalescing deduplicates a status file seen by both the grace-window scan and its re-scan into one wake, and config/wake-coalesce-seconds sets the window. The secondmate stall check no longer escalates a mate whose steering inbox is empty and which is idle at its own prompt. - Adaptive heartbeat backs off to config/heartbeat-idle-seconds while nothing is in flight and resets the moment any task is in flight. - The session-start digest enforces config/startup-memory-budget by truncating learnings with an explicit pointer instead of inlining it in full. - bin/fm-context-report.sh measures tokens-in-context per turn, wakes per hour, and the share above 150k from Claude session transcripts.
Reject leading-zero second values, never let a pending compact marker pin an unproven harness and starve the idle-clear path, drop a dead marker clear in the healthy-idle secondmate branch, and cover away-mode pause, unproven-composer refusal, unknown-harness marker drop, malformed budget fallback, and captain-shared budget counting.
Require a positively-proven steering inbox before a secondmate counts as healthy idle, drop a stale idle stamp when a reset rewrite fails so a delivered clear cannot re-fire every poll, reject leading-zero --hours values, and note that env-marker harness detection survives a reparented watcher.
Use the full native+rendered busy verdict (pane_is_busy_explicit) instead of a native-only fm_backend_busy_state read, which is unknown on tmux, and make the healthy-idle secondmate predicate refute a provably-working pane so a busy mate is never mistaken for idle. Extend the context-hygiene tests to pin both.
- Healthy-idle secondmates now use the unbounded rendered busy verdict, not the time-bounded active-turn gate, and decline when the pane cannot be read. - Maintain the idle window on every watcher cycle so a wake-handling cycle cannot leave a stale elapsed stamp, and restart it after a delivered compact. - Fail closed when a supervisor pane capture fails instead of treating the pane as idle.
The pipeline review found that an unmeasurable captain.md/captain-shared.md counted as zero tokens, silently under-counting and letting a huge learnings file inline; count it as over-allowance instead. Also drop a redundant guard in fm_context_hygiene_setting.
Add the regression test the pipeline review asked for: a symlinked captain.md is refused by the budget measurement and must fail the digest safe by truncating learnings rather than counting it as zero.
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
The captain, verbatim: "enhance firstmate, by adding an axi skill for auto compact faster / or clear the context when the task is done? What's contributing to your limits usage?"
His Claude usage report for the last 24 hours, which prompted the ask: 94% of usage is at contexts over 150k tokens, 86% comes from sessions active 8+ hours, and 71% happens while 4+ sessions run in parallel. The primary firstmate session and its Claude secondmates are those long-running, parallel sessions: every supervision wake is currently a full-context turn on a 200-300k token context, including heartbeats and false stall wakes that carry no new work.
Build firstmate-side context hygiene so a home's own agent compacts or clears its context at natural boundaries instead of accumulating it indefinitely across a long supervision session, without weakening the supervision contract (no missed wakes, no silently dropped work).
What Changed
bin/fm-context-hygiene-lib.sh, a new policy library that decides when a home's own agent should compact (at a task's merged/torn-down boundary) or clear (afterconfig/context-hygiene-idle-seconds, default 900s, of full idle with no in-flight work) its context, gated byconfig/context-hygiene(offdisables it), and owning the per-harness context-command table, the durable compact-pending marker, and the idle-since tracking.bin/fm-watch.sh(delivery of compact/clear commands only into a pane proven idle at an empty prompt, paused during away mode, plus newconfig/wake-coalesce-secondssignal-coalescing andconfig/heartbeat-idle-secondsidle-heartbeat backoff-with-reset support), and added compact/clear trigger points inbin/fm-session-start.sh,bin/fm-pr-merge.sh, andbin/fm-teardown.shat task-boundary events;bin/fm-session-start.shalso fails the startup memory budget check safe when the memory file is unmeasurable.bin/fm-context-report.sh, a read-only diagnostic that measures per-wake context growth from a Claude harness's own session transcripts (tokens per turn, wakes/hour), plus test coverage (tests/fm-context-hygiene.test.sh,tests/fm-context-report.test.sh) and updates to existing tests (fm-session-start,fm-pr-merge,fm-teardown) and docs (docs/architecture.md,docs/configuration.md,docs/scripts.md,AGENTS.md) describing the new config knobs and behavior.Risk Assessment
✅ Low: The change is well-bounded to firstmate's own bash scripts, all four round-1 findings were correctly addressed and verified (fail-safe budget on unmeasurable captain.md, redundant check removed, symlink regression test added), the only remaining issue is a mechanical duplicated predicate with no behavioral difference, and tracing the compact/clear decision logic, pane-injection guards, and marker durability shows the required "no missed wakes, no silently dropped work" invariant is upheld end-to-end (durable on-disk markers retried until delivered, fresh-computed idle state each cycle, double busy+composer proof before injection, away-mode short-circuit, post-compact idle-window reset before a clear can fire).
Testing
Ran the branch's product surface directly rather than the full suite: the new fm-context-report.sh CLI against synthetic Claude transcripts, the context-hygiene library's config/idle/marker/harness-guard functions via direct calls, the real fm-pr-merge.sh/fm-teardown.sh/fm-session-start.sh entry scripts (external gh/git/tmux faked, everything else real), and the project's own fm-context-hygiene.test.sh for the watcher's delivery/AFK/backoff/coalescing wiring (only the tmux pane-send primitive is stubbed there, since no live tmux+Claude/Pi pane exists in this sandbox). One scenario (watcher pane delivery) could not be driven against a real tmux pane and has been marked untested rather than pass, since it was not actually run live. Every other scenario I could drive passed. A single unrelated assertion (default status-tail line count) failed at both the target and the base commit, proving it's a pre-existing flake, not a regression from this change.
Evidence: Live test evidence summary (context report output, hygiene-lib scenario results, boundary-wiring confirmations)
Source: Live test evidence summary (context report output, hygiene-lib scenario results, boundary-wiring confirmations)
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-watch.sh:1758- context_hygiene_idle_touch() re-implements the same three-condition not-idle check (in-flight count, pending replies, wake queue) that fm_context_hygiene_idle_ready() in bin/fm-context-hygiene-lib.sh already encodes, including identical rm/date-stamp side effects, instead of calling the existing lib predicate. No current behavioral difference, but a future change to one condition set could desynchronize the idle-since stamp path from the actual clear-decision path.tests/fm-session-start.test.sh:1281- tests/fm-session-start.test.sh's test_status_tail_bounding fails an unrelated assertion ('default status tail (5 lines) missing an expected recent line') at both the target commit and the base commit (48fb85b), confirmed via a clean git-archive checkout of base. Pre-existing, unrelated to the context-hygiene change; flagging for awareness only, not requesting action here.bin/fm-context-report.sh --hours 24 --projects-dir <synthetic transcripts> (default, --all --json, missing root, bad --hours) run directlybin/fm-context-hygiene-lib.sh functions (fm_context_hygiene_disabled, fm_context_hygiene_idle_ready, fm_context_hygiene_command, fm_context_hygiene_mark_compact/clear_marker) sourced and called directly against real tmp filesystem state./bin/fm-test-run.sh tests/fm-context-hygiene.test.sh (14/14 ok)./bin/fm-test-run.sh tests/fm-context-report.test.sh (4/4 ok)./bin/fm-test-run.sh tests/fm-session-start.test.sh (targeted: 'an unmeasurable memory file fails the startup budget safe', 'captain-shared.md counts against the startup-memory allowance' both ok; unrelated pre-existing failure noted separately)isolated single-scenario run of test_verified_merge_records_pr_and_head against the real bin/fm-pr-merge.sh (ok)isolated single-scenario run of test_local_only_merged_to_local_main_allows against the real bin/fm-teardown.sh (ok)git archive of base commit 48fb85bd8c14b8358fcc0bff67822c89d1000251 + ./bin/fm-test-run.sh tests/fm-session-start.test.sh to confirm the status-tail flake predates this branch✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.