Implementation plan · v2 · independently reviewed

Local-first usage for T3 Code

Build a top-level Usage page backed by an append-only local ledger. Capture exact usage from live provider events, backfill native logs once, and merge aggregate reports from every connected T3 environment—without uploading raw logs, prompts, or paths.

Recommended Reviewed by gpt-5.6-sol T3-only by default All-local opt-in No cloud persistence

What the gpt-5.6-sol code review changed.

The v1 plan was reviewed by gpt-5.6-sol with read-only access to the repository; every cited file was re-verified before acceptance. Verdict: product direction and ledger-query shape sound; the persistence design needed restructuring before Phase 1. Four corrections are binding on the rest of this document.

Blocker fixed · durable events, not an ingestion fold

The ledger must be a real projector

In this codebase, projections are registered projectors replaying orchestration_events from a projection_state cursor, with writes transactionally coupled to event appends (ProjectionPipeline.ts:1462–1548, OrchestrationEngine.ts:169–180). v1's in-memory per-turn fold writing rows on turn.completed would be restart-lossy and unreplayable. v2: persist durable model.usage-recorded orchestration events (keeping providerRefs, typed modelUsage, exact cost), then derive the ledger with a standard registered projector. A new projector's empty cursor replays history automatically — this also simplifies backfill.

Misdiagnosis corrected · the adapter was innocent

Cost dies in ingestion, not in ClaudeAdapter

v1 claimed ClaudeAdapter fails to plumb total_cost_usd / modelUsage. Verified false: both completion paths already emit them on turn.completed (ClaudeAdapter.ts:1963–1980, :2036–2050). The loss is downstream — ProviderRuntimeIngestion consumes turn.completed for lifecycle only and discards its usage payload, and buildContextWindowActivityPayload (:596–613) strips providerRefs from persisted usage activities. Phase work moves accordingly. Also confirmed: ThreadTokenUsageSnapshot has no cache-creation field, so "emit the full split" requires a contract extension, and modelUsage needs a typed schema (currently UnknownRecord).

Identity fixed · NULLs defeat uniqueness

Fact IDs, not composite keys

v1's dedup key (environment, thread, turn, model) fails twice: SQLite UNIQUE ignores NULL components (interrupted turns have no turn_id), and it omits the provider-native session id that validation proved essential (concurrent Codex sessions on one T3 thread inflated sqlite replay 12×). v2: a stable fact_id hashed from provider + native session + native turn/message id + model + kind, with explicit upsert precedence (live > transcripts > events) and a stale flag for lifecycle-rejected completions. Per-model cost and turn-level totalCostUsd are stored as separate fact kinds so totals reconcile instead of double-counting.

Semantics added · lifecycle, revert, terminal paths

Usage survives what conversations don't

Existing projectors prune on thread.reverted (ProjectionPipeline.ts:851–980); the usage projector deliberately does not — consumed tokens are immutable billing history. Thread deletion keeps facts and redacts linkage. Finalization listens to turn.aborted (Codex emits it: CodexAdapter.ts:788–797), session exit, and steering-superseded turns — not just turn.completed. Backfill leaves schema migrations (which run during SQLite init) and becomes a versioned, resumable server-side job; transcript parsing is opt-in and never runs at startup. Pricing moves to versioned, effective-dated data in shared runtime code, never packages/contracts.

Confirmed feasible by the review
  • Multi-environment fan-out works with the existing client registry (EnvironmentRegistry.run is environment-scoped) — but it must lease the environment catalog, not just currently-live connections, with bounded concurrency and per-environment timeouts.
  • One dashboard-shaped usage.query RPC (named bucket sets per dimension) avoids four round-trips per page load; it needs a RPC_REQUIRED_SCOPE read-scope entry like every other method.
  • Grouping timezone comes from the requesting client (IANA), attribution at observation time; DST handled by local-calendar bucketing.
  • Sizing revised: the "scrappy 2–3 day" v1 cut is retired — it would have shipped an unreplayable table. Accounting correctness first; UI was mostly done in mock form anyway.

Index once; query the ledger.

The dashboard should never scan gigabytes of JSONL or rotated provider logs on page load. Each T3 environment owns a compact usage ledger in its existing SQLite state. The client asks every connected environment for aggregate rows and merges those rows locally.

Default scope

T3 Code only

Reliably attributable to T3 provider sessions, threads, projects, subagents, and environments.

Optional scope

All local agent activity

Opt-in indexing for Codex, Claude, OpenCode, and future sources launched outside T3.

Placement

Top-level /usage

A destination beside Settings, not a settings panel and not a thread-level activity view.

Do
  • Persist normalized, idempotent usage records.
  • Keep exact provider cost separate from API-equivalent estimates.
  • Return aggregate, coverage, pricing, and freshness metadata.
  • Show partial cross-environment results when a host is offline.
