# Budget, pause and handoff

Scope: quota and native context readings, checkpoints, pause, handoff and resume, and the status line tee. Read before editing `src/hub/budget.ts`, `src/hub/window-kind.ts`, `src/hub/budget-notes.ts`, `src/hub/context-window.ts`, `src/cli/statusline-tee.ts`, `src/adapters/definitions/native-quota.ts`, `src/adapters/definitions/native-context.ts`, `src/hub/bus.ts`, `src/hub/delivery-journal.ts`, `src/hub/restart.ts` (pause persistence), the per-account fanout in `src/hub/instance-budget.ts`, the usage roll-up in `src/hub/usage-rollup.ts` or Kimi's count (`src/adapters/kimi-wire-usage.ts`, `src/hub/kimi-usage.ts`, `src/hub/token-window.ts`), or the exhaustion projection (`src/hub/budget-projection.ts`).

- Reviewer quota admission opt-outs (#1467): keep defaults `review.gate = 0.8` and `review.unknown_quota = "skip"`. `unknown_quota = "pass"` admits unknown observations only, retaining the known floor and never treating admitted unknown as quota-wait evidence. Gate `"off"` bypasses floor/unknown checks and all quota waits, while actual Budget/manual pauses and every other routing guard remain binding. Report the active rule through the shared policy description; do not turn an opt-out into a reading, account transport, cleanup release or resume path. Require `reviewer_quota` on recovery for explicitly configured unknown policy, including skip, or gate off.
- Reviewer quota (#1446): accept only the pinned native outer Claude/Codex refusal frames in `native-quota.ts`, or the narrowly documented Kimi nonzero owned-child complete-stderr exception. Never match assistant/tool/model text. Keep reset unknown unless a typed native timestamp supplies it; credits do not affect admission. Record the hard pause through canonical-account `Budget.report` immediately when an admitted frame is observed (Kimi stderr only after confirmed settlement), independently of task fallback. Defer handoff until that owned attempt settles; only the existing Budget reset/resume policy releases the pause.
- Reviewer-only quota observation reuses attached account siblings (#1440). Do not add a reviewer transport or infer early reset from prose. Without an attached source, recheck only at a proven reset timestamp and Budget's existing expiry grace, within the original `task_sweep.review_min` deadline (kept across restarts); do not claim early-reset observation. Kimi's observed 2.2.0 stderr exception has no reset and is unverified on 2.5.2, so it never authorizes quota waiting.
- Kimi reviewer accounting journals a host-only opaque attempt before spawn and requires its ACK, then reads owned native usage after group settlement and before profile cleanup (`readKimiReviewerUsage`, the single session of the fresh profile through `ownedKimiSession`); its rows join the one Kimi account count through `KimiUsage.observeReviewer` (deduped by row id), never `addTokens`. Journal terminal complete/unknown only after that read. Drop cached soft-token headroom on unresolved accounting; unmatched starts, incomplete replay or unknown terminal stay unknown across restart, with no expiry inferred from start/cap. Retain an incomplete private profile or unacknowledged terminal through the existing cleanup hold. Never log its home, native session, prompt or stderr.
- Budget: checkpoint first, pause second (a paused peer receives nothing). A handoff that fails is left unmarked so the next tick or hub run retries it; never record it as done.
- A handoff needs somebody to hand over to: `canHandOff` is false right after a restart, when no peer is attached yet, and the handoff waits for a later tick instead of stripping tasks of their owner.
- A reading has its own timestamp. Numbers that arrive through a file (`claude-usage.json`) carry the file's `at`; a window whose `resetsAt` has passed says nothing any more.
- On resume the notice is published before the peer is released, so it leads the first delivery.
- The coordinator only lifts its own pauses: `manualPaused` in the daemon keeps a `ahub pause` in place, and `ahub resume` refuses while a budget record is open.
- Codex quota reads (#1440): use the canonical account's open Budget pause to select the fixed 60 s poll, return to usagePollMs on resume, and unsubscribe/cancel polling plus pending-read timers on detach/stop. Keep resume in Budget's existing evaluate/expiry paths, never in adapters or Tasks. Keep only reset-credit count/proven-complete earliest expiry and ordinaryUsageAllowed/hasCredits/unlimited flags with measurement time; never retain balance, account id, credit ids or descriptions. A capped/missing detail list leaves expiry unknown. Credit flags never lift or prevent a pause.

- `Bus.pause` and `Bus.resume` are transient and write no bus snapshot (#1204): the bus's `paused` set is not in `BusSnapshot`. Each owner persists and re-applies its own pause (`budget_pauses` for a budget record, `setManualPaused` for `ahub pause`, `conductorHolds` for a conductor hold); never restore a pause from the bus snapshot or add a `persist()` back for one.
- The status line tee must never fail or slow the render: no throw, original command run with the same stdin, 5 s cap.

- Keep native context occupancy (`src/hub/context-window.ts`, readers in `src/adapters/definitions/native-context.ts`) separate from quota accounting; never use Codex's accumulated `total` as occupancy or estimate Pi counters. Host code reads quota and context only through `readNativeQuota` (`budget.ts`) and `readNativeContext` on the resolved definition's declared `budget.reader` / `budget.context`; no declared reader is unknown, never an empty reading (rule: `adapters.md`).
- Context checkpoint completion requires its request id and the current attached peer/native session. Invalidate its transport generation synchronously at a new peer claim, before asynchronous recall or attachment. Never pause, reassign or replace a session on context pressure; `ContextWindows.admission` (#802) only copies the reading for new-offer routing and never changes the crossing latch. Refuse private-turn, PII-pattern and all associated open PII-task summaries (owner or reviewer, including in_review, with the current routing policy; use `isClosedTaskState` to exclude approved and cancelled work) before local persistence or cloud memory; never broadcast checkpoint text.
- A quota or context checkpoint also snapshots each owned task's creation and ownership-change epoch (#1506). Before accepting a summary, require that task binding and the original peer/session to remain current. If ownership moved or the task was cancelled, refuse the stale answer with a body-free cause retained only until that request's original deadline; a new request replaces the refusal. A changed peer/session reveals no prior task ids.
- Invalid/stale context readings expose unknown and do not rearm a crossing. Latch a crossing only after its event is accepted; reconsider paused/recovery-held crossings after release with fresh current-session readings. Tee context fields contain finite numeric values or null only, bound to daemon instance, launcher and native session. Context and session go to the per-peer file `claudeStateFile(base, peer)` (the builtin keeps the unsuffixed name); `claude-usage.json` stays one shared file per account.

- A provider hard refusal ends a reading override and supersedes a soft evaluation still awaiting its checkpoint; never let the obsolete checkpoint overwrite that pause. An ACP provider quota refusal reports a hard budget reading and confirms the live pause before the adapter requeues work, so the pause fences retries and the existing relay handles assignments. Use the observed window length for an unknown reset; repeated quota refusals while paused do not consume poison-envelope retries, except for an `invocation` request: it gets at most one automatic retry, only when `canRetryInvocation` says so, paused or not (rule: `bus.md`).
- Kimi's ACP `{used, size}` occupancy is a context reading (`acpContext`, source `acp_usage_update`) bound to the adapter's own session id: never a `tokens` event or a budget window, and an invalid shape reports unknown, not the previous value. A gate crossing sends a checkpoint request only to definitions with `budget.checkpoint` (Claude and Codex); an ACP peer gets the event and the notice (#285).
- Jcode (#801): its ACP `usage_update` `{used, size}` is a context reading (`jcodeContextValue`, source `jcode_usage_update`, session-bound); its prompt result `usage` is per-turn consumption recorded as one `jcode_acp` `usage` event (`acpTurnUsage`, `onTurnUsage`) and never reaches `addTokens`, a token window or a budget window. Never read Jcode's `totalTokens`, never infer a quota window from either record, and keep a malformed, wrong-session or stale value unknown. Never read `jcode usage --json`. A later Jcode version repeats `docs/verification/2026-10-28-jcode-0.99.1-usage.md` before its readings are claimed.
- A quota resume notice replaces the peer's unread resume notices: carry their moves into the new one (`refs.budgetResumeMoves`, or the whole text of a notice that has none), publish it, and only then withdraw the ones it replaces, so a failed publish keeps them (#306).
- Quota handoff context reads `QUOTA_HANDOFF_PLATFORMS` (`src/adapters/registry.ts`, each definition's `hooks.recallPlatform`: claude, codex, kimi, qwen, jcode). It is independent of `hooks.recallInjected`: a handoff platform never joins the injected-platform exclusion in recall (`test/adapter-handoff-platforms.test.ts`).
- `Budget.report` resolves the reporter and its account through `hooks.definitionOf` (the daemon's startup-bound project catalog; builtin-only when absent) and skips `user`, `hub` and a registered kind, configured and external module kinds included, with no `budget` block or with `budget.quotaExempt` (only local); an unregistered id keeps quota accounting. `budget.instrumented` (execution budget) never exempts quota.

- Key quota readings, pause records, overrides, checkpoints and handoffs by the canonical account (`hooks.account`, idempotent); telemetry keeps the reporter id and native context occupancy stays per instance. `instanceBudgetHooks` fans pause, resume, checkpoint and handoff out to every member, and `canHandOff` excludes the paused account's siblings. Startup normalization merges old alias pause rows without dropping a row or marking an unfinished handoff done. A manual pause stays per member. Reviewer and headless implementer variants keep their base kind's `budget.account`.
- Release-cut quota admission (`releaseQuotaSnapshot` in `src/hub/daemon.ts`, #481 S11): an account has a quota source only when one of its members' definitions has `budget.reader`, or `budget.resetSoftTokensOnResume` with `kimi_tokens_5h > 0`. Without a source a registered account is reported `no quota source` and never defers; with one, an unknown, stale or below-gate reading defers. Manual and budget-record pauses defer for every attached peer.

- Window kinds (#285 AC6, AC8): classify a window only through `windowKind` (`src/hub/window-kind.ts`: `native`, `count`, `manual`); a reporter that knows its kind passes it (`ahub budget set` is `manual`, the Kimi count `count`). Readings are kept per window id and kind, never overwriting each other. The gate and `headroom` act only on `gating()`: a fresh `manual` reading replaces the others for its window, and the hub `count` never gates while a fresh `native` or `manual` reading exists. A hard refusal drops the `manual` reading of each window it reports. `status()` lists the gating reading first and marks the information-only fresh ones `superseded`; never gate or route from `status()` windows.
- No-quota notes (#285 AC6, AC7): a peer whose definition sets `budget.noQuotaReason` (Pi, local) gets a hub 5 h token count (`hubTokenWindows`, replayed at start through `TokenWindow.seed`) as information only, never a window, a meter or a gate. Build the notes in `ahub budget`, the console and the dashboard only through `budgetNotes` (`src/hub/budget-notes.ts`) from the definition and the counters, and Kimi's source state only from `KimiUsage.status()`: a rule and a count, never a path, a session id or log text.
- Keep `readClaudeTranscriptUsage` at its 32 MiB accounting bound. For native turn completion, follow the admission rule in `daemon.md`.

- Limit ledger (#683 U1): write `budget_pause`, `budget_resume` and `quota_reset` only through `Budget.writeLedger` (`hooks.ledger`), at the one pause INSERT in `evaluate` (a new pause that replaces an expired open record first writes that record's `budget_resume`, `by: "hub"`) and the one DELETE in `resume` (`by: "person"` only from `override`); never from a call site that reads `budget_pauses`. `quota_reset` is derived in `deriveResets` from the last reading of each window (`lastSeen`, never `readings`, which a resume clears): a forward `resetsAt` move of more than `RESET_JITTER_MS` (15 min), or a `used` drop of `RESET_DROP` (0.5) or more within one window, is a reset, and anything smaller is the same window. It is deduplicated by `peer|window|resetsAt` in `resetsRecorded`, which the daemon seeds from `events.jsonl` at start so a restart adds none. A reading older than the baseline never counts. Entries carry ids, windows and numbers only: never a reason built from agent text, a checkpoint, a summary or a task title (the reason is the coordinator's own text). A throwing hook never costs the pause or the reading. Codex's `usage` event comes from `onTokenBreakdown` beside `onTokens`; keep `tokens` unchanged.

- Usage roll-up (#683 U2): `src/hub/usage-rollup.ts` is the only reader of `events.jsonl` for `ahub usage`, the console Usage panel and the dashboard Usage view (rules: `daemon.md`). A pass reads from the stored offset, keeps whole lines only and commits its rows with the new offset in one transaction; its 20 ms slice (`poll(maxMs)`, #719) stops only between whole records and commits the offset of the last one folded; a line longer than the cap is read whole and one past `MAX_LINE_BYTES` is skipped, so the fold always advances. Never store a title, reason or summary there; `limit_events` drops `reason`. issue/pr/release are joined from the board at query time through `TaskLinks`, never stored. A counter with no record behind it is `unknown`, not 0. Claude's total is derived as the sum of its four counters (`claudeReportedTokens`); a source whose input contains the cached part gets none. Every `usage` reply, errors included, answers the rid, and the op is for the console and a configured planner only, never during that planner's private turn. A rebuild from byte 0 must equal the incremental result (`test/usage-rollup.test.ts`). Never present unknown as 0 in a sum: an overall figure with an unknown peer is `partial` and names the peers (`total().unknownPeers`). Never drop rows silently: `limits()` reports `truncated`, `omitted` and the bound. An event-open pause the hub no longer holds is `endedUnknown` (`ahub reset` keeps the log), so `limits(peer, { live })` needs the daemon's held pauses. A poll's fold transaction is IMMEDIATE and rechecks the stored offset, so two roll-ups on one `hub.db` never fold a range twice.
- Daily usage (#683 U4): `UsageRollup.daily(days, now)` returns the last `days` UTC calendar days (at most 366) ending today, clipped to the first day with a record. A day inside the window with no record is a row with `empty: true`, never zeros. Per peer and day, take the native total when reported, else the counted tokens (`count`), else `unknown`; a day's total is `partial` when some peers are unknown and `unknown` when all are, never a sum that treats them as 0.
- Kimi's consumption (#285 phase 2, delayed drain #1281, sliced drain #1283): `src/adapters/kimi-wire-usage.ts` is the only reader of Kimi's wire log and `src/hub/kimi-usage.ts` the only owner of the Kimi count; `daemon.ts` supplies ports (events, budget, clock, session id, unreferenced scheduler) and binds the session at a turn start (no read), calls `collectKimiUsage` at a turn end, a `usage_update` and an offline transition, and schedules at most three coalesced follow-ups (250 ms, 1,000 ms, 2,000 ms). With a scheduler, one invocation reads and commits one slice, then yields with a 0 ms continuation while the same cue's backlog remains (at most 16 slices per burst). Discovery is fresh on every slice; do not cache the agent set. Without a scheduler, the original synchronous 16-pass behavior remains for compatibility. Stop, offline and session replacement cancel delayed work; offline preserves the final synchronous `collect -> drop`, with rows durable only later as the documented ceiling. A native row time selects a unique interval among the most recent 32 captured turns; no unique match gives `unattributed`. Late rows never rewrite an earlier `turn_end` or increment a later turn. A successful reader slice commits offsets only after its rows are recorded; restart seeding counts only rows recorded after the last `budget_resume` of a soft-token peer (`kimiSeedRows`). Tests never reach the person's `~/.kimi-code`: `test/hub-home.ts` sets `KIMI_CODE_HOME` to a temp dir. Never feed `budget.report(kimi, tokens)` from an ACP total or an estimate, and never change `kimiCountedTokens` without the AC5 test: cache reads are recorded, not counted. An unreadable log, an unknown row shape or an untested `protocol_version` is unknown (reading dropped via `Budget.forget(peer, "tokens", "count")`, so only the count's own reading goes; one notice), never a partial count. A usage row's text never leaves the reader: four integers, a model label and the row time. A resume clears the window (`kimiUsage.reset()`).

- Controlled recovery with retained reviewer accounting/wait history or explicitly configured reviewer quota keys requires `reviewer_quota`. Bind accounting replay completeness and safe ordered journal commitment through the existing snapshot integrity; missing/changed journal refuses restoration before optimistic counts can be published. Empty legacy state keeps older-target compatibility.
- Exhaustion projection (#1513): `projectExhaustion` (`src/hub/budget-projection.ts`) stays pure. An unusable reading answers `unknown` with a cause, never a time. The page's `PROJECTION_CAUSE`/`projectionText` in `src/ui/index.html` must render the same sentence as `projectionText` in `budget-projection.ts` (`test/budget-surfaces.test.ts` runs the page copy).
