# Hub events (`events.jsonl`)

Schema version 1. The hub appends one JSON object per line to
`.agenthub/state/events.jsonl`, next to `hub.log`. `hub.log` is for people; this
file is for tools (`ahub export`, `ahub report`, research measurements). The
version is bumped only when a field changes meaning or goes away; new fields and
new event types do not bump it.

## Rotation (#1546)

`events.jsonl` rotates by size: when the live file reaches 64 MiB the daemon renames it to `events.jsonl.<start>`, where `<start>` is the byte offset, in the one stream the segments and the live file make together, of the segment's first byte. Three rotated segments are kept. The oldest is dropped only when no open task could need it: it is kept while its last event is at or after the creation of the oldest open task, so the log may grow past three segments until that task closes, and `hub.log` says when it kept one. Readers (`ahub export`, `ahub report`, `ahub research backfill`, `ahub usage`, the startup seeds, `dogfood`) read the segments oldest first and then the live file, so they see the lines an unrotated file would have held; a byte offset is a position in that stream and survives a rotation. Dropped segments are gone: an offset below the oldest kept byte starts at the oldest kept segment, and a task whose first event was dropped is read from what the log still holds. `hub.log` rotates the same way at 16 MiB with two segments kept, by copy and truncate while the daemon runs (its stderr also appends to the file) and by rename at the next start.

Every event has `v` (schema version), `at` (ISO time) and `type`. No event ever
carries a message body or a task title or detail. Private (PII) envelopes are
marked `private: true`, and PII tasks `pii: true`.

