Skip to content

feat(bin): add context hygiene for long-lived supervising agents - #75

Merged
adibirzu merged 9 commits into
mainfrom
fm/fm-context-hygiene
Sep 14, 2026
Merged

adibirzu merged 9 commits into
mainfrom
fm/fm-context-hygiene

Conversation

@adibirzu

Copy link
Copy Markdown
Owner

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

  • Added 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 (after config/context-hygiene-idle-seconds, default 900s, of full idle with no in-flight work) its context, gated by config/context-hygiene (off disables it), and owning the per-harness context-command table, the durable compact-pending marker, and the idle-since tracking.
  • Wired that policy into bin/fm-watch.sh (delivery of compact/clear commands only into a pane proven idle at an empty prompt, paused during away mode, plus new config/wake-coalesce-seconds signal-coalescing and config/heartbeat-idle-seconds idle-heartbeat backoff-with-reset support), and added compact/clear trigger points in bin/fm-session-start.sh, bin/fm-pr-merge.sh, and bin/fm-teardown.sh at task-boundary events; bin/fm-session-start.sh also fails the startup memory budget check safe when the memory file is unmeasurable.
  • Added 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.

  • Live validation: ✅ go - 8 of 9 scenarios driven live against the product
Scenario Result Live Evidence
Context report surfaces what's driving limits usage (fm-context-report.sh) ✅ pass live Direct CLI run against synthetic transcripts: firstmate home grouped with 2 turns, mean 160000 tokens, 50.0% share above the 150k threshold; non-firstmate session excluded by default and included with…
config/context-hygiene = off disables the feature; absent/garbage value leaves it on ✅ pass live Direct calls to fm_context_hygiene_disabled with 'off', case-insensitive variants, an absent file, and a garbage value all matched the documented default-on/off-only contract.
Idle-clear only fires after a full continuous idle window (no premature clear) ✅ pass live fm_context_hygiene_idle_ready returned not-ready on the seeding poll and ready only after the configured window elapsed continuously.
Adversarial: an in-flight task, a non-empty wake queue, or a pending captain reply blocks the idle clear indefinitely (no missed wakes) ✅ pass live Each of a non-secondmate state/.meta record, a non-empty state/.wake-queue, and a state/pending-replies/ entry independently kept fm_context_hygiene_idle_ready from firing even after the idle window…
Adversarial: an unverified harness never receives a guessed context-reset command ✅ pass live fm_context_hygiene_command returned empty for an unverified harness name and the correct '/compact' for claude.
Durable compact marker survives until confirmed delivery ✅ pass live fm_context_hygiene_mark_compact wrote the marker with the focus line intact; fm_context_hygiene_clear_marker removed it only after an explicit call, matching the 'boundary reached while busy is not lo…
A verified PR merge and a completed teardown each queue the compact marker at the task boundary ✅ pass live Isolated real-script runs: test_verified_merge_records_pr_and_head against bin/fm-pr-merge.sh and test_local_only_merged_to_local_main_allows against bin/fm-teardown.sh both confirmed state/.context-c…
Watcher delivers the harness command only into a provably idle pane, pauses during AFK, and coalesces/backs off signals without dropping wakes ⏸️ untested no The prior payload marked this scenario 'pass' without a live result: no live tmux pane with a real Claude or Pi harness attached was ever driven in this sandbox, so no actual pane delivery, AFK pause,…
A symlinked/unmeasurable captain.md fails the startup-memory digest safe instead of silently counting as zero tokens (round-1 fix) ✅ pass live The real bin/fm-session-start.sh executed as a subprocess against a home with data/captain.md symlinked to a large file: output showed the truncation pointer to data/learnings.md and did not inline th…
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)

# fm-context-hygiene live test evidence (branch fm/fm-context-hygiene)

## fm-context-report.sh, direct CLI drive (bin/fm-context-report.sh)

Synthetic transcripts: one firstmate-home session with two assistant turns
(150000+149990+10=~300000 tokens, and 10000+9990+10=~20000 tokens), one
non-firstmate session (50000+49990+10=~100000 tokens).

Default (firstmate-only) text report:
`` `
HOME                                                                TURNS   WAKES/HR  MEAN_TOKENS MEDIAN_TOKENS PCT_GT_150K ACTIVE_H
~/firstmate                                              2       0.00       160000       160000      50.0%      0.0
TOTAL                                                                   2          -       160000            -      50.0%        -
`` `
Non-firstmate home correctly excluded by default; --all --json included both
homes as valid JSON; missing --projects-dir printed "no Claude transcript root
... nothing to report" (rc=0); --hours 0 refused with rc=2.

## fm-context-hygiene-lib.sh, direct function calls (bin/fm-context-hygiene-lib.sh)

- config/context-hygiene = "off" (and case-insensitive variants) disables the
  feature; an absent file or garbage value leaves it on (documented default).
