Skip to content

Metering schema — as-built specification

Companion to docs/spec/implementation/README.md (requirement 33a) and docs/spec/review/requirements.md (R16), and referenced by docs/spec/dashboard/README.md. This document is the field-by-field contract for the per-stage, per-cycle token and cost accounting both pipelines produce: field names, types, units, aggregation rules, and a stability policy for changing any of it later. Like its companions it is as-built — it describes the metering data that exists today, not a plan for data that will exist later. Where it says “requirement N”, it means requirement N of docs/spec/implementation/README.md.

Two related things carry the pipelines’ spend data, and this document is the contract for both:

  • The per-stage metering record, attached to every stage-end / review-stage-end event in log.jsonl / review-log.jsonl (requirement 33a): what one invocation of claude cost, how long it took, which model it ran, and how many tokens it moved.
  • The per-cycle and roll-up aggregates the monitoring dashboard computes from those transcripts across both pipelines’ history (docs/spec/dashboard/README.md): a cycle’s total cost, and fleet-wide spend by day, by model, and by actor.

Both derive from the same upstream source: the JSON envelope in <stage>.out (dashboard spec, “cycles/<cycle-id>/<stage>.out”) — the result event of the stage’s own stream, which run_model_stage truncates into that file and which is byte-for-byte what the substrate’s own non-streaming output format would have written there before the pipelines began streaming (requirement 4d). This document does not restate that envelope’s own schema — that is the stage’s own provider’s contract, not this repo’s, and only a subset of it is used here. It documents the fields this repo depends on, the shape it derives from them, and the guarantee it makes about that shape going forward. It is still described in Claude Code’s own terms (issue #2133’s provider field, below, names which provider a given record actually ran on). Grok Build’s own raw envelope is a second upstream source — its streaming-messages-json terminal result line, as docs/reviews/2026-10-06-grok-build-evaluation.md §3 records it — but a success envelope already carries total_cost_usd/duration_ms/num_turns/ is_error/modelUsage unchanged, and a failure envelope is normalised onto the same vocabulary before metering_fields ever reads it (lib/substrate-grok-build.sh’s own adapter boundary, issue #2134). So this document’s field table holds for either provider’s envelope without a branch of its own; only the two Claude-specific terms this document’s own “Stability policy” section names below (total_cost_usd, modelUsage) are, for a Grok record, the adapter’s own normalisation rather than the CLI’s.

Carried on every stage-end (agent-cycle.sh) and review-stage-end (review-cycle.sh) event, alongside that event’s existing stage/repo, exit_code and — when one of requirement 4e’s two caps ended the stage — kill_reason fields (requirement 33). Those are the event’s own, not part of this record: kill_reason describes how the stage ended rather than what it spent, and a reader that wants to exclude killed runs from an aggregate selects on it rather than on anything below. Produced by lib/metering.sh’s metering_fields — the one implementation both pipelines call, so a stage in either emits the same shape.

Field Type Unit Meaning
model string — The model id passed to the invocation (the same string config.json names, resolved per lib/model-id.sh). Always present, including on a stage that never ran: it is what the invocation was asked for, not something read back out of the envelope.
provider string — The provider model resolves to (lib/model-id.sh’s MODEL_PROVIDER, issue #2133) — anthropic for a Claude Code stage, xai for a Grok Build one (issue #2134), or whichever name a configured providers entry gives a third. Always present, for the same reason model is: it is read off the id the invocation was given, not out of the envelope, so it is never affected by whether the envelope itself is readable.
lane string | null — The credential lane this invocation actually ran on — api or subscription (issue #2239, D30) — read off the stage’s own stream, never assumed from what was intended: the substrate’s _lane_of operation (lib/substrate-claude-code.sh) maps the stream’s first system/init event’s apiKeySource (none → subscription; ANTHROPIC_API_KEY, apiKeyHelper or /login managed key → api), and lib/stage-run.sh passes the result to metering_fields beside the gap statistics. null when the stream carries no readable answer — a stage that never ran, one killed before its first byte, or an init event in a vocabulary this adapter does not recognise — and that null is never coerced to a guessed lane. Distinct from stage-start’s own lane (requirement 33), which is what the Script intended before the run happened; the two may disagree, and a mismatch there is informational only. Distinct too from the lane run_model_stage itself forced the launch onto (issue #2241, D30): that forced lane is verified against this same observed one, read off the same stream, while the stage is still running — a mismatch there is not informational, it stops the stage outright (kill_reason: "lane-mismatch", requirement 4e), except for a forced subscription launch whose apiKeySource reports a Console login (/login managed key), which the draw’s own rule treats as expected rather than a fault.
cost_usd number | null US dollars The envelope’s own total_cost_usd — a client-side estimate the provider’s own CLI computes from token counts, not a charge or a draw against any plan limit (docs/spec/dashboard/README.md’s design decision on plan limits makes the same point about the dashboard’s own cost figures). Includes any subagents the stage’s own invocation spawned. null if the envelope is missing or unparseable.
duration_ms integer | null milliseconds The envelope’s duration_ms: wall-clock time for the invocation.
num_turns integer | null count The envelope’s num_turns.
is_error boolean | null — The envelope’s is_error.
tokens object | null — Token counts by kind, summed across every model the invocation’s own tree used — see below. null if the envelope carries no readable modelUsage entry: an absent, empty or malformed map, or an empty/missing envelope.
tokens.input integer tokens Sum of each model’s inputTokens.
tokens.output integer tokens Sum of each model’s outputTokens.
tokens.cache_creation integer tokens Sum of each model’s cacheCreationInputTokens — tokens written to the prompt cache.
tokens.cache_read integer tokens Sum of each model’s cacheReadInputTokens — tokens served from the prompt cache.
gaps object | null — How long the invocation went between one piece of output and the next — see below. null means the record was not measured (a stage that never ran, or a record derived after the fact from an envelope alone), never that the run was continuously busy: every run that happened has at least one gap.
gaps.n integer count Gaps observed.
gaps.p50, .p95, .p99 integer seconds Nearest-rank percentiles of the gap sample.
gaps.max integer seconds The longest single silence in the run.

A field’s absence from the envelope is distinct from it being genuinely zero or false — a stage entirely served from cache can have cost_usd: 0, and is_error: false is the common case, not a null. metering_fields preserves that distinction rather than treating a present-but-falsy value as missing.

Every envelope shape yields a record: one whose modelUsage entries cannot be read contributes nothing to tokens rather than failing the derivation, and an envelope that defeats it entirely still produces the all-null record above. Consumers therefore never see a stage-end event that lost its stage or exit_code (requirement 33) to a metering failure — which is what an empty derivation would cost, since the record is merged into that event as it is logged.

tokens sums the envelope’s own modelUsage map (one entry per model actually used, keyed by model id) rather than reading its top-level usage object, because usage excludes subagent activity while modelUsage — like cost_usd — includes it; the two fields would otherwise disagree about what “this stage” spent. A stage that used one model end to end has one entry to sum; a stage whose subagents ran a different model has several, and tokens reports their total, not a per-model breakdown — model above already names the invocation’s own model, and a full per-model breakdown was not needed by any reader this schema serves.

gaps is the odd field here, and in a way worth stating plainly: every other field is read out of the envelope the invocation wrote when it finished, and this one cannot be, because it is a fact about when the run was doing things and the envelope records only that it did them.

A gap is the interval between one growth of the stage’s own event stream (<stage>.stream.jsonl, requirement 4d) and the next. lib/stage-run.sh measures them by stat-ing that file inside the poll loop that already runs every two seconds while a stage is in flight, so:

  • the unit of observation is bytes arriving, not events parsed. The contract is “the runner streams progress to a file; liveness is monotonic growth of that file” — deliberately not “the events carry timestamps”, which is a fact about one CLI’s output format rather than about running a stage at all.
  • the stage cooperates in nothing and can fake nothing. No heartbeat is emitted, no cadence is agreed, and an actor that hangs cannot report otherwise.
  • the resolution is the poll interval, two seconds. Percentiles are therefore multiples of it, and n is a count of observed growths, not of events: several events arriving inside one interval are one observation. That is the correct unit for the purpose — what is being measured is how long the file stood still, and it did not stand still between them.
  • the first gap is the wait for the run’s first byte — model start-up, reliably one of the longer silences — and the last is the interval from the final growth to the end of the stage. That last one is included deliberately, and unconditionally: a stage that fell silent and was killed has its longest silence at the end, unterminated by any event, and a sample that dropped it would be missing precisely the population these numbers exist to describe. It is why a stage that emitted nothing at all still reports one gap, spanning the whole run, rather than none.

Percentiles are nearest-rank over the sorted sample (ceil(p·n)-th smallest), not interpolated, so every figure printed is a silence that really happened. null therefore means one thing only — this record carries no measurement — and never “the run was never quiet”.

cycles[].total_cost_usd (docs/spec/dashboard/README.md) is the sum of cost_usd across the cycle’s three rendered stages — Co-Ordinator, Implementer, Reviewer — treating a stage that never ran (cost_usd: null) as 0. It is the cost of the cycle’s own attempt at its item, which is what the card reporting it is about: spend the cycle incurred outside those three stages is not in it. Three things fall outside today — the Enabler, which runs from the exit trap over items other cycles left blocked (requirement 35a) and is rendered as its own verdict rather than as a fourth stage; the Refiner, which runs from that same exit trap over items no cycle has specified yet (requirement 39) and is no more one of a cycle’s rendered stages than the Enabler is; and the usage-limit probe of requirement 1b. All three are counted in the roll-ups below, which scan transcripts rather than stages, so none goes missing from a spend total; they are simply not attributed to one cycle’s attempt.

No other per-cycle field is currently aggregated from the per-stage token counts; a cycle’s token totals can be derived by the same sum over tokens.* if a future reader needs them, following the same null-as-zero rule.

counts.by_day / counts.by_model / counts.by_actor / counts.spend_total_usd / counts.spend_today_usd are computed by docs/spec/dashboard/README.md‘s Publisher directly from the raw transcripts across both pipelines’ history, not from the per-stage record above — a fleet-wide history spans more transcripts than any single node’s recent log.jsonl retains. Their fields:

Field Type Unit Meaning
spend_total_usd number US dollars Sum of cost_usd across every transcript scanned (COST_SCAN_DAYS window).
spend_today_usd number US dollars The same sum, restricted to today (UTC).
by_day[].usd, .n number, integer US dollars, count Cost and transcript count for one UTC day.
by_model[].usd, .n number, integer US dollars, count Cost and transcript count for one model id.
by_actor[].usd, .n number, integer US dollars, count Cost and transcript count for one actor. The actor is the transcript’s own filename stem, so the set is open, not enumerated: coordinator, implementer, reviewer, enabler, refiner, limit-probe and credential-probe (requirement 2.0h, agent-ops#2308) from a cycle directory, project-reviewer normalised from a review’s reviewer-<repo>.out, and any other stem verbatim — see the dashboard spec’s note on actor naming.
by_lane[].usd, .n number, integer US dollars, count Cost and transcript count for one lane — api, subscription or unknown (issue #2239, D30) — read the same way the per-stage record’s own lane is, off each transcript’s sibling <stage>.stream.jsonl, not off the .out envelope the rest of this roll-up scans. unknown covers every transcript this reads cannot assign a lane to: the stream was pruned, predates this field, belongs to a peer node (the stream never replicates — docs/spec/dashboard/state.md), carries no system/init event at all, or names an apiKeySource this mapping does not recognise (a provider whose own vocabulary is issue #2246’s business). No readable stream is ever lost to an unreadable one: each is read in its own pass, so a stage killed mid-write — whose stream’s final line is torn by construction — costs neither its own lane, which it recorded before the tear, nor any other transcript’s. One row per transcript, like by_day/by_actor above, never per (transcript × model) like by_model.
cost_rows[].repo, .item, .source, .outcome string | null — Which work item the row’s cost bought (issue #593, D21), joined by cycle against the fleet-wide event union (log.jsonl, the same union cycles[] renders from) rather than against cycles[] itself — the union is never rotated (docs/spec/implementation/requirements requirement 2.6) and is retained per analytics_retained_days (requirement 2.6d) rather than the MAX_CYCLES cap that keeps cycles[] to a recent detail window, so the join reaches back over the whole COST_SCAN_DAYS span the roll-ups themselves cover. Derived exactly as cycles[].repo/.item/.source/.outcome are: the last event in the cycle’s own events carrying .repo/.item, the most recent selection event’s .source, and the same outcome ladder (pr-ready > pr-raised > attempt-failed > none-selected > stand-down > cycle-skipped > selection > ended). All four are null together whenever .attributed (below) is false.
cost_rows[].attributed boolean — Whether the four fields above are populated. true only for a coordinator/implementer/reviewer row whose own cycle has events in the union. false for every other actor — enabler, refiner, limit-probe, credential-probe and project-reviewer — even when the row’s cycle matches a real, populated cycle: the Enabler/Refiner/limit-probe/credential-probe share their triggering cycle’s directory (and so its cycle id) but spend on a different item than the one that cycle selected, and a project-reviewer row’s cycle is a review id that never appears in log.jsonl at all (the review pipeline logs to its own review-log.jsonl). Also false for a coordinator/implementer/reviewer row whose own cycle has no events in the union — rare in practice, since log.jsonl is never rotated and its analytics content outlives transcript pruning by design; a state_dir reset predating the cycle, or a line lost to lib/fleet.sh’s NUL-corruption repair (fleet_repair_log), are the realistic causes, not rotation. A row is never dropped from cost_rows[] for lacking attribution; only these five fields go null.
cost_rows[].tokens_input, .tokens_output, .tokens_cache_creation, .tokens_cache_read integer | null tokens Issue #594, D21. That row’s own modelUsage entry’s token counts — the same fields, the same units, as the per-stage record’s tokens.* above — pulled from the same cost-scan pass that already reads costUSD from that entry, so no second scan. All four are null together on an unknown-model row (an envelope with no readable modelUsage): that row has no per-model breakdown to offer, and reading it as 0 would corrupt a prompt-cache ratio computed over it, exactly as tokens: null on the per-stage record above means “not measured,” never “measured as zero.”
cost_rows[].lane string — Issue #2239, D30. api, subscription or unknown — the same reading by_lane[] above sums, carried per row rather than only in the roll-up so a reader can re-aggregate it over whatever time frame the page’s own selector picks, exactly as model/actor already let it. unknown, never null: unlike the per-stage record’s own lane, which says “not observed” by being absent, this roll-up has no envelope-shaped degradation to preserve and so states plainly that the transcript’s lane could not be read, the same convention cost_rows[].model already uses for unknown.

The prompt-cache ratio a reader computes from these four fields — cache_read / (cache_read + cache_creation + input), the share of prompt-side tokens served from cache; output tokens are not in the denominator — is not itself a stored field: it is computed client-side, per stage and per model, over whatever cost_rows[] slice the page’s own time-frame selector picks, exactly as docs/spec/dashboard/README.md’s spend-by-model and spend-by-actor charts already re-aggregate that array.

The stall profile: the per-stage record’s own gaps (above), rolled up by stage. Unlike cost_rows[], this does not ride COST_SCAN_DAYS — its source is the gaps object on stage-end/review-stage-end events in log.jsonl/review-log.jsonl, not the transcripts the cost scan walks, and those two logs’ own retention (analytics_retained_days, requirement 2.6d — 0 by default, meaning indefinitely) is a materially different, and usually longer, span than the 60-day cost window. Presenting the two under one implied window would be wrong, so this object states its own:

Field Type Unit Meaning
window_from, window_to string | null ISO 8601 The earliest and latest ts among every event read to build this object — the same “state the window” convention counts.actor_scorecards already follows, not the cost scan’s COST_SCAN_DAYS cutoff.
by_stage[].stage string — stage-end’s own stage field verbatim (coordinator, implementer, reviewer, enabler, enabler-adjudicate, enabler-decide, refiner) for a stage-end row, or the literal project-reviewer for a review-stage-end row — review-stage-end carries no .stage field of its own, so it is keyed the same way the cost scan’s own reviews/ rows are, rather than left to collide with the implementation pipeline’s own reviewer stage: a different actor under the same word. This vocabulary is not cost_rows[].actor’s (a transcript’s filename stem) — a reader joining the two panels must not treat them as interchangeable.
by_stage[].runs integer count How many stage-end/review-stage-end records for this stage carried a non-null gaps. A record whose gaps is null means “not measured” (per-stage record table, above) and is excluded here rather than counted as a silent run.
by_stage[].median_of_run_p50 integer | null seconds Nearest-rank median (the same convention lib/stage-run.sh uses for its own percentiles) over the sample of each contributing run’s own gaps.p50. Rendered on the page as “across runs” — never as a pooled percentile: percentiles of percentiles are not percentiles, and the raw per-gap samples behind each run’s own figures are not retained (see “gaps”, above), so no pooled percentile can be computed from what this schema keeps.
by_stage[].worst_run_p95 integer | null seconds The largest gaps.p95 any single contributing run reported. Also “across runs,” not pooled — the same reasoning as median_of_run_p50.
by_stage[].worst_run_max integer | null seconds The longest single silence any contributing run saw — the maximum of each run’s own gaps.max. Unlike the two figures above, this is an exact percentile-free fact: a max of maxima is a max, not an approximation of one.

scripts/node-health.sh --metrics / the HTTP surface’s /metrics (scripts/node-health-server.py, docs/spec/implementation/requirements requirements 57-60, issue #608) — a different shape from everything above: where the per-stage record and the roll-ups are about spend, this is about node state, one node’s own liveness, readiness and health verdicts plus a handful of counters, read fresh on every call rather than aggregated over history. Documented here, under this document’s own stability policy below, because that policy — additive changes are free, a rename/removal/unit change ships in the same pull request as its code — is the contract this object needs exactly as much as the per-stage record does, not because it shares that record’s own fields.

Field Type Meaning
node string NODE_NAME, or a bare hostname fallback.
role string AGENT_OPS_ROLE (active|standby).
ts string This call’s own timestamp, ISO-8601 UTC.
version object lib/version.sh’s agent_ops_version — the same object heartbeat.json’s own version field carries.
live object scripts/node-health.sh --live’s own output verbatim: {live, age_s, reason}.
ready object scripts/node-health.sh --ready’s own output verbatim: {ready, unmet}.
health object scripts/node-health.sh --health’s own output verbatim: {status, components: {outbound, converged}}.
cycles.log_selections integer Count of selection events in this node’s own retained log.jsonl — this node’s log only, never the fleet union, so nothing here double-counts against a reader that also unions every peer.
cycles.log_attempts_failed integer Count of attempt-failed events, same source and scope as log_selections.
containers object | null host-facts/<node>.json’s own budget section (issue #606’s collector) where it exists, null otherwise — reported where produced, never fabricated by this endpoint.
mix object The credit mix’s effective lanes (issue #2244, D30), keyed by provider name — {api: {weight, enabled, present, state}, subscription: {...}, source?} per provider. enabled/present are true/false/null (enabled: null means D4’s own unset default applies; present: null means this node’s substrate ships no presence check at all); state is "open"/"closed". source, present only when fleet/mix.json names this provider, carries {ts, by} plus which side — "config" or "fleet" — supplied each of the two lanes’ weight/enabled/balance fields. The identical object agent-cycle.sh --status’s own mix: section renders from (lib/mix.sh’s mix_fleet_status_json, requirement 34a).

Additive-only in practice so far (no field has ever been renamed, removed, or changed unit or type) — governed by the same policy as every other object this document defines: see “Stability policy” below.

This is a contract other code depends on — the dashboard today, and (per docs/ROADMAP.md Decision D4) whatever usage-based billing eventually reads it. Two classes of change:

  • Additive, non-breaking: a new field on the per-stage record or a roll-up row; a new roll-up dimension; a new event carrying the record (e.g. a future stage). A reader that ignores fields it doesn’t recognise is unaffected.
  • Breaking, and must land in the same pull request as the code that makes it (AGENTS.md, “As-built specifications”): renaming or removing a field; changing a field’s type or unit (e.g. milliseconds to seconds, or a string model id to a numeric one); changing what tokens sums (top-level usage instead of modelUsage, or vice versa); changing an aggregation rule (sum vs. max, or null-as-zero vs. null-propagates).

cost_usd and tokens.* both ultimately depend on fields Anthropic’s own Claude Code CLI writes to the envelope (total_cost_usd, modelUsage), which this repo does not control. If that envelope’s shape changes upstream in a way that breaks the derivation above — a renamed field, a changed unit — that is a bug in this document or in lib/metering.sh, to be fixed the same way any other spec/code disagreement is.

A Grok Build stage’s cost_usd/tokens both understate what the run actually spent, by a known and bounded amount: every Grok session also sends the head of its own prompt, truncated, to a second xAI model (grok-4.6) to generate a session title (docs/DATA-HANDLING.md, “What a stage sends to its model provider”), and that call’s cost never appears in modelUsage — modelUsage names only the run’s own model, in every envelope the evaluation record captured. This is a known gap in the record, not a derivation bug: there is nothing in lib/metering.sh to fix, because the envelope itself never carries the figure.

A Grok Build stage run on the xAI subscription credential path (issue #2139, a device-code login rather than XAI_API_KEY) carries a second, larger gap today: xAI’s own streaming-messages-json format reports an unknown cost as the literal 0 rather than omitting the field, so total_cost_usd/modelUsage.*.costUSD read as a genuine zero rather than null — the opposite of D21’s own convention, under which an unknown figure must never read as a free run. The adapter does not yet correct this: doing so needs the init event’s own apiKeySource to tell the two credential paths apart, which lib/substrate-grok-build.sh does not read (issue #2246, blocked on #2139, adds it). Until #2246 lands, a subscription-lane Grok Build run’s cost_usd is an undercount that reads as exactly 0, not null, and should be read with that caveat rather than trusted at face value.

  • Produced: lib/metering.sh (metering_fields), called from every stage-end/review-stage-end site across both pipelines and the Monitor, each passing its own model id, .out path, the gap statistics lib/stage-run.sh left in stage_gaps_json, and (issue #2239, D30) the lane it left in stage_lane_json for the run that just ended (requirement 33a). The usage-limit probe of requirement 1b and the model-credential probe of requirement 2.0h — each a single minimal-model call that is deliberately not a stage and so logs no stage-start — gain their own stage-end, stage: "limit-probe" and stage: "credential-probe" respectively, each carrying this same record (lib/standdown.sh); lib/stage-health.sh ignores both, since its stage list does not name either. The one invocation that still logs neither is a <stage>-salvage resume.
  • metering_intended_lane produces stage-start/review-stage-start’s own lane (requirement 33) — the lane this node’s own credential implies, read before the run and so neither the lane run_model_stage’s draw went on to force (issue #2241) nor the one metering_fields’s own lane later observed the run actually use; all three are independent and, on a node holding both credentials, disagree by construction.
  • Consumed: scripts/publish-dashboard.sh reads the same upstream envelope fields directly for its own per-stage and roll-up rendering (docs/spec/dashboard/README.md) rather than reading the derived log.jsonl copy — the two are independent derivations of the same source and are expected to agree; a reader that finds them disagreeing has found a bug in one of them, not a second source of truth to reconcile.

test/metering.test.sh is the validation helper: it feeds metering_fields a well-formed single-model envelope, a multi-model envelope (the subagent case), and the missing-file, empty-object and malformed-JSON degradations, and asserts the exact shape documented above — including that a genuinely zero or false value survives rather than collapsing to null, and that gaps passes through when given, is null when omitted, and is null rather than fatal when the caller hands it something unparseable; the same three properties hold for lane (issue #2239). Because both pipelines call the same function, “both pipelines emit conforming records” reduces to one producer to check, rather than two.

test/stage-gaps.test.sh covers the measurement itself, which metering_fields only carries: the percentile arithmetic against a known sample, and — against a stub that emits with controlled pauses — that a real run’s gaps are measured from stream growth, that the silence after the last event is counted, and that a stage which emitted nothing reports null.

test/stage-run.test.sh covers lane’s own observation (issue #2239): a stub stream’s init event, with each of the four recognised apiKeySource values and with none at all, maps to stage_lane_json exactly as lib/substrate-claude-code.sh’s own substrate_claude_code_lane_of header documents. test/stage-health.test.sh asserts stage: "limit-probe" and stage: "credential-probe" are each ignored by stage_health_verdicts, never read as an idle implementation stage. test/standdown-limit-probe.test.sh lifts the probe’s own stage-end block out of lib/standdown.sh and asserts it carries stage: "limit-probe", the real exit code, and this same metering record — lane, cost_usd and tokens included. test/standdown-credential-preflight.test.sh asserts the same for the model-credential probe’s own stage-end, stage: "credential-probe", on both its refused and healthy paths.

test/node-health-cli.test.sh covers the node metrics object above: it asserts scripts/node-health.sh --metrics’s output carries every top-level field this section documents, against a fixture state_dir.