| type | fields |
|---|---|
| `model_change` | `peer`, `previousModel` and `model` (previous/new desired override ids, null for inherited selection), `by: person`, `source` (`cli` or `dashboard`), `appliesFrom: next_turn`, optional `afterTurn` (an already existing hub turn id). The event records a person's desired-state change, not native model acceptance or provider availability; no future turn id, prompt or credentials. |
| `envelope` | `id`, `from`, `to` (absent for broadcast), `priority`, `hop`, `kind`, `task` (task id from refs), `bytes` (UTF-8 size of the body; absent on a private envelope, whose size would say something about the PII text), `private`, `dropped` (`hop` or `fyi` when not delivered) |
| `overflow`, `undeliverable` | `id`, `from`, `peer` |
| `stale` | `id`, `from`, `peer`, `task`: a notice about the recipient's open task, dropped unsent because, right before it would have been handed over, that task was closed, had another owner or was gone (issue #106) |
| `quiet` | `id`, `from`, `peers`: an agent message held back from these members of a silent turn-free cohort; its other recipients got it (issue #107) |
| `fact` | `peer`, `id` (the offer), `files` (files whose diff it carried), `plans`, `unknown` (files whose change it showed with attribution unknown), `named` (files under a named directory it named without a diff, those counted as "N more" or held back by the PII filter included), `bytes` (the injected text), `via` (`hook` for Claude, `steer` for Codex, `done` with an integration request), `ms` (the hub's time to build it), `hookMs` (the hook process's own start-up and connect time), `accepted` (whether app-server took the steer), `unanswered` (app-server did not answer it within 10 s: it may have gone in), `rttMs` (an accepted steer: from sending it to app-server's answer), `probe` (a context check), `coverage` (it named files earlier changes are not covered for): one fact offer (issue #108) |
| `fact_ack` | `peer`, `id`, `via` (`hook` and `steer`: a readback found the offer in the native session; `done`: the next `hub_task_done`), `ms` (from the offer): an acknowledged offer, the only thing that moves a peer's view |
| `route` | `peer`, `route`, `tier`, `source` (`override`, `dimensions`, `hold`, `classifier`, `default`; for `hub/auto` also `load`: a busy MLX slot moved it to `dgx/fast` (opt-in, `[pi] efficient_wait_ms`), `cooldown`: a cooling MLX went to its fallback first, and `pin`: an enforced tool loop went to the backend it is pinned to, issue #199), `score`, `ms`. Local decisions also carry `decision`, `turn`, optional numeric `task`, `pii`, and decision-time `severity`, `spinning`, `exploring`, `production`. A `hub/auto` decision for a request without a session key carries `stateless: true` (`ahub report` then counts its sessions as unknown). `hub/auto` and hub stage decisions carry `turnType` (`tool_result`, `user`, `compaction`: what the call answers) and `prefillTokens` (estimated input a backend would prefill; absent on a PII route), and, unless `stay_switch` is `off`, `staySwitch` (`shadow`, `enforce`), `plan` (`stay`, `switch`) and `reason` (`new_pin`, `compaction`, `context_fit`, `same_tier`, `override`, `tool_loop`, `prefill_bound`, `user_turn`): the planner's verdict next to the tier taken (issue #197). Decision routes additionally use source `decision`, `decisionMode`, `chosenAlias`/`chosenEffort` (null when the hub has no validated pick), `margin`, `decisionLatencyMs`, closed `decisionReason`, `fallbackApplied` and the decider provider/model/latency metadata (null when no decider was asked). In shadow, `tier` is still the actual heuristic choice; the proposed pair never replaces it. The decider metadata additionally carries optional `version` when the provider reports a pinned version; absent remains unknown, never inferred from the model id. R2 judge-choice observations additionally carry `decisionTarget: "judge"`; `tier` is the requested fallback judge alias, not a served-model identity, and the event has no purpose or phase field or executor label/usage credit. Off mode emits no judge observation. No prompt/evidence text, tool arguments, credentials or service error prose |
| `cooldown` | `peer`, `alias`, `event` (`start`, `end`), `failures` (consecutive transport or startup failures), `ms` (on `start`, how long the alias cools down): a relay backend alias after repeated failures (issue #199). An `end` is recorded at an HTTP answer (any status) or when the hub next checks the alias after it expired |
| `route_outcome` | `peer`, `decision`, `turnId`, `turn` (`completed` or `failed`), optional `task`, `pii`, `latched`, optional `next` (`severity`, `tests`: `pass`/`fail`/`none`, `repeat`) and `advisor` (`approve`/`redo`/`failed`). Exactly once per local decision at turn settlement, including failure/cancellation |
| `advisor` | `peer`, `route`, `trigger`, `verdict` (`approve`, `redo`, `failed`), `discardedChars`: an advisor check result; no transcript or feedback text |
| `progress` | `peer`, `task` (task id), `severity`, `spinning`, `exploring`, `production`: normalized tool activity dimensions for an open task; coverage differs by peer and no commands or task text are recorded |
| `stuck` | `peer`, `task` (task id), `category` (`repetition`, `false_progress`, `drift`, `desperation`, `capability_gap`), `streak`, `latched`: an escalation verdict; it recommends considering reassignment and never reassigns automatically |
| `capability` | `peer`, `state` (`verified` or `lost`), `via`: a peer's context path for facts |
| `memory_brief` | `peer`, `task`, `native`, `fails`, `claudeMem`: what a task brief carried, as counts (#258, docs/memory.md); the research record's `memory` block reads agent-mem's counters for the task, not new events (#1279, docs/research.md) |
| `preface` | `peer`, `bytes` (of the whole session preface block), `lines` (memory lines in it, those that start with `mem:`), `ordered` (true when observed use reordered the long-term section): one per peer per hub run, when the preface is installed (#1330). Numbers and a boolean only, never a line. |
| `hub_start` | `instance`, `personAttribution: true` (this run writes `task` and `attribution` on `permission`, `question`, `completion` and `agent_cli`, #1278; a log with no such start says nothing about which task a person interaction belonged to): a hub run began, written once it holds its control port and before any peer can attach (a daemon that cannot bind writes none); every peer counts as detached until its next `state` event |
| `tooling` | `peer`, `addons` (`{ name, version }` from a closed list, version null when unknown): the add-ons a peer works with, at each attach (#248, docs/research.md) |
| `native_turn_end` | `peer`, `id` (an opaque hash that names the completed turn): the end of a Claude turn, recorded once the hub finds the turn its Stop hook reported completed in the native transcript (Codex's is its `turn_end`), or the correlated final `turn.ended` of a Kimi TUI turn (#1282), or an agy terminal `Stop` of an active, fully idle turn, which carries no `id` and a closed `reason` (`user_canceled`, `error`, `max_invocations`, `max_forced_invocations`, `max_token_budget_exceeded`, `terminal_step_type`, `terminal_custom_hook`; #1280); quiescence evidence for an integration, never a hook payload, prompt or error |
| `supervision_turn` | `peer`, `turn` (the hub turn a supervision notice was delivered into, or `supervision-<uuid>` when none was open), `tokens` (when the adapter reported any for it), `ms` (from that turn's start, or from the delivery when none was open, to its native end): a completed native turn that received supervision, which `ahub report` counts; a failed delivery or turn, a peer that went offline or a changed native session records none |
| `conduct` | `peer` (the conductor, or `user` when the console releases a conductor hold), `action`, `task` (when the action names or creates one), `target` (the peer an assignment, start, hold or release names): one action of the conductor that ran, the structured twin of the console's `conductor` notice. `action` is a tool name without its `hub_` prefix: a conductor tool (`status`, `task_show`, `task_assign`, `task_escalate`, `peer_start`, `peer_hold`, `peer_release`), or one of the conductor peer's own task tools, which are not conductor tools (`task_propose`, `task_accept`, `task_decline`, `task_done`, `review`, `checkpoint`, `remember`). The role-free reads and redirects (a task's owner or reviewer with `hub_task_show`, its proposer with `hub_task_assign`) record none, and neither does `hub_task_list` |
| `agent_cli` | `peer` (`unknown` when the agent markers were invalid), `command` (the command and, where it has one, its subcommand, from a closed list; `unknown` otherwise; never an argument), `refused` (the CLI refused it before connecting: a human-only command, or an invalid identity; the daemon also writes this event for a conductor operation it admits or refuses on authority; for any other task command the CLI adds a second record with `refused: true` beside the up-front one only when the daemon's reply carries `authorityRefused: true`, which the daemon sets only for conductor operations, so any other failed task command, an unknown task or a role refusal by the hub included, adds none, #1547), optional `delegated: true` or `instructed: true` for the corresponding audited authority path: an `ahub` command run from an agent session. The hub reads these from the `cli-audit/` outbox, so `at` is when it read the record. From #1278 it also carries `task` and `attribution` (the `turn_end` rule) when the record is drained within 15 s of the command; an older record is `unattributed`, never matched to the task open at drain time. An `ahub instructed run` command (#1622) is not read from the outbox: the daemon writes one record itself, with `refused: false`, `instructed: true` and `instructionReceipt` (the opaque id of the instruction receipt the command consumed), after the receipt is consumed and before the command takes effect; `at` is the write time and it carries no `task` or `attribution`. If that record cannot be written, the command is refused and nothing runs |
| `hook_stats` | `peer`, `n` (facts hook calls in the turn, its Stop included), `startupMs` and `maxStartupMs` (the hook processes' start-up and connect time, summed and the largest), `hubMs` (the hub's own time for them): at Claude's Stop (issue #108) |
| `cohort` | `id`, `event` (`formed`, `joined`, `lifted`), `silent`, `tasks`, `owners`: owners of overlapping tasks formed a cohort, it changed membership, or it stopped being silent (issue #107). Recorded in every regime; only a turn-free project's cohorts can be silent |
| `split` | `task`, `where` (`routing`: routing chose the first owner of a task overlapping another owner's task not started yet, not an escalation, relay or reassignment, the record calibration reads; `cohort`: an overlap formed or changed a cohort), `verdict` (`split`, `single`, `unknown`), `single` (the peer that would finish both units alone soonest), `splitS`, `singleS`, `reason` (for `unknown`), `trace` (the inputs and steps: peer names, their profiles of versions and coordination, and numbers only): a shadow split prediction; it never changes the assignment (issue #109) |
| `state` | `peer`, `state` |
| `visual` | `id`, `kind` (`mermaid`, `comparison`, `table`, `beforeAfter`), payload UTF-8 `bytes`, image `files` count, optional numeric `task`: a bounded public visual was stored (#1058). Never the title, source, comparison/table text, path or image bytes. Ordinary delivery records carry only the visual stub and id. |
| `native_thread` | `peer` (`codex`), `thread` (its native thread id), `fresh` (`true` when the TUI started the thread, `false` when it resumed one): each thread the Codex adapter adopts, before any turn on it. The upgrade planner reads it: a thread with no rollout that the hub saw start, with no `turn_start` since, is planned as a fresh start (issue #215) |
| `turn_start` | `peer`, `turn` (`<peer>#<hub run>.<n>`, unique across restarts). A turn follows the adapter: pausing a busy peer does not end it |
| `turn_end` | `peer`, `turn`, `ms`, `tokens` (when the adapter reported any during the turn), `files` and `snapshotMs` (when snapshots are on: how many files the turn changed, and the time both snapshots took); optional numeric `task`, `attribution` (`delivery`, `single_open`, `unattributed`) frozen at turn start, `pii: true` for an attributed PII task; optional `model` and `modelEvidence`, both or neither (#1402): the model id the adapter observed for the turn, with how it was learned, strongest first: `served` (the provider or the native transcript named it for this turn's responses), `session` (the native session's current model id), `configured` (only the hub's own override or launch flag is known). An alias is recorded as the native surface reported it, never expanded; a label that fails the safe-label check is dropped with its evidence; optional `edits` (#1556 T2, only with `research.enabled`, never for a private turn, absent on a read-only turn): closed counts `obs` (`hook`, `stream`, `tree`), `arm`, `e` (edit tool) and `s` (shell route) as five counts each (total, verified full read, partial read only, blind or stale, rejected or blocked), `u` (tree writes no hook attributed), `fe`, `rev`. Never a path, a command or text; the operational view does not export it |
| `tokens` | `peer`, `n` (tokens added since the previous report), optional `source: kimi_wire` and opaque `id` (the native row, used to keep a partial-write retry exactly once), optional numeric `task`, `attribution` (`delivery`, `single_open`, `unattributed`), `pii: true` for an attributed PII task |
| `usage` | `peer`, `source` (`omniroute`, `claude_transcript`, `claude_result`, `codex_appserver`, `kimi_wire`, `jcode_acp`, `agy_transcript`), opaque `id`, optional `measuredAt` (provider/source time), the `requestedModel`, `servedModel` and `provider` labels, and any provider-reported counters (`inputTokens`, `outputTokens`, `cacheReadTokens`, `cacheWriteTokens`, `reasoningTokens`, `totalTokens`); optional numeric `task`, `attribution` (`delivery`, `single_open`, `unattributed`), `pii: true` for an attributed PII task. Missing counters stay unknown. |
| `task` | `id`, `event` (the board history event, e.g. `proposed`, `assigned`, `done`, `check failed`, `blocked`, `ready`), `by`, `state`, `owner`, `reviewer`, `class`, `pii`, and `reason` when the board recorded a move reason (`manual`, `budget`, `offline`, `idle`, `rejections`, `declined`, `inference_failed`, `delivery_failed`, `step_limit`). The research record (docs/research.md, #1277) reads these for every terminal task, approved or cancelled; no new event type was added |
| `overlap` | `task`, `owner`, `others` (`task`, `owner`, `paths`, and `symbols` when plans name the same symbol; a name that matches a PII pattern is left out, so either list can be empty), the structured twin of the console notice |
| `permission_mode` | `peer`, `from`, `to` (`ask`, `ask-when-needed`, `never-ask`): a person set a peer's permission mode (`from` equals `to` when it was already in force) or confirmed a never-ask default (issue #242) |
| `settings` | `key` (a registry key such as `permission.kimi` or `routing.classes.implement.peers`), `from`, `to` (the value before and after: the one in force for a setting that applies at once, the stored one for a setting read at a start; a closed word, a boolean, a number, a list of peer ids, a route id, or null for none), `source` (`dashboard`, `terminal`, `conductor`), optional `peer` and `reason`, and `undo: true` for an undo: a person changed a setting from the dashboard or `ahub settings` (issue #269). A mode change also writes its `permission_mode` event |
| `permission` | `id`, `peer`, `event` (`requested`, then one of `answered`, `expired`, `cancelled`) and, on the closing event, `latencyMs`, `surface` (`console`, `dashboard`, `terminal`: where a person answered; absent when the hub closed the request) and `option` (the kind of the option chosen: `allow_once`, `allow_always`, `reject_once`, `reject_always`): one approval request relayed to the console and how it ended. `expired` is `approvals.timeout_s` without an answer. `cancelled` with a `surface` is a person's deny in the console or by `ahub permit <id> deny` (a deny on the dashboard is `answered` with a reject option); without one, the hub withdrew the request (its call or turn ended, the peer was stopped, or the hub is stopping). Never the title or the tool. From #1278 it also carries `task` (a board task id) and `attribution` (`delivery`, `single_open`, `unattributed`, the rule `turn_end` and `tokens` use; `task` is absent when unattributed), resolved when the event's subject opens (a permission when requested, a question when asked, a completion's run when it starts) and repeated on every later event of it, so an answer given after the task closed still names the task it was asked under; `pii: true` when that task is PII. Ids and a closed word only. |
| `question` | `set`, `peer`, `event` (`asked`, `answered`, `pending`, `superseded`, `cancelled`, `expired`, `unavailable`) and, where they apply, `latencyMs`, `person` (for `surface: acon`, the console's verified identity; for `surface: conductor`, the conductor peer id), `surface` (`terminal`: `ahub answer`; `console`: the `A` key; `dashboard`: reserved, no surface sets it today; `acon`: the plugin's answer with the console's person meta; `conductor`: an instructed conductor answer), `reason` (`superseded`, `stopped`, `turn_aborted`, `session_changed`, `expired`, `unattended`), `questions` (a count) and `private`: one question a peer asked the person through `hub_ask` and how it ended (#1053). Never a prompt, an option, an answer or any other text. The attention need a question raises (`question`, in `status.needs` and `attentionItems`) is not an event: it carries the set id, the peer and the time only. From #1278 it also carries `task` (a board task id) and `attribution` (`delivery`, `single_open`, `unattributed`, the rule `turn_end` and `tokens` use; `task` is absent when unattributed), resolved when the event's subject opens (a permission when requested, a question when asked, a completion's run when it starts) and repeated on every later event of it, so an answer given after the task closed still names the task it was asked under. A question answered after the hub restarted while it was open (or after the bounded map dropped it) is `unattributed`, never the peer's task of the moment: the opening answer lives in memory only; `pii: true` when that task is PII. Ids and a closed word only. |
| `completion` | `id`, `peer`, `outcome` (`done`, `failed`, `limit`, `interrupted`), `ms` (start of the run to settle): a run a person started settled (#1054). A run starts at the `turn_start` that consumes the person's message and settles only when the adapter's `settle` signal fired and nothing else is pending (no queued continuation, open permission or question, owned child, running check, held delivery, native background task or unknown native inventory); a restart or launcher loss cut short settles `interrupted`, once. An explicit person Stop and a budget pause create none. Never the prompt, the reply, an error, a task command or any other text: the envelope ids live in `hub.db` and are read through the usual privacy path; native-person results are private stubs. From #1278 it also carries `task` (a board task id) and `attribution` (`delivery`, `single_open`, `unattributed`, the rule `turn_end` and `tokens` use; `task` is absent when unattributed), resolved when the event's subject opens (a permission when requested, a question when asked, a completion's run when it starts) and repeated on every later event of it, so an answer given after the task closed still names the task it was asked under; `pii: true` when that task is PII. Ids and a closed word only. |
| `completion_seen` | `id`, `surface` (`terminal`, `console`, `dashboard`, `acon`): a person marked a result read (#1054). One per receipt written, never from a snapshot read or a listing, never the prompt or the reply. `surface` is where the person marked it: `dashboard` is the Results section of `ahub ui` and of the acon panel (the panel's own buttons), `acon` is the acon inbox's `result_seen` or "Mark all read" with the console's verified person meta, `terminal` is `ahub results`. Mark-unread deletes a receipt and records no event. The detail line shown beside a result (the head of the starting prompt) is built at display and is in no event |
| `pii_screen` | `task` (absent for a budget hand-off or a note not about a task), `item` (`task`, `summary`, `review note`, `handoff`, `note`), `label` (`pii`, `clear`), `source` (`regex`: a pattern matched and no call was made; `screen`; `unknown`: no verdict, handled as PII), `category` (`name`, `student_id`, `phone`, `address`, `grade`, `health`, `other`), `miss` (why there was no verdict: `too long`, `off campus`, `timeout`, `unreadable`, `failed`), `ms` (absent for `regex`): one PII screen verdict while `signals.pii_screen = "local"` (issue #198); never the text |
| `checkpoint` | `peer`, `reason` (`quota`, `context`), `fields` (the names, from `done`, `in_progress`, `next`, `verified_by`, `traps`, of the structured fields the saved checkpoint carried; an empty list for a summary-only one): one per `hub_checkpoint` the hub accepted (#1331). Never the checkpoint text. |
| `context_pressure` | `peer`, `source` (`claude_statusline`, `codex_token_usage`, `acp_usage_update`), `measuredAt` (epoch ms of the reading), `used` (the fraction of the context window in use, 0 to 1), `window` (its size in tokens, or null): a fresh reading of a peer's native context reached `context.gate`. Recorded once per crossing, until a reading below the gate or a new native session rearms it, and not while the peer is paused or offline or the hub is in recovery or stopping |
| `quota` | `peer`, `windows` (`id`, `used`, `resetsAt`), `hard`, `measuredAt` (when the reading was taken; older rows omit it when the reading was current) |
| `budget_pause` | `peer` (the account), `reason` (the coordinator's own text: window id, percent and source), `window` (`5h`, `week`, `tokens` or `unknown`), `resetsAt` (epoch ms), `by` (`hub`). Written where the pause record is written (#683). |
| `budget_resume` | the same fields; `reason` says why it ended and `by` is `hub` (the window reset, or usage fell back under the gate) or `person` (an `ahub budget resume` override). A pause replaced by a new one after its window reset gets a `budget_resume` first (reason `replaced by a new pause after its window reset`). `ahub reset` clears pauses without writing one, because it keeps `events.jsonl` untouched. |
| `quota_reset` | `peer`, `window`, `cause` (`resets_at_moved`: the window's `resetsAt` moved forward by more than 15 minutes, since a provider's `resetsAt` wobbles by seconds inside one window; `used_dropped`: `used` fell by 0.5 or more inside one window id), `resetsAt`, `previousResetsAt`, `used`, `previousUsed`, optional `measuredAt`. Derived from two readings, one entry per peer, window and `resetsAt`, also across a restart. |
| `conflict` | `peer`, `task` (its task in progress, when it had one), `other` (the other owner's open task), `owner`, `paths` (names that match a PII pattern left out, so it can be empty), `concurrent` (another peer worked during the turn), `turns` (the two turn ids, when two overlapping turns' snapshots both hold the change) |

The hub also writes `release_authorization`, `role`, `config_edit` (for an instructed `ahub sdlc configure`, #1432: `by` names the session that ran it, `source` is `conductor` when that was not the console user, and `instructionClaim: person_direct_instruction`), `sdlc_config_instruction` (`by`, the key `paths`, `instructionClaim`; no value: the intent record written before that edit, which writes nothing if it cannot be retained), `reviewer_accounting` (`peer` as the account, an opaque `attempt` id and `outcome` `started`, `complete` or `unknown`: an owned reviewer run on the Kimi account, whose `kimi_wire` usage counts toward `budget.kimi_tokens_5h`, #1466; never a native session, home or model text), `invocation`, `attach` and `planning` events, and optional fields not listed above; `HubEvent` in `src/hub/events.ts` is the full schema.

Token usage by adapter:

- Kimi (#285 phase 2, delayed drain #1281): consumption is the hub's own count of Kimi's session wire log, never an ACP total. The `{used, size}`
  `usage_update` Kimi sends is context occupancy: it is shown as the peer's native context reading (source
  `acp_usage_update`, phase 1) and writes no `tokens` event. The reader (`src/adapters/kimi-wire-usage.ts`, the only code that knows
  the format) finds the session directory from `session_index.jsonl` (resolved with `realPath`, kept inside `<kimi home>/sessions`)
  and reads `agents/*/wire.jsonl` incrementally from saved offsets, sub-agents included, at a turn end, when a `usage_update`
  arrives and when the peer goes offline. A turn start only binds the session and fixes the history floor, it reads nothing. Each cue
  also schedules at most three follow-ups, after 250 ms, 1,000 ms and 2,000 ms, coalesced into one pending drain per peer with
  unreferenced production timers. Stop, offline and session replacement cancel them. The offline path keeps its final synchronous
  `collect -> drop`; a row durable only after that read remains uncollected, a documented ceiling. One call reads at most a fixed
  byte bound across all of the session's files (the rest waits for the next call), and two agent entries that are one file count once.
  A successful reader slice commits its offsets only after its rows, `seen` ids, events and window entries are committed, so a failed
  event or cancellation cannot advance past an unrecorded row. Each `usage.record` row becomes a `usage` event
  (`source: kimi_wire`, `inputTokens` = Kimi's `inputOther`, `outputTokens`, `cacheReadTokens`, `cacheWriteTokens`, `totalTokens`
  including cache reads, `servedModel`, `measuredAt` = Kimi's row time) and a `tokens` event of the counted share. The id is an
  opaque hash of session, agent and byte offset; no path, session id or text reaches an event. Only the four integers, the model
  label and the time are copied from a row. The counted share is `inputOther + inputCacheCreation + output` (`kimiCountedTokens`,
  one function): cache reads are recorded and shown, never counted against `budget.kimi_tokens_5h`. The rolling 5 h sum of the
  counted share against that ceiling is the `tokens` window (`hub count, kimi wire log, of kimi_tokens_5h N`, kind `count`: #285 phase 4 names each window's kind in the budget reply, never in an event, and a person's `ahub budget set` value, kind `manual`, outranks it at the gate). Rows already in the
  session's log when the hub first sees it (a resumed session) are history and are not counted. A row's native time selects one of
  the 32 most recent captured turn intervals; no unique match, an evicted interval or an ambiguous time gives `unattributed` with no
  task id. Rows collected before a turn closes keep that turn's `turn_end.tokens`. Late rows update `usage`, `tokens`, the roll-up
  and soft-quota window, but never rewrite an earlier `turn_end` or increment a later turn. An unreadable index, a missing,
  shrunk or replaced file (a replacement is told by a hash of the consumed head and tail kept with each offset, since Linux can reuse the inode), a truncated last line, an unknown row shape or an untested wire `protocol_version` (only 1.5 is known)
  makes the count unknown: one notice (`kimi usage unknown (<reason>)`), the `tokens` reading is dropped, and no figure is reported
  until the 5 h window the gap touched has passed (a transient read error or truncated line heals on the next read). Wire format
  followed: protocol 1.5 as written by Kimi Code 2.3.0 (the issue read 2.1.1; the verified Kimi versions are listed in `compat.ts`). The
  AC11 receipt is [2026-10-25-kimi-usage-ac11.md](verification/2026-10-25-kimi-usage-ac11.md); the current native timing and
  attribution receipt is [2026-11-07-kimi-delayed-usage.md](verification/2026-11-07-kimi-delayed-usage.md).
- Codex (app-server `thread/tokenUsage/updated`): recorded as the growth of the thread's running total, so
  compaction estimates, usage-limit refreshes and the replay to a reattaching connection add nothing. A thread
  started under the hub counts from zero; a resumed thread's first update is its history and only sets the
  baseline. The model call of a compaction itself is real usage and counts.
  Each update that adds tokens also writes a `usage` event with source `codex_appserver`, beside the unchanged `tokens`
  event: `inputTokens`, `cacheReadTokens` (cached input), `outputTokens` and `reasoningTokens` are the growth of
  Codex's own counters, with the same baseline rule, and `totalTokens` is the growth of `totalTokens`. Codex counts
  cached input inside input and reasoning inside output, so `inputTokens + outputTokens` equals `totalTokens` and the
  other two are shares of those, never added again. Replaying 55 real updates of a recorded Codex 0.163.0 session through the proxy handler gave the same totals as the recorded counters, with 98 percent of the input cached. Codex 0.163.0 also reports `cacheWriteInputTokens` (0 in every update of that session); the hub does not read it yet, so a nonzero value would be missing from the breakdown until a later slice adds it. The id is unique per hub run, peer and sequence and never carries the native thread, since usage telemetry has no session id. The ledger events
  carry ids, windows and numbers only: no checkpoint text, summary or task title.
- Pi: the assistant usage its extension forwards at each `message_end`, tool-loop messages included, is recorded as
  increments, each usage id once; a message without a usable count adds nothing.
- Claude native transcript usage is optional and keyed by an opaque hash of session and message identity; streamed records with the same message id count once. The status line tee also records bounded native context counters separately from quota percentages.
- The local worker records optional counters returned by OmniRoute. Requested route/model and gateway-reported served model/provider are separate fields; an alias is never treated as a served model.
- `ahub report` deduplicates usage records by peer, source and id. Coverage counts distinguish calls with provider usage from calls where usage was absent. Token counters are provider-reported values; the report never derives a price or treats missing spend as zero. Estimated price and measured provider spend remain unknown unless a future source reports them.
- Usage telemetry has no prompt, completion, task text, credential, Access header, session id or transcript path.
  Jcode (#801): each prompt whose result carries a well-formed `usage` writes one `usage` event with `source: jcode_acp`, `inputTokens`, `outputTokens`, `cacheReadTokens` and `cacheWriteTokens` when present, and task attribution; never `totalTokens` (Jcode's adds the cached read to an input that already holds it for OpenAI-style providers), never a `tokens` event, and no session id, text or path. The id names the hub run, the peer and a per-run sequence.
- agy (#1280): each transcript step row with token counts, read through the hook-gated transcript readback, writes one `usage` event with `source: agy_transcript`, `inputTokens`, `outputTokens`, `cacheReadTokens` and `totalTokens` (their sum), and a `tokens` event of `totalTokens` when it is above zero. The id is an opaque hash of session and step, counted once across restarts. A row the active turn produced takes that turn's attribution; any other row is `unattributed`.

## The usage roll-up (#683)

`ahub usage` does not read `events.jsonl` on each call. The daemon folds it into `hub.db`: `usage_rollup` (day, peer, model, source, task and the private mark, with the sum of each provider counter and how many records carried it), `token_rollup` (the hub's own `tokens` increments), `limit_events` (every `budget_pause`, `budget_resume` and `quota_reset`, without the reason text), `usage_points` (#1513: per hour, peer and `native` or `count`, the tokens each record spent and how many records added to it; the quota forecast in `ahub budget` reads it, taking the provider's figure for an hour a provider reported and the hub's own `tokens` count otherwise, so an hour is never counted twice) and `rollup_state` (the byte offset and the first event's time). Each `usage` record is counted once by peer, source and id, as `ahub report` counts it. The roll-up holds ids and numbers only, so a title cannot reach it. A sum is shown only where at least one record carried the counter, otherwise it is unknown.

## Per-task usage reports

`ahub report --by task` (also `--json` and `--since`) reads only `events.jsonl`.
It reports task ids, the latest recorded class/outcome, completed logical turns,
and wall time from the first `in_progress` task event to the first `approved`
event. Wall time is unknown if either boundary is absent or the latest outcome
is not approved. Each task and class rollup includes per-peer native token
increments and provider-reported input/output/cache/total counters. Usage is
deduplicated by peer, source and id; missing counters are `null` in JSON and
`unknown` in text, with known-record counts alongside measured subsets. A
missing task history has unknown class/outcome and belongs to the unknown class
rollup. PII tasks have ids and a `pii: true` flag, never titles. No prices are derived.
Each task also carries `person`, the person's interactions from `permission`,
`question`, `completion` and `agent_cli` events (the research record's figures,
docs/research.md), null for a task that began before the first `hub_start` with
`personAttribution`; person events no task owns are counted apart by peer and as
`unattributed`, never folded into a task (#1278).

At write time, the first applicable attribution rule wins:

- `delivery`: the current turn's original delivery names exactly one distinct positive task id, including work by a peer that does not own it.
- `single_open`: otherwise the peer owns exactly one `in_progress` task.
- `unattributed`: otherwise no task is assigned to the record.

`Bus.onDeliver` observes originals immediately before `peer.deliver` starts the
turn. Pending task identity is consumed at turn start and cleared on delivery
admission/failure, so later user-started native turns do not inherit it. Usage
and token events apply the rule at write time, except that a delayed Kimi row uses the unique captured turn interval selected by its native timestamp, never the later open task. `turn_end` keeps the start-time
attribution. Local usage uses its request-bound route policy task when present.
The existing relay has no task-bearing route usage event; this change adds no
new usage source. Schema version 1 and the control protocol are unchanged.

The unattributed share is always printed for token increments and deduplicated
usage records, against all recorded increments/usage records. A zero denominator
has unknown share. Records with no `attribution` field belong to a separate
`before attribution` bucket displayed beside the share, even if a task field is
present. Neither bucket is redistributed. `ahub export` preserves these fields
as raw JSON lines; plain `ahub report` keeps its existing behavior.

The file is local and never uploaded. It grows without rotation; delete it to start
over (the hub recreates it).

## Judge model-choice observations

A `route` row may carry exactly `decisionTarget: "judge"` to identify a separate
model-choice observation for an optional host judge. An absent target retains the
executor contract. The row's `tier` is the requested fallback judge alias, not a
served model; `source` is `default`, and any decision fields are the existing
validated service metadata. It introduces no purpose, phase, served or applied
field. Off mode emits no such row. It is published through existing `onRoute`
only after current privacy/observer/turn confirmation, bypassing executor
`addDecision`, labels, progress, usage and cost credit.

Executor reports exclude these rows before timestamp or switch accounting;
research excludes them before task/cohort/peer accumulation; the owned routing
corpus excludes them before collecting its last executor observation. They have
no outcome decision id and are not execution examples. The raw research-quality
event-type census still counts them as recorded metadata. Raw event export keeps
the target; the closed operational projection withholds the entire `route` kind
as before, so this adds no console display feature.

## Offline route outcome joins

For local-worker decisions, join `route_outcome.decision` to `route.decision` (one-to-one).
The route row records the chosen tier and decision-time dimensions; `next` describes only
the tool results answering that response, not an aggregate over later unrelated calls.
A final no-tool response has no `next`. Advisor checks add their closed verdict.
`latched` includes escalation that occurred later in the same turn.

Join `route.turn` or `route_outcome.turnId` to `turn_start.turn` / `turn_end.turn`.
The outcome's `turn` field is the completion status, not the turn id. To add offline
review supervision, join `route.task` to `task.id` and inspect subsequent task events
whose `state` is `approved` or `changes_requested`. Keep their timestamps so a review
from a different task revision is not treated as immediate per-call evidence.

Exclude both decisions and outcomes with `pii: true` before exporting a training set.
Labels contain ids, numbers, booleans and closed values only; they never retain tool
output, task text, advisor feedback, or raw failure fingerprints. A failed telemetry
sink does not affect model selection, budget admission or delivery. Pi outcome labels
are deferred: its existing route events retain their original shape. No control WebSocket
message changed, so the protocol number is unchanged.

Progress coverage is asymmetric: Codex contributes completed command and file-change items, local and Pi contribute
per-model-step tool observations, and Claude contributes tool inputs from turn-free pre-hooks without tool results or
a native turn id. Missing peers or intervals therefore mean unobserved, not zero activity. Escalation uses only known
native turn ids; observations without one still contribute progress dimensions but cannot establish separate attempts
or the eight-turn spinning threshold.

Quota rows record the first reading, material changes and a 15-minute heartbeat; pending last readings are flushed before a long silence or clean shutdown. `ahub report` counts recorded quota rows and hard rows, not provider polls. JSON retains `quota.readings` and `quota.hard`.