Do not
  • Require a separately installed ccusage binary.
  • Store usage rows in thread activities or conversation snapshots.
  • Call cache tokens “input” without separating their semantics.
  • Publish durable usage aggregates to the cloud relay.

The raw signal is already rich.

T3 currently persists turn timing and context snapshots. Native source logs provide model-level token accounting, cache use, reasoning output, and—on Claude—reported USD cost. The missing layer is durable normalization.

T3 SQLite 673

turns across 113 threads

Context snapshots 19.5k

durable updates across 103 threads

T3 provider logs 2.06 GB

247 current and rotated files

Codex history ~390

JSONL sessions · 396 MB

Claude history 297

JSONL sessions · 213 MB

Direct attribution 109/109

T3 provider sessions matched native logs

Source What it already knows Current limitation Plan role
T3 projections Turns, timestamps, model selection, project/thread ownership Usage is a generic context activity; completion usage is not projected Exact interaction timing and relational joins
T3 provider logs Native and canonical events with thread IDs Rotated at 10 × 10 MB per thread; unsuitable as the sole history Recent fallback and debugging
Codex JSONL Model, cumulative and last-call tokens, cache, reasoning, T3 originator Cumulative counters require careful delta conversion Exact live semantics and historical backfill
Claude JSONL Per-assistant usage, model, cache creation/read, UUID, cost SDK entrypoint alone is not unique to T3 Backfill matched by durable provider session ID
ccusage Timezone reports, cache split, model breakdown, offline pricing External native binary and output/version coupling Oracle, conventions, and compatibility reference
Performance finding. An all-history ccusage scan completed quickly on this host, but peaked near 196 MB RSS and used substantial parallel CPU. A representative SQLite usage aggregation completed in roughly 40 ms. The ledger turns an expensive parse into a cheap read.

Define the numbers before drawing charts.

Token fields differ across providers. The normalized contract must make inclusion and subset relationships explicit so totals remain comparable.

Uncached input Input tokens that were not served from a provider cache.
Cache read Reused input tokens. Kept separate because these can dominate totals.
Cache write Tokens written into a prompt cache, including Claude cache creation.
Output All generated output. Reasoning output is included here.
Reasoning output A visible subset of output, never added to the total twice.
Total tokens Uncached input + cache read + cache write + output.
Model calls Positive native usage records—not turns and not tool calls.
T3 turns User-initiated turns. A turn can produce many model calls and subagents.
Time of day Turn-start distribution for T3 scope; call distribution for all-local scope.
Do not report “hours spent” from provider logs. Logs reveal activity points, not foreground app duration. A future client-presence signal could add actual active time, but it must be named and stored separately.

One normalized path for live and historical usage.

Live adapters emit provider-neutral usage events. Backfill adapters produce identical record identities, so the SQLite uniqueness boundary de-duplicates live and imported data automatically.

Provider events and native logs feed a local usage ledger queried by connected clients. INGESTION Live provider events Codex · Claude · OpenCode · ACP exact, low latency Native log backfill incremental JSONL / provider stores streaming, cursor-based NORMALIZATION model.usage-recorded stable native key · model · token split thread / turn · cost · tier · accuracy LOCAL SQLITE usage_records append-only ledger · uniqueness on native key usage_source_state file offsets · parser version · freshness · dataset ID READ-ONLY RPC usage.query bounded aggregates · coverage · pricing · freshness CLIENT RUNTIME Connected environments parallel query · dataset dedupe · partial success /usage local merged dashboard
Canonical event

model.usage-recorded

A single provider-neutral usage contract. Context-window events remain dedicated to UI occupancy and compaction behavior.

ProviderUsageRecord {
  nativeRecordKey, provider, providerInstanceId,
  threadId?, turnId?, projectId?, providerSessionId?,
  model, occurredAt, requestCount,
  uncachedInputTokens, cacheReadInputTokens,
  cacheWriteInputTokens, outputTokens,
  reasoningOutputTokens,
  providerCostMicros?, serviceTier?,
  origin: "t3" | "external",
  accuracy: "exact" | "derived" | "estimated"
}
Idempotency boundary

Stable native identity

  • Claude: session ID + assistant message UUID
  • Codex: session ID + monotonic cumulative usage state
  • OpenCode: provider session/message ID
  • ACP: session + turn + response ordinal
  • Canonical fallback: T3 provider event ID
Live ingestion and later backfill insert the same key. A unique index prevents double counting without source-specific cleanup passes.

Capture at the closest trustworthy source.

Avoid parsing provider-specific Unknown payloads downstream. Each adapter should normalize usage while it still understands the native event schema.