- fm_context_hygiene_idle_ready: does not fire before the continuous idle
  window elapses; fires once it has; an in-flight (non-secondmate) task record,
  a non-empty state/.wake-queue, or a pending state/pending-replies/* entry
  each block it indefinitely (no missed-wake risk); a secondmate-only record
  does not block it.
- fm_context_hygiene_command: an unverified harness gets no guessed
  compact/clear command; "claude" gets its verified /compact.
- fm_context_hygiene_mark_compact / clear_marker: durable marker write, content
  round-trip, and removal after confirmed delivery.

## Real entry-script execution (external gh/git/tmux faked, everything else real)

- `tests/fm-context-hygiene.test.sh` (14/14 ok): sources the real
  bin/fm-context-hygiene-lib.sh and bin/fm-watch.sh; watcher delivers the
  compact/clear command only into a provably idle pane, pauses while
  state/.afk exists (away mode), heartbeat backoff doubles/caps/resets on a
  spawned task, and coalesced signal rows dedupe. Only the tmux pane-send
  primitive is stubbed (no live tmux+Claude/Pi pane in this sandbox).
- Isolated single-scenario runs (scratch copies of the real test files, real
  bin/fm-pr-merge.sh and bin/fm-teardown.sh executed as real subprocesses):
  `test_verified_merge_records_pr_and_head` (pr-merge) and
  `test_local_only_merged_to_local_main_allows` (teardown) both confirm
  state/.context-compact-pending is queued at the merge/teardown task
  boundary.
- `tests/fm-session-start.test.sh` targeted assertions: "an unmeasurable
  memory file fails the startup budget safe" and "captain-shared.md counts
  against the startup-memory allowance" both ok (round-1 symlink fail-safe
  fix and its regression test).

## Unrelated pre-existing flake

`test_status_tail_bounding`'s default-5-lines assertion ("missing:
'working: step 3'") fails identically at the target commit
(53dc5beecb428356) and at the base commit (48fb85bd8c14b835), reproduced via
`git archive` of the base commit into a clean checkout. Not a regression from
this branch.
- Outcome: ⚠️ 1 info across 1 run (42m34s)

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • ℹ️ 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.
⚠️ **Test** - 1 info
  • ℹ️ 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.
  • Live validation: ✅ go - 8 of 9 scenarios driven live against the product
Scenario Result Live Evidence
Context report surfaces what's driving limits usage (fm-context-report.sh) ✅ pass live Direct CLI run against synthetic transcripts: firstmate home grouped with 2 turns, mean 160000 tokens, 50.0% share above the 150k threshold; non-firstmate session excluded by default and included with…
config/context-hygiene = off disables the feature; absent/garbage value leaves it on ✅ pass live Direct calls to fm_context_hygiene_disabled with 'off', case-insensitive variants, an absent file, and a garbage value all matched the documented default-on/off-only contract.
Idle-clear only fires after a full continuous idle window (no premature clear) ✅ pass live fm_context_hygiene_idle_ready returned not-ready on the seeding poll and ready only after the configured window elapsed continuously.
Adversarial: an in-flight task, a non-empty wake queue, or a pending captain reply blocks the idle clear indefinitely (no missed wakes) ✅ pass live Each of a non-secondmate state/.meta record, a non-empty state/.wake-queue, and a state/pending-replies/ entry independently kept fm_context_hygiene_idle_ready from firing even after the idle window…
Adversarial: an unverified harness never receives a guessed context-reset command ✅ pass live fm_context_hygiene_command returned empty for an unverified harness name and the correct '/compact' for claude.
Durable compact marker survives until confirmed delivery ✅ pass live fm_context_hygiene_mark_compact wrote the marker with the focus line intact; fm_context_hygiene_clear_marker removed it only after an explicit call, matching the 'boundary reached while busy is not lo…
A verified PR merge and a completed teardown each queue the compact marker at the task boundary ✅ pass live Isolated real-script runs: test_verified_merge_records_pr_and_head against bin/fm-pr-merge.sh and test_local_only_merged_to_local_main_allows against bin/fm-teardown.sh both confirmed state/.context-c…
Watcher delivers the harness command only into a provably idle pane, pauses during AFK, and coalesces/backs off signals without dropping wakes ⏸️ untested no The prior payload marked this scenario 'pass' without a live result: no live tmux pane with a real Claude or Pi harness attached was ever driven in this sandbox, so no actual pane delivery, AFK pause,…
A symlinked/unmeasurable captain.md fails the startup-memory digest safe instead of silently counting as zero tokens (round-1 fix) ✅ pass live The real bin/fm-session-start.sh executed as a subprocess against a home with data/captain.md symlinked to a large file: output showed the truncation pointer to data/learnings.md and did not inline th…
  • bin/fm-context-report.sh --hours 24 --projects-dir <synthetic transcripts> (default, --all --json, missing root, bad --hours) run directly
  • bin/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.

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.
@adibirzu
adibirzu merged commit 3a71a11 into main Sep 14, 2026
41 of 43 checks passed
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