Repository navigation
feat(bin): add per-turn quota instrumentation with state fingerprint proxy - #1449
eduardstan wants to merge 6 commits into
Conversation
|
Automated reminder: thanks for the PR! This branch currently has a merge conflict with the base branch. When you get a chance, please rebase onto (or merge) the latest base branch, resolve the conflict, and push. After that, checks will re-run and the PR will get looked at again. Noted for firstmate#1449 at |
|
Automated reminder: thanks for the PR! This branch currently has a merge conflict with the base branch. When you get a chance, please rebase onto (or merge) the latest base branch, resolve the conflict, and push. After that, checks will re-run and the PR will get looked at again. Noted for firstmate#1449 at |
|
Automated reminder: thanks for the PR! This branch currently has a merge conflict with the base branch. When you get a chance, please rebase onto (or merge) the latest base branch, resolve the conflict, and push. After that, checks will re-run and the PR will get looked at again. Noted for firstmate#1449 at |
|
Automated reminder: thanks for the PR! This branch currently has a merge conflict with the base branch. When you get a chance, please rebase onto (or merge) the latest base branch, resolve the conflict, and push. After that, checks will re-run and the PR will get looked at again. Noted for firstmate#1449 at |
5ef7374 to
b017237
Compare
b017237 to
bde344d
Compare
…caching in turn quota
bde344d to
c31acef
Compare
Intent
Give firstmate the ability to measure its own token cost per turn with state fingerprint proxy and quota accounting
What Changed
bin/fm-turn-quota.shdispatcher over a writer/reader pair: the writer appends one tab-separated record per primary turn end tostate/quota-turns.log(wake kind, state fingerprint, and Claude/Gemini quota remaining), and the reader prints a summary with per-wake-kind breakdown and quota deltas. Both treat the fingerprint strictly as a proxy — missing hashers or absent probes record an explicit absent marker rather than a fabricated zero, and absent rows are excluded from the no-op ratios with the exclusion count disclosed.bin/fm-turnend-guard.shnow invokes the writer at primary turn end as a fail-safe observer (all errors swallowed tostate/.turn-quota-error.log, exit 0), gated on the consecutive-block ledger rather thanstop_hook_activeso a guard-forced continuation does not append a second record while genuinely new post-rewake turns still get measured.bin/fm-wake-drain.shstampsstate/.turn-wake-kindon every drain so each record is attributed to the wake that caused it.sha256sum/shasumandtimeout/gtimeoutfallbacks reuse the repo's existing helpers, bothquota-axiandantigravity-usageresults are mtime-cached, and the Gemini reading picks the scarcest dispatch-eligible pool instead of whichever model the tool lists first. Docs cover the new scripts, state artifacts, and the optionalantigravity-usageprobe;tests/fm-turn-quota.test.shand new turn-end guard cases cover reader math, absent-marker honesty, unknown-subcommand failure, and per-turn recording.Risk Assessment
✅ Low: The round-3 change is a narrow, correct replacement of an unreliable signal with the guard's own block ledger — every allow path clears the ledger so the skip can never outlive a single block chain, the post-rewake recording regression from round 2 is gone, and the behavior is directly covered by a new four-step test; only a cosmetic duplicate-jq simplification remains.
Testing
Ran the two directly affected test scripts plus the wake-queue suite (all pass), added one focused test for the Gemini accounting branch that had no automated coverage, and then demonstrated the feature the way the captain experiences it: a 6-turn simulated primary session driven through the real chain (wake drain stamping the wake kind, the real Claude Stop payload into fm-turnend-guard.sh --claude, the writer appending one row per turn), ending with the actual
bin/fm-turn-quota.sh reportoutput showing 6 turns, 50% proxy no-op, 1.42% Claude 5-hour per turn (2.83% per changed turn), Gemini deltas, and a per-wake-kind breakdown. The repo coverage guard fails under the machine's en_US.UTF-8 locale due to a comm/sort collation mismatch that reproduces identically at the base commit and passes under LC_ALL=C, so it is not attributable to this change; scratch demo state was removed and the worktree carries only the intentional test addition.Evidence: End-to-end turn quota CLI transcript (6 turns, raw log rows + captain-facing report)
turn 1 (captain) recorded turn 2 (signal) recorded turn 3 (heartbeat) recorded turn 4 (stale) recorded turn 5 (signal) recorded turn 6 (captain) recorded ### state/quota-turns.log (raw instrumentation rows) 1785564183 captain f7140af6ee40caf1 1 13.7 41.4 2026-08-01T10:01:00Z 14.5 2026-08-01T10:01:00Z 1785564184 signal d8e6fdc71d0720b4 1 15.4 41.8 2026-08-01T10:02:00Z 17 2026-08-01T10:02:00Z 1785564184 heartbeat d8e6fdc71d0720b4 0 17.1 42.2 2026-08-01T10:03:00Z 19.5 2026-08-01T10:03:00Z 1785564184 stale d8e6fdc71d0720b4 0 18.8 42.6 2026-08-01T10:04:00Z 22 2026-08-01T10:04:00Z 1785564185 signal c8c5b660b956050d 1 20.5 43.0 2026-08-01T10:05:00Z 24.5 2026-08-01T10:05:00Z 1785564185 captain c8c5b660b956050d 0 22.2 43.4 2026-08-01T10:06:00Z 27 2026-08-01T10:06:00Z ### bin/fm-turn-quota.sh report === Firstmate Turn Quota Report === NOTICE: Proxy state fingerprint metric used below cannot prove a turn was useless (e.g. answering the captain changes nothing on disk). Total turns: 6 Proxy no-op (fingerprint unchanged): 3 (50.0%) Proxy changed (fingerprint changed): 3 (50.0%) --- Quota Consumed per Turn --- Claude 5-hour: total delta 8.50% | 1.42% / turn | 2.83% / changed turn Claude 7-day: total delta 2.00% | 0.33% / turn | 0.67% / changed turn Gemini / agy: total delta 12.50% | 2.08% / turn | 4.17% / changed turn --- Breakdown by Wake Kind --- WAKE KIND TURNS FP KNOWN NO-OP (OF FP KNOWN) CLAUDE 5H DELTA stale 1 1 1 (100.0%) 1.70% heartbeat 1 1 1 (100.0%) 1.70% signal 2 2 0 (0.0%) 3.40% captain 2 2 1 (50.0%) 1.70%Evidence: Reproducible end-to-end demo script (drives the real wake-drain -> turn-end guard -> writer -> reader chain)
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
bin/fm-turn-quota-writer.sh:61- Fingerprint fallback fabricates a "no-op" instead of an absent marker.fpis built from asha256sumpipeline; when the pipeline yields nothing (missingsha256sum, unreadable state), line 61 substitutes the constant0000000000000000. Every subsequent turn then compares equal to that constant and recordsfp_changed=0, so the reader prints a fabricated "Proxy no-op (fingerprint unchanged): 100.0%". This violates the same absent-not-zero honesty invariant the suite already enforces for quota (tests/fm-turn-quota.test.sh:40"reader must never coerce missing Gemini quota to zero"). Emit anabsentfingerprint marker and have the reader exclude those rows from the no-op ratio instead of a constant.bin/fm-turn-quota-writer.sh:56- GNU-only tooling with no macOS fallback, contradicting the repo's own conventions. Line 56 usesls -l --full-time(GNU-only), line 57/59 use baresha256sum, and lines 79/104 use baretimeout. On macOS all three are absent by default, so: the .meta component of the fingerprint is empty, the final hash produces nothing (falling into the constant at line 61), and bothquota-axi/antigravity-usageprobes fail to 127 leaving quota permanentlyabsent— the entire feature silently degrades to a fixed fingerprint plus no quota data. The repo already owns fallbacks for exactly these:bin/fm-config-inherit-lib.sh:76-79(shasum -a 256/sha256sum) andbin/fm-quota-axi-lib.sh:26-31(timeout/gtimeout/perlalarm). Reuse them; replacels --full-timewith a portablestat(the same file already doesstat -c %Y || stat -f %mat line 75).bin/fm-turn-quota-writer.sh:104-antigravity-usageis invoked uncached and synchronously on every turn end, up to 3s of added latency per turn, whilequota-axigot a 15s cache (lines 72-81). The file header states "this writer must never block, delay, or fail a turn", andbin/fm-turnend-guard.sh:127calls it inline before the guard predicate, so the delay lands on the captain's turn-end path. Apply the same mtime-based cache file to the antigravity probe (or background the whole writer), so consecutive turn ends do not each pay a fresh subprocess round trip.bin/fm-turnend-guard.sh:127- The writer call sits before the guard predicate, so guard blocks manufacture spurious no-op records and mislabel wake kind. In--claudemode the guard re-blocks up to FM_CLAUDE_TURNEND_BLOCK_BUDGET times; each block exits 2, Claude continues, and the next Stop re-entersfm-turnend-guard.shand appends another record. Those continuation records almost always see an unchanged fingerprint (the continuation only arms the watcher), so every block event injects an extrafp_changed=0row and biases the headline "Proxy no-op" ratio upward. The first of those records also resetsstate/.turn-wake-kindtocaptain(writer line 141), so the continuation of asignalwake is attributed tocaptain. Additionally, codex/grok mode exits atfm-turnend-guard.sh:110whenstop_hook_activeis true, i.e. before the writer, so those harnesses do not record the same continuation turns — the metric is not comparable across harnesses.bin/fm-turn-quota-writer.sh:108- Gemini quota selection is order-dependent and may measure the wrong model.[.models[]? | select(.modelId | contains("gemini")) | .remainingPercentage] | firsttakes whichever gemini entry the tool happens to list first. Against the liveantigravity-usage --jsonon this machine that isgemini-2.5-pro, which is flaggedisAutocompleteOnly: true— not a model the fleet dispatches work to. If model ordering changes or the pools diverge per model, the recorded "Gemini / agy" delta silently tracks a different budget than the one being spent. Pin an explicit modelId (or take the minimum remaining across dispatch-eligible gemini models) rather than relying on array order.bin/fm-test-isolation-proof.sh:112- Thefm-test-isolation-proof.shchange is dead code carrying a false audit rationale.exclusion_reasonis only consulted fromlist_exclusions_for_report(line 184) over a fixed heredoc that does not includefm-turn-quota.test.sh, and the test is also absent fromlist_parallel_candidates, so adding the basename changes no behavior. Worse, it files the test under "watcher/wake/lock family; intentional process locks and daemon races" — the test uses no locks or daemons, and the same commit classifies itpure-contract-unitinbin/fm-test-run.sh:131. The block header states "Reasons are audit evidence; do not re-add a basename without clearing its reason." Drop the exclusion entry so the audit record stays truthful and consistent with the declared family.bin/fm-turn-quota-writer.sh:57- The|| echo "no-backlog"fallback can never fire: the pipeline's exit status isawk's, andawksucceeds with empty output even whensha256sumfails or the file is missing.backlog_hashbecomes the empty string instead of the intended sentinel, so a missing backlog and a present-but-unhashable backlog are indistinguishable in the fingerprint. Test the file with[ -f ](or capture and check the hash) before substituting the sentinel. The siblinghead_revon line 58 is a plain command and does work as written.bin/fm-turn-quota.sh:24- The dispatcher's catch-all*)branch execs the reader with the unrecognized token still in$@, and the reader ignores unknown args. A typo such asbin/fm-turn-quota.sh writsilently prints a report instead of recording a turn — the failure mode is a silently-missing measurement, not an error. Exit non-zero with the usage line for unknown subcommands (keeping the bare no-arg default asreport).bin/fm-turn-quota-reader.sh:39-c5_first,c7_first, andg_firstare initialized and assigned but never read — the report only uses the running*_total_deltasums. Dropping the three variables and their three assignment lines removes six lines of misleading dead state from the awk program.🔧 Fix: fix portability, absent fingerprints, and probe caching in turn quota
2 issues (1 error, 1 info) still open:
bin/fm-turnend-guard.sh:131- The newSTOP_HOOK_ACTIVE != "true"gate silently stops recording most Claude turns — the exact turns the feature exists to price. The gate treatsstop_hook_active=trueas "same turn re-entering after a block", but this same file states the opposite 85 lines above (lines 41-46): "Claude Code marks EVERY stop after ANY stop-hook-driven continuation stop_hook_active=true, including turns started by the asyncRewake auto-arm", anddocs/turnend-guard.md:54repeats it: "Claude Code setsstop_hook_active=trueon every stop after any stop-hook continuation, includingasyncRewakerewakes, which re-opened the 2026-07-21 blind window". That is precisely why--claudemode ignores the flag for the block decision. Concrete path:bin/fm-claude-stop-autoarm.shexits 2 with a rewake banner on any actionable arm close (signal:/stale:/check:/heartbeat); from that Stop onward every payload in the session carriesstop_hook_active=true, so line 131 skips the writer for every subsequent turn — including genuinely new, token-spending wake-handling turns. The log then contains only the pre-first-rewake turns, and the report's "Total turns" and quota deltas understate real cost by an unbounded margin, contradicting the intent's required "measure its own token cost per turn". Earliest supported shared boundary: the guard already cooperates with the auto-arm's event-epoch ledger (state/.claude-autoarm-epoch,FM_CLAUDE_AUTOARM_EPOCH_FRESH, documented as "one event epoch yields exactly one recovery turn") — dedupe the quota record on that epoch, or record unconditionally with a continuation flag in the row and let the reader collapse it. Non-Claude modes already get the one-row property from the pre-existing early exit at line 108, so they need no gate here.bin/fm-turn-quota-reader.sh:153- The per-wake-kind breakdown table cannot be reconciled by a reader:w_total(the TURNS column) counts all rows for that wake kind, whilew_pctnow divides byw_known(rows with a computable fingerprint). A wake kind with 4 rows of which 2 have absent fingerprints printsTURNS 4and1 (50.0%), where 50% is of 2, not 4. The summary section discloses its exclusion count (Fingerprint absent (excluded from proxy ratios)), but the table does not. Printw_knownas its own column or append the excluded count per row so the two numbers are self-consistent.🔧 Fix: gate turn quota on block ledger, disclose breakdown denominator
1 info still open:
bin/fm-turnend-guard.sh:127-PAYLOADis now parsed by two separatejqsubprocesses on every primary turn end: line 99 for the loop-guard flag and line 127 forsession_id. The second one was previously only reached on the re-block path; moving it above the writer gate puts it on the hot path for every turn in every mode. The existing filter at line 99 already has the payload object in hand — emitting both values from one invocation (e.g. a tab-joined"\(.stopHookActive // .stop_hook_active // false)\t\(.session_id // \"unknown\")"read with oneIFS=$'\t' read) removes a per-turn subprocess from the turn-end hook without changing behavior. Purely a simplification; the error-handling contract (both fall back to safe defaults, guard exits 0 on a malformed payload) must be preserved.✅ **Test** - passed
✅ No issues found.
bash tests/fm-turn-quota.test.sh(reader math, writer records, absent-marker honesty, CLI wrapper, unknown-subcommand failure)bash bin/fm-test-run.sh tests/fm-turn-quota.test.sh(family registration: pure-contract-unit)bash bin/fm-test-run.sh tests/fm-turnend-guard.test.sh(includes newtest_hook_claude_mode_quota_records_every_new_turn)bash bin/fm-test-run.sh tests/fm-wake-queue.test.sh(drain now stamps state/.turn-wake-kind)Added and ran new case:writer prices the scarcest dispatch-eligible gemini pool and ignores autocomplete-only poolsin tests/fm-turn-quota.test.shManual end-to-end:/tmp/no-mistakes-evidence/01KYX6JTVQS6V0RB4K8CN7JRYM/e2e-turn-quota-demo.sh— 6 simulated turns through bin/fm-wake-drain.sh +bin/fm-turnend-guard.sh --claudewith a healthy watcher lock and stubquota-axi/antigravity-usage, thenbin/fm-turn-quota.sh reportLC_ALL=C bash bin/fm-test-run.sh --check-coverage(passes; the default en_US.UTF-8 failure reproduces identically at base commit a805766)🔧 **Document** - 1 issue found → auto-fixed ✅
docs/configuration.md:273-bin/fm-turn-quota-writer.shprobes an optionalantigravity-usagebinary that no prose surface mentions. docs/configuration.md is the single owner of the toolchain list, but it enumerates required tools only, so listing an optional absent-tolerant probe there risks reading as a new bootstrap requirement. Left unedited as a judgment call; if operators should know Gemini/agy accounting is silentlyabsentwithout that binary, docs/configuration.md "Toolchain" is the place, as an explicitly optional note.🔧 Fix: note optional antigravity-usage probe in toolchain
✅ Re-checked - no issues remain.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.