Provider Live source Backfill source Required change Expected quality
Codex thread/tokenUsage/updated ~/.codex/sessions/**/*.jsonl Preserve full total/last components, cache write, actual model, and reroutes Exact
Claude Native assistant SDK message + result reconciliation Claude project JSONL matched by session ID Emit one record per assistant response UUID; preserve reported cost Exact
OpenCode Assistant message.updated OpenCode local data store Extract message model, tokens, cost, and message ID currently ignored Exact when present
Cursor / Grok ACP PromptResponse.usage and usage_update Recent native/canonical logs Stop discarding the usage object; preserve cumulative cost carefully Capability-dependent
Unknown drivers Turn model selection only None until an adapter exists Return turns with explicit token coverage gap Unavailable, not zero
T3-only backfill
  1. Resolve configured Codex and Claude home paths per provider instance.
  2. Seed ownership from provider_session_runtime.
  3. Follow Codex parent_thread_id chains for subagents.
  4. Keep Claude sidechains inside the matched direct session.
  5. Use T3 originator metadata as validation, not global ownership.
Import mechanics
  • Stream files; never read entire histories into memory.
  • Persist file identity, byte offset, mtime, and parser version.
  • Tolerate partial final lines, append, truncation, and rotation.
  • Whitelist usage fields; never persist prompt or tool payloads.
  • Run at low priority with visible progress and a manual reindex action.

Aggregate environments, not SSH machines.

T3 already knows its connected execution environments and can run an RPC in any one of them. That catalog is the product-native aggregation boundary and works for local, SSH, bearer, and relay-backed connections.

usage.query

Request

UTC range, IANA timezone, bucket granularity, scope, environment filters, and optional project grouping.

Response

Totals, daily buckets, model rows, hour/weekday distributions, environment/source breakdown, coverage, indexed-through time, errors, and pricing basis.

Failure model

Partial success by default

If one environment is offline, show available totals and “3 of 4 environments reporting.” Older environments without usageReporting show “Update required” instead of failing the page.

connected stale unsupported relay transport
Cross-environment dedupe

Dataset fingerprints

Multiple T3 servers on one physical host can see the same provider directory. Hash a stable host identity plus canonical source root; return per-source rollups and select the freshest duplicate dataset before summing.

Authorization

Read-only and already scoped

Use the existing orchestration:read scope: it already grants access to more sensitive thread snapshots. Manual reindex can require orchestration:operate.

Cost is not billing. Display “API-equivalent estimate,” use provider-reported cost where available, bundle a pinned offline pricing snapshot, preserve service tier, and label unknown custom models “Unpriced” rather than $0.00. Support import of ccusage-compatible pricing overrides.

Make coverage as visible as consumption.

The page should feel like ccusage translated into an interactive, multi-environment T3 surface. Every total needs an inspectable source and quality story.

Chosen mock (v6) The approved design, built from this machine's full ledger (3.45B tokens, Jun 26 – Jul 22). Interactive version with hover tooltips: postplan.dev/d/5bx21h42g0b9. Design system: hue = harness (Claude terracotta, Codex white), lightness = model within the family; violet is reserved for T3-side stats (heatmap, projects); estimated dollars are always striped, exact ones never.
Tokensall processed, by harness
3.45B27 days
Claude256 turns · $3,04357% · 1.95B
fable-51.69B
opus-4.8221M
sonnet-5 · haiku · sonnet-4-640M
Codex127 turns · plan-covered43% · 1.50B
CostClaude metered exactly · Codex estimated at list price
$5,407$3,043 exact + $2,364 est.
Claudeexact · SDK-metered56% · $3,043
fable-5$2,810
opus-4.8$213
Codex est.list price · $0 billed (Pro)44% · $2,364
Output tokens15.4Mactually generated text
Claude spend$3,043exact, from SDK results
Codex value~$2,364list-price est. · $0 billed
Turns383across 115 threads
Cache hit rate96.2%of all input tokens
Below the fold (see the interactive mock): tokens-per-day stacked by model, Claude spend-per-day, hour×weekday turn heatmap in the violet T3 lane, per-provider hourly token charts, the full models table (the accessible view of every chart), projects, reasoning-effort breakdown, and marathon-turn records.
Harness first, models as shadesThe top-level split is Claude vs Codex; models are lightness steps within the harness hue, so the donut reads at two zoom levels.
Exact and estimated never blendMetered cost is solid; list-price estimates are striped and labeled est. — in charts, tiles, and tooltips alike.
Official marks carry identityProvider logos (already in Icons.tsx) appear in legends, tiles, and table rows; brand color is for logos, validated steps for data.
The table is the fallbackThe models table is the accessible view of every chart; violet marks T3-side stats so provider hues stay unambiguous.

Ship in six reviewable slices.

Establish accounting correctness before UI polish. Each slice leaves a usable, testable boundary and avoids bundling provider parsing, fleet aggregation, and charting into one risky change.

Semantics, durable events, and projector
Add packages/contracts/src/usage.ts (typed facts: cumulative vs interval, cache read vs write, native identity, reset generation; typed modelUsage), emit durable model.usage-recorded orchestration events from ingestion, and register a usage projector with its own projection_state cursor. Schema migration creates tables only. Tests: live-vs-replay equivalence, restart, duplicates, abort, steering, revert retention, deletion redaction.
Codex and Claude live capture
Preserve providerRefs, per-model usage, and exact cost through ingestion (ClaudeAdapter already emits them on turn.completed); finalize on turn.aborted, session exit, and steering-superseded paths, not completion alone. Extend the snapshot contract with cache-creation tokens.
Backfill and pricing
Versioned, resumable server-side backfill job (never inside migrations, no second DB writer): event replay via the projector's empty cursor, then provider-log parse, then opt-in transcript enrichment — same fact IDs, explicit upsert precedence. Versioned, effective-dated pricing catalog in shared runtime code; estimates computed at query time, never stored as truth.
RPC and aggregation
Add usage.query, environment capability negotiation, client-runtime query atoms, partial errors, timezone grouping, and dataset de-duplication.
Web and desktop Usage page
Add the route, sidebar affordance, summary cards, accessible SVG/CSS charts, model and environment tables, coverage states, filters, and empty/error states.
Coverage and mobile
Add OpenCode and ACP capture, all-local opt-in, cached offline aggregates, responsive mobile UI, and the mobile integrated verification pass.

Test accounting invariants, not screenshots alone.

Backend changes require focused tests for every changed behavior. Frontend integration follows the repository’s isolated T3 app verification workflow.

Normalizer and importer
  • Cumulative-to-delta conversion
  • Counter reset and compaction
  • Cache semantic normalization
  • Reasoning as output subset
  • Model changes and reroutes
  • Duplicate live/backfill keys
  • Partial final JSONL line
  • Append, truncate, and rotate
  • Custom provider home paths
  • T3 descendant attribution
Query and client
  • DST spring and fall boundaries
  • Arbitrary IANA timezones
  • Range limits and read scope
  • Offline partial results
  • Server version skew
  • Dataset fingerprint dedupe
  • Unknown and mixed pricing
  • Accessible chart labels
  • Empty and stale states
  • Thread deletion retention
Integrated pass

Launch one isolated environment with the test-t3-app skill, authenticate via its printed pairing URL, seed deterministic ledger rows, and verify the date, scope, model, environment, timezone, partial-data, and unpriced-model flows in the controlled browser. Stop every server and watcher afterward. Run test-t3-mobile only when mobile UI ships.

30-day query target < 200 ms / environment streaming import memory bounded no full workspace suite locally

Be honest where inference stops.

The largest risk is not missing data; it is silently presenting duplicate, cumulative, unpriced, or differently defined data as a single exact total.

Cumulative counters double-count. Use monotonic totals, stable native keys, and explicit reset rules.
Live and backfill overlap. Enforce native record uniqueness independent of ingestion source.
Two environments share one provider home. Return per-source rollups and dedupe hashed dataset fingerprints.
Provider formats drift. Version parsers, use golden fixtures, surface importer errors, retain cursors.
Custom models have no public price. Show “Unpriced,” report coverage, and support compatible overrides.
Historical thread deletion changes joins. Persist stable project/thread IDs in usage rows; clear usage separately.
Raw logs contain private content. Whitelist fields during streaming parse; store no prompts, tools, or cwd.
Estimated cost looks like a bill. Label API-equivalent cost, basis, pricing version, tier, and unknowns.

Likely implementation touch points.

Keep contracts schema-only, place runtime parsing in shared/server modules, and reuse the environment-aware client-runtime query machinery.

Area Files / package Responsibility
Contracts packages/contracts/src/usage.ts, rpc.ts, environment.ts Usage schemas, RPC input/output, capability flag
Server usage domain apps/server/src/usage/{Services,Layers} Ledger, importers, pricing, aggregation, source status
Persistence apps/server/src/persistence/Migrations/033_UsageLedger.ts Usage rows, source cursors, indexes, repository tests
Provider adapters CodexAdapter.ts, ClaudeAdapter.ts, OpenCodeAdapter.ts, ACP adapters Native usage extraction and stable record identities
Transport apps/server/src/ws.ts, packages/contracts/src/rpc.ts Read query, manual reindex, authorization, instrumentation
Client runtime packages/client-runtime/src/state/usage.ts Per-environment queries, partial success, dedupe, merged report
Web apps/web/src/routes/usage.tsx, components, sidebar Filters, charts, tables, freshness, coverage, route navigation