cctrack 0.10.0__tar.gz → 0.11.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -31,13 +31,14 @@ uv build
31
31
 
32
32
  This is a single-module CLI tool. All logic lives in `src/cctrack/__init__.py`:
33
33
 
34
- 1. **Rate card** (`RATES`, `_an`/`_oa` row builders, `_family_matches`, `get_rates`, `calculate_cost`, `is_known_model`) - Anthropic and OpenAI prices. **Every model version needs its own row**: `_family_matches` lets a row absorb only the exact id, dated snapshots (`-20250514`, `-2025-08-07`) and non-version suffixes (`-codex`) — never a short-number minor version (`claude-opus-5` does NOT match `claude-opus-5-5`) or a size-tier word (`mini`, `nano`, `pro`, `max`, `luna`, `terra`, `sol`, `astra`). This is deliberate: prefix inheritance silently mispriced opus-4-8 (3×) and opus-5-5 (84%) before. Unknown models are flagged `?` and fall back to Sonnet (Claude) or GPT-5 (OpenAI) rates. `get_rates` takes the usage date (time-limited `intro` pricing) and the request's prompt size (`long_context` tiers: Haiku 5.5 >100K, several OpenAI models >272K). Re-verify against the official pricing pages when adding rows; don't infer a price from a neighbouring model.
34
+ 1. **Rate card** (`RATES`, `_an`/`_oa` row builders, `_family_matches`, `get_rates`, `calculate_cost`, `is_known_model`) - Anthropic and OpenAI prices. **Every model version needs its own row**: `_family_matches` lets a row absorb only the exact id, dated snapshots (`-20250514`, `-2025-08-07`) and non-version suffixes (`-codex`) — never a short-number minor version (`claude-opus-5` does NOT match `claude-opus-5-5`) or a size-tier word (`mini`, `nano`, `pro`, `max`, `luna`, `terra`, `sol`, `astra`). This is deliberate: prefix inheritance silently mispriced opus-4-8 (3×) and opus-5-5 (84%) before. Unknown models are flagged `?` and fall back to Sonnet (Claude) or GPT-5 (OpenAI) rates. `get_rates` takes the usage date (time-limited `intro` pricing) and the request's prompt size (`long_context` tiers: historical Sonnet 4/4.5 >200K, Haiku 5.5 >100K, several OpenAI models >272K). Re-verify against the official pricing pages when adding rows; don't infer a price from a neighbouring model.
35
35
  1a. **Energy model** (`ENERGY_WH_PER_MTOK`, `estimate_energy_wh`) - Opt-in (`--energy`) order-of-magnitude estimate keyed off each rate entry's `tier`. Deliberately NOT a function of price: both cache-write TTLs use one figure because a 1h write costs more money but the same compute.
36
- 2. **File discovery** (`sandy_home`, `_sandy_print_state`, `sandbox_roots`, `default_dirs`, `discover_files`) - Claude transcripts from `~/.claude/projects/` plus each Sandy sandbox's `claude/projects/` (ONLY `projects/` — `claude/` also holds `history.jsonl`, job timelines, tool-audit logs). Sandbox roots come from `sandy --print-state` → `sandboxes[].path` (follows `$SANDY_HOME`), else `$SANDY_HOME/sandboxes/*` (default `~/.sandy`). Per sandy's host-side path contract each root has agent homes `claude/` (→ `~/.claude` in the sandbox) and `codex/` (→ `~/.codex`); everything else under a root is private. **Dot-entries** (`_is_sandbox_name`): skip `.rsync-from.*` (an in-progress `sandy --rsync-from` copy — its hook data was being summed twice) and `*.lock`; any other dot-dir is a REAL sandbox iff it holds `WORKSPACE.json` (a workspace like `~/.dotfiles` → sandbox `.dotfiles-<sha8>`). Sandy's own enumeration, hence `--print-state`, currently omits dot-named sandboxes, so they're always added by scanning `sandboxes/` directly. Tests are isolated from real sandboxes by `tests/conftest.py`.
37
- 2a. **Codex** (`codex_homes`, `discover_codex_files`, `parse_codex_lines`, `parse_codex_events`, `fetch_remote_codex`) - Reads `$CODEX_HOME` (default `~/.codex`) and every sandbox's `codex/` (sandy never sets CODEX_HOME), `sessions/` + `archived_sessions/` rollouts, incl. `.jsonl.zst` (stdlib `compression.zstd` on 3.14+, else the `zstd` CLI, else skipped and counted). Lines are `{timestamp, type, payload}`. Prefer `token_usage_record` items (per-response, dedup by `response_id` — forks replay parent history); fall back to legacy `event_msg`/`token_count` only before a file's first record, counting `last_token_usage` only when `total_token_usage.total_tokens` moved (it's re-emitted unchanged). **`input_tokens` includes `cached_input_tokens` and `cache_write_input_tokens`; `output_tokens` includes reasoning** — uncached input = input − cached − cache_write. Model/cwd from the latest `turn_context`; thread id + git branch from `session_meta`. Codex events carry `agent="codex"`.
38
- 3. **Remote aggregation** (`remote_sandbox_roots`, `fetch_remote_jsonl`, `parse_remote_events`, `fetch_remote_hook_data`, `parse_remote_hook_data`, `fetch_remote_codex`) - One SSH call per host finds its sandbox roots (same rules as locally, cached), then each fetch cats the host's own dirs plus the matching per-sandbox dirs with file separators and parses locally.
36
+ 2. **File discovery** (`sandy_home`, `_sandy_print_state`, `sandbox_roots`, `default_dirs`, `discover_files`) - Claude transcripts from `~/.claude/projects/` plus each Sandy sandbox's `claude/projects/` (ONLY `projects/` — `claude/` also holds `history.jsonl`, job timelines, tool-audit logs). Sandbox roots come from scanning `$SANDY_HOME/sandboxes/*` (default `~/.sandy`), locally and remotely. `sandy --print-state` (`sandboxes[].path`) is asked ONLY when that dir is missing — it takes many seconds and was called 3× per run, which made cctrack look hung. It is cached per run, gets stdin=/dev/null, and has a `CCTRACK_SANDY_TIMEOUT` (default 15s) with a fallback note. Per sandy's host-side path contract each root has agent homes `claude/` (→ `~/.claude` in the sandbox) and `codex/` (→ `~/.codex`); everything else under a root is private. **Dot-entries** (`_is_sandbox_name`): skip `.rsync-from.*` (an in-progress `sandy --rsync-from` copy — its hook data was being summed twice) and `*.lock`; any other dot-dir is a REAL sandbox iff it holds `WORKSPACE.json` (a workspace like `~/.dotfiles` → sandbox `.dotfiles-<sha8>`). Sandy's own enumeration, hence `--print-state`, currently omits dot-named sandboxes; the directory scan finds them. Tests are isolated from real sandboxes by `tests/conftest.py`.
37
+ 2a. **Codex** (`codex_homes`, `discover_codex_files`, `parse_codex_lines`, `parse_codex_events`, `fetch_remote_codex`) - Reads `$CODEX_HOME` (default `~/.codex`) and every sandbox's `codex/` (sandy never sets CODEX_HOME), `sessions/` + `archived_sessions/` rollouts, incl. `.jsonl.zst` (stdlib `compression.zstd` on 3.14+, else the `zstd` CLI, else skipped and counted). Lines are `{timestamp, type, payload}`. Reconcile `token_usage_record` items with their matching `event_msg`/`token_count` snapshots; never discard the rest of a file after its first record. Keep standalone compaction usage, last-only and cumulative-only snapshots; dedup unchanged cumulative re-emissions. Prefer the record's explicit model and recorded service tier. Forked legacy usage is matched against the parent's sequence, preserving history through repeated merges and nested forks; missing parents retain uncertain usage flagged UNKNOWN. **`input_tokens` includes `cached_input_tokens` and `cache_write_input_tokens`; `output_tokens` includes reasoning** — uncached input = input − cached − cache_write. Model/cwd from the latest `turn_context`; thread id + git branch from `session_meta`. Codex events carry `agent="codex"`.
38
+ 3. **Remote aggregation** (`fetch_remote_bundle`, `_remote_program`, `_remote_collect`, `_parse_remote_files`, `parse_hook_blob`, `remote_sandbox_roots`, `fetch_remote_jsonl`, `parse_remote_events`, `fetch_remote_hook_data`, `parse_remote_hook_data`, `fetch_remote_codex`) - **Default: parse on the host.** `fetch_remote_bundle` sends this module's own source (zlib+base64) to `ssh host python3 -`; `_remote_collect` runs there (read-only: no hook rollup) with the host's own discovery and EXACTLY the per-file code the raw stream uses (`_parse_remote_files`, `parse_hook_blob`), and returns events + parse stats + hook rows as zlib-compressed tagged JSON (`_tag_json`/`_untag_json` round-trip tuples, sets, datetimes, non-str keys — never pickle). Remote `Progress` emits `CCTRACK_PROGRESS` stderr lines that `_run_streaming` relays into the local status line. Results are cached per host; the parse_remote_* functions read the bundle. `{"failed"}` (ssh error 255, timeout) means no retry; `{"fallback"}` (no python3 / <3.10 / unreadable reply, or `CCTRACK_REMOTE_PARSE=0`) streams raw: one SSH call finds sandbox roots (same rules as locally, cached), then each fetch cats the host's dirs with file separators, gzip-compressed in transit (`_gzip_wrapped`/`_decode_stream`), and parses locally. `tests/test_remote_parse.py` runs both paths against one fake host via a fake `ssh` and requires identical events, stats and hook rows; `tests/conftest.py` stubs `fetch_remote_bundle` unless marked `real_remote_bundle`. All ssh runs through `_run_ssh`: `ssh -T`, stdin=/dev/null, local termios saved/restored (a timed-out ssh once left the terminal raw → staircased report). Fetch timeout `CCTRACK_SSH_TIMEOUT` (default 600s); a timeout warns that the host's data is MISSING. `Progress` draws a cylon bar + bytes/files on stderr only when it's a TTY (`CCTRACK_NO_PROGRESS` disables).
39
39
  3a. **Hook parsing** (`parse_hook_rows`, `compute_hook_deltas`) - The hook gives **cost only**. Its `input_tokens`/`output_tokens`/`cache_*` fields are context-window SNAPSHOTS (`input_tokens` ≈ `cache_read + cache_write`; `output_tokens` is just the last message's), not cumulative — never use them for token counts. `cost_usd` is a session-lifetime cumulative that is unreliable in two ways handled by `compute_hook_deltas`: (1) it can already be large the first time a session is observed (a long-running/unattended session that only rendered its statusline partway through), so the **first observation is a baseline that is NOT counted** — booking a session's pre-existing cumulative onto its first-seen day is what produced a bogus $3,370 day; (2) it **drops** on resume/compaction (or when parallel processes share one session id), so a drop **rebaselines without counting the new level** — otherwise a day's booked spend can exceed the counter's own peak, which is impossible for real money. Net rule: **book only observed upward increments**; a rolled-up baseline seeds `prev` so already-counted days aren't recounted.
40
- 4. **JSONL parsing** (`parse_lines`, `parse_events`, `dedup_events`) - Extracts `assistant` events with token usage. Deduplicates by `requestId` across all of a host's files (last event wins) — resumed sessions (`--resume`/`--continue`) repeat events with the same `requestId` in new files. Events without `requestId` are never deduped.
40
+ 3b. **Hook install** (`install_hook`, `uninstall_hook`, `_apply_hook_install`, `_apply_hook_uninstall`, `remote_*_hook`, `HOOK_SCRIPT`) - The hook is Claude Code's `statusLine` command. Install **wraps** any existing status line: it's saved as `wrapped_status_line` in `~/.claude/cctrack/config.json` (other statusLine keys like `padding` are kept), and `HOOK_SCRIPT` records the cost and then runs it via the shell with the same stdin, passing stdout and exit code through. Re-install keeps the saved command and `installed_at` (the start of hook coverage). Uninstall restores the wrapped line only if `statusLine` still points at cctrack. `_apply_hook_*` are self-contained (imports inside) because `remote_*_hook` ship their source with `inspect.getsource` to `ssh host python3 -`. Local and remote share one implementation, and tests run that shipped program for real.
41
+ 4. **JSONL parsing** (`parse_lines`, `parse_events`, `dedup_events`) - Extracts `assistant` events with token usage. Deduplicates by message + request identity, falling back to Anthropic message id scoped to the session when request id is absent, and then request id when older logs omit message id. Gateway message ids without request ids also include timestamps. Keep the fullest snapshot, prefer parent messages over sidechain replays, and count advisor iterations separately. `reconcile_sources` performs the final cross-host merge and rebuilds source costs so all report modes agree. Preserve copy locations in JSON/CSV.
41
42
  5. **Aggregation** (`aggregate`) - Buckets events into daily and monthly summaries with token counts and costs.
42
43
  6. **Output** (`print_report`) - Prints current month-to-date summary with projections, daily breakdown, and previous month summaries. Cost is composed **per source** (one source per machine): hook cost where a source has statusline coverage, accuracy-factor-adjusted JSONL cost otherwise, summed per date. The accuracy factor is measured per source over dates strictly after that source's hook install day; when unmeasurable, `DEFAULT_ACCURACY_FACTOR` is **1.0** — the old 1.25 "logs undercount ~20-25%" was entirely rate-card error and inflated unmeasured days 25%.
43
44
  6a. **Explore** (`print_explore`, `--explore DATE`) - Drills into one day: dollar decomposition by token class, then by model / project / session / machine. Each JSONL event carries its `project` (from `cwd`), `session_id`, `source` (host) and `git_branch` for attribution. Per-session JSONL estimate is shown against the hook's authoritative per-session cost; a >15% day-total divergence is flagged so an inflated estimate (incomplete logs, unknown model) is distinguishable from real spend.
@@ -48,7 +49,7 @@ Entry point: `cctrack:main` (registered in `pyproject.toml` as a console script)
48
49
  ## Key Design Decisions
49
50
 
50
51
  - Zero external dependencies - stdlib only (json, argparse, subprocess, etc.)
51
- - Deduplication is global per host by `requestId` (last wins) - resumed sessions replay history into new files and must not double count. Cross-host `requestId` collisions can't occur (distinct API calls).
52
+ - Deduplication is global across files, Sandy sandboxes and hosts by API identity, with fullest-snapshot selection. Rsync copies can share request/response ids across hosts. Preserve all copy locations and rebuild per-source totals after dedup. Raw hook histories are also merged before differencing; legacy monthly rollups lack the identities needed to dedup copied summaries reliably.
52
53
  - Hook data is authoritative for **cost only**; every token count comes from the JSONL logs. Never mix the two in one figure - the hook's token fields are snapshots and would double count against JSONL cache columns.
53
54
  - Never let one machine's hook coverage suppress another machine's JSONL cost - compose per source.
54
55
  - Each coding agent is its own source. Codex sources are `exact`: priced straight from their logs, never replaced by the Claude hook and never scaled by the (Claude-derived) accuracy factor. In `--explore`, hook comparisons use only the Claude slice of the JSONL total.
@@ -57,3 +58,9 @@ Entry point: `cctrack:main` (registered in `pyproject.toml` as a console script)
57
58
  - `session-baselines.json` carries each session's rolled-up cumulative across the 90-day retention boundary so straddling sessions aren't re-counted from zero.
58
59
  - Build system is Hatch (`hatchling`)
59
60
  - Requires Python 3.10+
61
+
62
+ ## Accounting compatibility
63
+
64
+ - `tests/test_accounting.py` and `tests/fixtures/ccusage-parity.json` pin synthetic reference cases to ccusage 20.0.34. `scripts/compare_ccusage.py` optionally checks an installed binary in isolated temporary homes; no Node/network requirement for ordinary tests or runtime.
65
+ - Provider rules take precedence over matching ccusage. Historical Sonnet 4/4.5 context premiums apply to the whole request, including cache input in the threshold; ccusage's marginal calculation is an intentional documented difference.
66
+ - Service tiers come from log metadata, never retrospectively from the user's current config. Explicit model aliases must not absorb arbitrary suffix variants. JSON rate metadata includes service-tier multipliers; session rows include tier counts and copy locations. Redaction must cover all added paths/cwds.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cctrack
3
- Version: 0.10.0
3
+ Version: 0.11.1
4
4
  Summary: Claude Code cost tracker — scans JSONL logs and reports token usage + estimated cost
5
5
  Project-URL: Homepage, https://github.com/rappdw/cctrack
6
6
  Project-URL: Repository, https://github.com/rappdw/cctrack
@@ -84,7 +84,7 @@ Daily breakdown:
84
84
 
85
85
  1. Walks `~/.claude/projects/` — and each [Sandy](#sandy-sandboxes) sandbox's `claude/projects/` — for Claude Code transcripts, and each Codex home for Codex rollouts
86
86
  2. Parses `assistant` events with token usage
87
- 3. Deduplicates by `requestId` (last event wins, matching Claude Code's semantics)
87
+ 3. Deduplicates API message/response identities across files, Sandy sandboxes and remote hosts, keeping the fullest usage snapshot
88
88
  4. Calculates cost using Anthropic's published rates per model
89
89
  5. Prints daily breakdown with input/output/cache token splits and monthly summaries
90
90
 
@@ -94,20 +94,24 @@ cctrack also reads [Codex CLI](https://github.com/openai/codex) usage from `$COD
94
94
 
95
95
  How it's counted (verified against the Codex source, not inferred):
96
96
 
97
- - **Per-response usage.** Newer Codex versions log a `token_usage_record` for every API response with a unique `response_id`; those are counted and deduplicated across files, so forked and resumed threads (which replay their parent's history) aren't double counted. Older versions only log `token_count` events, which are re-emitted with unchanged totals — only events whose running total moved are counted.
97
+ - **Request records and cumulative snapshots.** `token_usage_record` and `token_count` can coexist, including around compactions. A request record replaces only its matching snapshot; later ordinary usage still counts. Last-usage-only and cumulative-only rollouts are supported, and unchanged cumulative re-emissions are ignored. Explicit models on request records take precedence over the surrounding turn's model.
98
+ - **Forks and copies.** Response IDs deduplicate exact records. Older fork histories with rewritten timestamps are compared against the parent's usage sequence. If the parent is unavailable, possible replay is retained and flagged UNKNOWN by `--coverage`; a fast burst alone is not proof of duplication.
98
99
  - **Cached tokens are inside `input_tokens`.** Codex reports cached reads and cache writes as parts of `input_tokens`, and reasoning tokens as part of `output_tokens`. Billable uncached input is `input − cached − cache_write`; reasoning is never added on top.
99
100
  - **Its own cost source.** Codex spend is priced directly from its logs and is never replaced by, or scaled with, Claude Code's statusline-hook figures.
100
101
  - **Compressed rollouts.** Codex compresses older rollouts to `.jsonl.zst`. Python's standard library only reads zstd from 3.14, so on older Pythons cctrack uses the `zstd` command if it's installed, and otherwise skips those files and says how many it skipped.
101
102
 
103
+ Recorded `service_tier` settings (`priority`/`fast`, `flex`, or `default`/`standard`) select the model's corresponding price. Claude's recorded `usage.speed` is also respected. Missing tier metadata uses standard pricing; today's config is not applied retrospectively to old requests.
104
+
102
105
  Costs are at OpenAI's **API list prices**. If you use Codex through a ChatGPT plan, that's an API-equivalent value, not what you're billed — the same is true of Claude Code on a Claude subscription.
103
106
 
104
107
  ## Sandy sandboxes
105
108
 
106
109
  cctrack finds every [Sandy](https://github.com/rappdw/sandy) sandbox on the machine (and on `--remote` hosts) and includes its Claude Code and Codex usage. It follows sandy's published host-side path contract:
107
110
 
108
- - **Finding sandboxes:** `sandy --print-state` (`sandboxes[].path`) when sandy is installed, which follows `$SANDY_HOME`; otherwise `$SANDY_HOME/sandboxes/*` (default `~/.sandy/sandboxes`).
111
+ - **Finding sandboxes:** a direct scan of `$SANDY_HOME/sandboxes/*` (default `~/.sandy/sandboxes`), the same on `--remote` hosts. `sandy --print-state` can take many seconds, so cctrack only asks it when that directory doesn't exist, waiting at most 15 seconds (`CCTRACK_SANDY_TIMEOUT`).
109
112
  - **Per sandbox:** Claude Code transcripts from `claude/projects/`, statusline-hook data from `claude/cctrack/`, Codex rollouts from `codex/sessions/` and `codex/archived_sessions/`. Other files under `claude/` (`history.jsonl`, job timelines, tool-audit logs) aren't transcripts and are ignored.
110
- - **Never double counted:** the hidden `.rsync-from.<name>.<pid>/` copy that exists while `sandy --rsync-from` is pulling a sandbox in is skipped, as are `.lock` directories. A sandbox's Codex home is never shared with the host's `~/.codex`, and anything copied between hosts with `sandy --rsync` is deduplicated by request/response id.
113
+ - **Copies:** matching API identities are charged once across all collected locations. The fullest usage snapshot wins; equivalent copies have deterministic attribution. Session JSON/CSV includes `source_locations` and `source_files` so every copy remains traceable. Raw statusline histories are merged before calculating cost increments. Old monthly hook summaries contain no session identities, so copied summaries cannot yet be deduplicated reliably.
114
+ - **Temporary copies:** the hidden `.rsync-from.<name>.<pid>/` copy that exists while `sandy --rsync-from` is pulling a sandbox in is skipped, as are `.lock` directories. A sandbox's Codex home is never shared with the host's `~/.codex`, and transcript history copied between hosts with `sandy --rsync` is deduplicated by API message/response identity.
111
115
 
112
116
  - **Dot-named sandboxes count:** a workspace named like a dotfile directory (e.g. `~/.dotfiles`) gets a sandbox whose name starts with a dot. Sandy's own listing currently omits these, so cctrack scans for them itself — any dot-directory holding `WORKSPACE.json` is a real sandbox.
113
117
 
@@ -153,15 +157,36 @@ cctrack --json --redact # hash path
153
157
  ```
154
158
 
155
159
  - `--since` / `--until` take ISO-8601 (zones converted to UTC; naive times are UTC) or `YYYY-MM-DD`. The window is `since <= t < until`, and a bare `--until` date includes that whole day.
156
- - **Sessions**: one row per session, with Claude subagent (sidechain) turns as their own rows linked by `parent_session_id`. Codex subagent threads are separate sessions that carry their parent's id. Each row has agent, host, Sandy sandbox, project/cwd, git branch, first and last record time, models, request count, tokens and cost in five classes (input, output, cache read, 5-minute and 1-hour cache write), mean and max cache-read and context tokens per request, and compactions.
160
+ - **Sessions**: one row per session, with Claude subagent (sidechain) turns as their own rows linked by `parent_session_id`. Codex subagent threads are separate sessions that carry their parent's id. Each row has agent, host, Sandy sandbox, project/cwd, git branch, recorded service-tier counts and all observed copy locations, first and last record time, models, request count, tokens and cost in five classes (input, output, cache read, 5-minute and 1-hour cache write), mean and max cache-read and context tokens per request, and compactions.
157
161
  - **Cost basis**: `cost_usd` is always API list price from the built-in rate card. The rates applied (per model, $/Mtok per class), the card's version and its sources are in the JSON (`rate_card`, `cost_basis`) and in `--csv rates`. For Claude, `hook_cost_usd` is Claude Code's own cost counter. It's booked per UTC day, so it's only filled in for day-aligned windows. Logs don't say whether you're on API or subscription billing, so record that with `--billing-mode subscription` (or `claude=subscription,codex=api`, or `CCTRACK_BILLING_MODE`). It's shown on each row and doesn't change cost.
158
162
  - **Coverage**: for each log directory (per host and sandbox), the file count, usage records, earliest and latest timestamp, and any unparseable lines or unreadable files (status `UNKNOWN`). Days in the window with no records are listed as UNKNOWN, since idle days and lost logs look the same. Where the statusline hook saw Claude spend but no transcript exists, the day and session are flagged with tokens UNKNOWN. That's the signature of lost logs.
159
163
  - `--redact` hashes cwd, project, sandbox, branch and file paths, but not session ids. Set `CCTRACK_REDACT_SALT` so the hashes of guessable repo names can't be reversed.
160
164
  - JSON and CSV carry `schema_version` (currently 1). Field names are stable within a schema version.
161
165
 
166
+ ## Statusline hook (optional)
167
+
168
+ ```bash
169
+ cctrack --install-hook # this machine (add --remote HOST to install on another)
170
+ cctrack --uninstall-hook # keeps the data it collected
171
+ ```
172
+
173
+ The hook is optional. Without it, Claude Code cost is priced from the transcripts at list price. With current rates that tracks Claude Code's own counter closely, typically within a few percent. With it, cctrack also records Claude Code's own running cost counter. That gives you:
174
+
175
+ - the "authoritative" Claude cost in reports and `hook_cost_usd` in JSON;
176
+ - a measured correction for days priced from transcripts;
177
+ - detection of lost transcripts in `--coverage`.
178
+
179
+ It's installed as Claude Code's `statusLine` command (`~/.claude/hooks/cctrack-hook.py`), not as an entry under `hooks`. Each status-line redraw appends one record to `~/.claude/cctrack/statusline-<UTC date>.jsonl`.
180
+
181
+ **An existing status line is kept.** If one is configured, install saves it in `~/.claude/cctrack/config.json`. On every redraw the hook records the cost, then runs your command with the same input, and passes its output and exit code through, so your status line looks the same as before. Uninstall puts your status line back. If you've changed the status line to something else since installing, uninstall leaves it alone. Re-installing keeps the saved command and the original install date.
182
+
162
183
  ## Remote aggregation
163
184
 
164
- With `--remote`, cctrack SSHs to each host and streams back both the JSONL logs and the host's statusline hook data (`~/.claude/cctrack/`) for local parsing, so authoritative hook costs from every machine are summed per day. Requires SSH key auth.
185
+ With `--remote`, cctrack reads each host's Claude Code transcripts, Codex rollouts and statusline hook data (`~/.claude/cctrack/`), including the host's Sandy sandboxes. Usage from every machine is then reconciled and summed per day. Requires SSH key auth.
186
+
187
+ **Logs are parsed on the host.** Over one SSH connection, cctrack sends its own code to the host and runs it with `python3 -`. Only the usage records come back: ids, timestamps, models and token counts, compressed. Raw logs are mostly conversation content, so this cuts the transfer from gigabytes to megabytes. The host doesn't need cctrack installed, nothing on it is changed, and the results are the same as reading the raw logs. If the host has no Python 3.10+, cctrack says so and streams the raw logs instead, gzip-compressed. Set `CCTRACK_REMOTE_PARSE=0` to always stream.
188
+
189
+ Each fetch may take up to 600 seconds (set `CCTRACK_SSH_TIMEOUT` to change it). If one times out, cctrack warns that the host's data is missing from the report. While it works, a status line on stderr shows each step: files found and parsed, bytes received, elapsed time. It's shown only when stderr is a terminal; `CCTRACK_NO_PROGRESS=1` turns it off.
165
190
 
166
191
  ```bash
167
192
  # Aggregate this machine + DGX server + laptop
@@ -184,7 +209,8 @@ Prices per million tokens. Claude prices are from [Anthropic's pricing page](htt
184
209
  | Opus 4.1 / 4 | $15.00 | $75.00 | $1.50 | $18.75 | $30.00 |
185
210
  | Sonnet 5.5 | $2.00 | $10.00 | $0.10 | $2.50 | $4.00 |
186
211
  | Sonnet 5 | $2.00 | $10.00 | $0.20 | $2.50 | $4.00 |
187
- | Sonnet 4.6 / 4.5 / 4 / 3.7 | $3.00 | $15.00 | $0.30 | $3.75 | $6.00 |
212
+ | Sonnet 4.6 / 4.5 / 4 / 3.7 (base) | $3.00 | $15.00 | $0.30 | $3.75 | $6.00 |
213
+ | Sonnet 4.5 / 4 (historical prompts > 200K) | $6.00 | $22.50 | $0.60 | $7.50 | $12.00 |
188
214
  | Haiku 5.5 (prompt ≤ 100K) | $0.10 | $0.50 | $0.01 | $0.125 | $0.20 |
189
215
  | Haiku 5.5 (prompt > 100K) | $0.50 | $2.50 | $0.05 | $0.625 | $1.00 |
190
216
  | Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | $2.00 |
@@ -214,9 +240,21 @@ OpenAI prices (for Codex) are from [OpenAI's pricing page](https://developers.op
214
240
  | gpt-5-mini | $0.25 | $0.025 | $2.00 | — | |
215
241
  | gpt-5-nano | $0.05 | $0.005 | $0.40 | — | |
216
242
 
217
- Codex variants without their own price (e.g. `gpt-5.1-codex`) are priced as their base model, consistent with the one variant OpenAI does list (`gpt-5.3-codex` = `gpt-5.2`). Long-context and Haiku 5.5 prompt-length tiers are applied per request.
243
+ Codex variants without their own price (e.g. `gpt-5.1-codex`) are priced as their base model, consistent with the one variant OpenAI does list (`gpt-5.3-codex` = `gpt-5.2`). Long-context and Haiku 5.5 prompt-length tiers are applied to the whole request, including cache tokens when selecting the tier. The historical Sonnet 4/4.5 premium follows [Anthropic's published whole-request pricing](https://claude.com/resources/articles/1m-context), rather than ccusage 20.0.34's marginal calculation. Explicit aliases include `gpt-5.1-codex-mini` (GPT-5 mini), `gpt-5.1-codex-max` (GPT-5.1), and `gpt-5.6` (GPT-5.6 Sol); dated snapshots of those aliases are supported.
244
+
245
+ **Every model version has its own row.** A model only matches a row if it is that version or a dated snapshot of it — never a newer minor version. So a newly released model (say `claude-opus-5-7`, or `gpt-5.9-codex-mini`) shows as unknown and is flagged with `?` in the Model column, rather than silently inheriting its predecessor's price. Unknown Claude models are estimated at Sonnet rates, unknown OpenAI models at GPT-5 rates. Pricing is date-aware, so any time-limited introductory price applies only to usage on the days it was in effect.
246
+
247
+ ## Accounting regression checks
248
+
249
+ Run the offline test suite with `PYTHONPATH=src python3 -m pytest`. Synthetic fixtures in `tests/fixtures/ccusage-parity.json` are pinned to ccusage 20.0.34, commit `e4f63baa4e2943d4588f1b644281d6c8325faa74`. They cover compactions, legacy snapshots, forks, speed tiers, message deduplication, advisor calls and model aliases. Additional tests cover sandbox/host copies, cumulative hook histories, context boundaries and attribution.
250
+
251
+ To repeat the comparison against an independently installed executable:
252
+
253
+ ```bash
254
+ PYTHONPATH=src python3 scripts/compare_ccusage.py --ccusage /path/to/ccusage
255
+ ```
218
256
 
219
- **Every model version has its own row.** A model only matches a row if it is that version or a dated snapshot of it — never a newer minor version. So a newly released model (say `claude-opus-5-7`, or `gpt-5.1-codex-mini`) shows as unknown and is flagged with `?` in the Model column, rather than silently inheriting its predecessor's price. Unknown Claude models are estimated at Sonnet rates, unknown OpenAI models at GPT-5 rates. Pricing is date-aware, so any time-limited introductory price applies only to usage on the days it was in effect.
257
+ The command requires exactly ccusage 20.0.34 and uses isolated temporary homes with offline pricing. Runtime cctrack and its normal tests do not depend on Node or ccusage. Provider documentation resolves pricing disagreements. Intentional differences are recorded in the fixture: Sonnet 4 uses whole-request context pricing, unknown models retain a flagged estimate, and cctrack's token-derived costs correspond to ccusage's `calculate` mode rather than its stored-`costUSD` `auto` mode.
220
258
 
221
259
  ## Energy estimate
222
260
 
@@ -59,7 +59,7 @@ Daily breakdown:
59
59
 
60
60
  1. Walks `~/.claude/projects/` — and each [Sandy](#sandy-sandboxes) sandbox's `claude/projects/` — for Claude Code transcripts, and each Codex home for Codex rollouts
61
61
  2. Parses `assistant` events with token usage
62
- 3. Deduplicates by `requestId` (last event wins, matching Claude Code's semantics)
62
+ 3. Deduplicates API message/response identities across files, Sandy sandboxes and remote hosts, keeping the fullest usage snapshot
63
63
  4. Calculates cost using Anthropic's published rates per model
64
64
  5. Prints daily breakdown with input/output/cache token splits and monthly summaries
65
65
 
@@ -69,20 +69,24 @@ cctrack also reads [Codex CLI](https://github.com/openai/codex) usage from `$COD
69
69
 
70
70
  How it's counted (verified against the Codex source, not inferred):
71
71
 
72
- - **Per-response usage.** Newer Codex versions log a `token_usage_record` for every API response with a unique `response_id`; those are counted and deduplicated across files, so forked and resumed threads (which replay their parent's history) aren't double counted. Older versions only log `token_count` events, which are re-emitted with unchanged totals — only events whose running total moved are counted.
72
+ - **Request records and cumulative snapshots.** `token_usage_record` and `token_count` can coexist, including around compactions. A request record replaces only its matching snapshot; later ordinary usage still counts. Last-usage-only and cumulative-only rollouts are supported, and unchanged cumulative re-emissions are ignored. Explicit models on request records take precedence over the surrounding turn's model.
73
+ - **Forks and copies.** Response IDs deduplicate exact records. Older fork histories with rewritten timestamps are compared against the parent's usage sequence. If the parent is unavailable, possible replay is retained and flagged UNKNOWN by `--coverage`; a fast burst alone is not proof of duplication.
73
74
  - **Cached tokens are inside `input_tokens`.** Codex reports cached reads and cache writes as parts of `input_tokens`, and reasoning tokens as part of `output_tokens`. Billable uncached input is `input − cached − cache_write`; reasoning is never added on top.
74
75
  - **Its own cost source.** Codex spend is priced directly from its logs and is never replaced by, or scaled with, Claude Code's statusline-hook figures.
75
76
  - **Compressed rollouts.** Codex compresses older rollouts to `.jsonl.zst`. Python's standard library only reads zstd from 3.14, so on older Pythons cctrack uses the `zstd` command if it's installed, and otherwise skips those files and says how many it skipped.
76
77
 
78
+ Recorded `service_tier` settings (`priority`/`fast`, `flex`, or `default`/`standard`) select the model's corresponding price. Claude's recorded `usage.speed` is also respected. Missing tier metadata uses standard pricing; today's config is not applied retrospectively to old requests.
79
+
77
80
  Costs are at OpenAI's **API list prices**. If you use Codex through a ChatGPT plan, that's an API-equivalent value, not what you're billed — the same is true of Claude Code on a Claude subscription.
78
81
 
79
82
  ## Sandy sandboxes
80
83
 
81
84
  cctrack finds every [Sandy](https://github.com/rappdw/sandy) sandbox on the machine (and on `--remote` hosts) and includes its Claude Code and Codex usage. It follows sandy's published host-side path contract:
82
85
 
83
- - **Finding sandboxes:** `sandy --print-state` (`sandboxes[].path`) when sandy is installed, which follows `$SANDY_HOME`; otherwise `$SANDY_HOME/sandboxes/*` (default `~/.sandy/sandboxes`).
86
+ - **Finding sandboxes:** a direct scan of `$SANDY_HOME/sandboxes/*` (default `~/.sandy/sandboxes`), the same on `--remote` hosts. `sandy --print-state` can take many seconds, so cctrack only asks it when that directory doesn't exist, waiting at most 15 seconds (`CCTRACK_SANDY_TIMEOUT`).
84
87
  - **Per sandbox:** Claude Code transcripts from `claude/projects/`, statusline-hook data from `claude/cctrack/`, Codex rollouts from `codex/sessions/` and `codex/archived_sessions/`. Other files under `claude/` (`history.jsonl`, job timelines, tool-audit logs) aren't transcripts and are ignored.
85
- - **Never double counted:** the hidden `.rsync-from.<name>.<pid>/` copy that exists while `sandy --rsync-from` is pulling a sandbox in is skipped, as are `.lock` directories. A sandbox's Codex home is never shared with the host's `~/.codex`, and anything copied between hosts with `sandy --rsync` is deduplicated by request/response id.
88
+ - **Copies:** matching API identities are charged once across all collected locations. The fullest usage snapshot wins; equivalent copies have deterministic attribution. Session JSON/CSV includes `source_locations` and `source_files` so every copy remains traceable. Raw statusline histories are merged before calculating cost increments. Old monthly hook summaries contain no session identities, so copied summaries cannot yet be deduplicated reliably.
89
+ - **Temporary copies:** the hidden `.rsync-from.<name>.<pid>/` copy that exists while `sandy --rsync-from` is pulling a sandbox in is skipped, as are `.lock` directories. A sandbox's Codex home is never shared with the host's `~/.codex`, and transcript history copied between hosts with `sandy --rsync` is deduplicated by API message/response identity.
86
90
 
87
91
  - **Dot-named sandboxes count:** a workspace named like a dotfile directory (e.g. `~/.dotfiles`) gets a sandbox whose name starts with a dot. Sandy's own listing currently omits these, so cctrack scans for them itself — any dot-directory holding `WORKSPACE.json` is a real sandbox.
88
92
 
@@ -128,15 +132,36 @@ cctrack --json --redact # hash path
128
132
  ```
129
133
 
130
134
  - `--since` / `--until` take ISO-8601 (zones converted to UTC; naive times are UTC) or `YYYY-MM-DD`. The window is `since <= t < until`, and a bare `--until` date includes that whole day.
131
- - **Sessions**: one row per session, with Claude subagent (sidechain) turns as their own rows linked by `parent_session_id`. Codex subagent threads are separate sessions that carry their parent's id. Each row has agent, host, Sandy sandbox, project/cwd, git branch, first and last record time, models, request count, tokens and cost in five classes (input, output, cache read, 5-minute and 1-hour cache write), mean and max cache-read and context tokens per request, and compactions.
135
+ - **Sessions**: one row per session, with Claude subagent (sidechain) turns as their own rows linked by `parent_session_id`. Codex subagent threads are separate sessions that carry their parent's id. Each row has agent, host, Sandy sandbox, project/cwd, git branch, recorded service-tier counts and all observed copy locations, first and last record time, models, request count, tokens and cost in five classes (input, output, cache read, 5-minute and 1-hour cache write), mean and max cache-read and context tokens per request, and compactions.
132
136
  - **Cost basis**: `cost_usd` is always API list price from the built-in rate card. The rates applied (per model, $/Mtok per class), the card's version and its sources are in the JSON (`rate_card`, `cost_basis`) and in `--csv rates`. For Claude, `hook_cost_usd` is Claude Code's own cost counter. It's booked per UTC day, so it's only filled in for day-aligned windows. Logs don't say whether you're on API or subscription billing, so record that with `--billing-mode subscription` (or `claude=subscription,codex=api`, or `CCTRACK_BILLING_MODE`). It's shown on each row and doesn't change cost.
133
137
  - **Coverage**: for each log directory (per host and sandbox), the file count, usage records, earliest and latest timestamp, and any unparseable lines or unreadable files (status `UNKNOWN`). Days in the window with no records are listed as UNKNOWN, since idle days and lost logs look the same. Where the statusline hook saw Claude spend but no transcript exists, the day and session are flagged with tokens UNKNOWN. That's the signature of lost logs.
134
138
  - `--redact` hashes cwd, project, sandbox, branch and file paths, but not session ids. Set `CCTRACK_REDACT_SALT` so the hashes of guessable repo names can't be reversed.
135
139
  - JSON and CSV carry `schema_version` (currently 1). Field names are stable within a schema version.
136
140
 
141
+ ## Statusline hook (optional)
142
+
143
+ ```bash
144
+ cctrack --install-hook # this machine (add --remote HOST to install on another)
145
+ cctrack --uninstall-hook # keeps the data it collected
146
+ ```
147
+
148
+ The hook is optional. Without it, Claude Code cost is priced from the transcripts at list price. With current rates that tracks Claude Code's own counter closely, typically within a few percent. With it, cctrack also records Claude Code's own running cost counter. That gives you:
149
+
150
+ - the "authoritative" Claude cost in reports and `hook_cost_usd` in JSON;
151
+ - a measured correction for days priced from transcripts;
152
+ - detection of lost transcripts in `--coverage`.
153
+
154
+ It's installed as Claude Code's `statusLine` command (`~/.claude/hooks/cctrack-hook.py`), not as an entry under `hooks`. Each status-line redraw appends one record to `~/.claude/cctrack/statusline-<UTC date>.jsonl`.
155
+
156
+ **An existing status line is kept.** If one is configured, install saves it in `~/.claude/cctrack/config.json`. On every redraw the hook records the cost, then runs your command with the same input, and passes its output and exit code through, so your status line looks the same as before. Uninstall puts your status line back. If you've changed the status line to something else since installing, uninstall leaves it alone. Re-installing keeps the saved command and the original install date.
157
+
137
158
  ## Remote aggregation
138
159
 
139
- With `--remote`, cctrack SSHs to each host and streams back both the JSONL logs and the host's statusline hook data (`~/.claude/cctrack/`) for local parsing, so authoritative hook costs from every machine are summed per day. Requires SSH key auth.
160
+ With `--remote`, cctrack reads each host's Claude Code transcripts, Codex rollouts and statusline hook data (`~/.claude/cctrack/`), including the host's Sandy sandboxes. Usage from every machine is then reconciled and summed per day. Requires SSH key auth.
161
+
162
+ **Logs are parsed on the host.** Over one SSH connection, cctrack sends its own code to the host and runs it with `python3 -`. Only the usage records come back: ids, timestamps, models and token counts, compressed. Raw logs are mostly conversation content, so this cuts the transfer from gigabytes to megabytes. The host doesn't need cctrack installed, nothing on it is changed, and the results are the same as reading the raw logs. If the host has no Python 3.10+, cctrack says so and streams the raw logs instead, gzip-compressed. Set `CCTRACK_REMOTE_PARSE=0` to always stream.
163
+
164
+ Each fetch may take up to 600 seconds (set `CCTRACK_SSH_TIMEOUT` to change it). If one times out, cctrack warns that the host's data is missing from the report. While it works, a status line on stderr shows each step: files found and parsed, bytes received, elapsed time. It's shown only when stderr is a terminal; `CCTRACK_NO_PROGRESS=1` turns it off.
140
165
 
141
166
  ```bash
142
167
  # Aggregate this machine + DGX server + laptop
@@ -159,7 +184,8 @@ Prices per million tokens. Claude prices are from [Anthropic's pricing page](htt
159
184
  | Opus 4.1 / 4 | $15.00 | $75.00 | $1.50 | $18.75 | $30.00 |
160
185
  | Sonnet 5.5 | $2.00 | $10.00 | $0.10 | $2.50 | $4.00 |
161
186
  | Sonnet 5 | $2.00 | $10.00 | $0.20 | $2.50 | $4.00 |
162
- | Sonnet 4.6 / 4.5 / 4 / 3.7 | $3.00 | $15.00 | $0.30 | $3.75 | $6.00 |
187
+ | Sonnet 4.6 / 4.5 / 4 / 3.7 (base) | $3.00 | $15.00 | $0.30 | $3.75 | $6.00 |
188
+ | Sonnet 4.5 / 4 (historical prompts > 200K) | $6.00 | $22.50 | $0.60 | $7.50 | $12.00 |
163
189
  | Haiku 5.5 (prompt ≤ 100K) | $0.10 | $0.50 | $0.01 | $0.125 | $0.20 |
164
190
  | Haiku 5.5 (prompt > 100K) | $0.50 | $2.50 | $0.05 | $0.625 | $1.00 |
165
191
  | Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | $2.00 |
@@ -189,9 +215,21 @@ OpenAI prices (for Codex) are from [OpenAI's pricing page](https://developers.op
189
215
  | gpt-5-mini | $0.25 | $0.025 | $2.00 | — | |
190
216
  | gpt-5-nano | $0.05 | $0.005 | $0.40 | — | |
191
217
 
192
- Codex variants without their own price (e.g. `gpt-5.1-codex`) are priced as their base model, consistent with the one variant OpenAI does list (`gpt-5.3-codex` = `gpt-5.2`). Long-context and Haiku 5.5 prompt-length tiers are applied per request.
218
+ Codex variants without their own price (e.g. `gpt-5.1-codex`) are priced as their base model, consistent with the one variant OpenAI does list (`gpt-5.3-codex` = `gpt-5.2`). Long-context and Haiku 5.5 prompt-length tiers are applied to the whole request, including cache tokens when selecting the tier. The historical Sonnet 4/4.5 premium follows [Anthropic's published whole-request pricing](https://claude.com/resources/articles/1m-context), rather than ccusage 20.0.34's marginal calculation. Explicit aliases include `gpt-5.1-codex-mini` (GPT-5 mini), `gpt-5.1-codex-max` (GPT-5.1), and `gpt-5.6` (GPT-5.6 Sol); dated snapshots of those aliases are supported.
219
+
220
+ **Every model version has its own row.** A model only matches a row if it is that version or a dated snapshot of it — never a newer minor version. So a newly released model (say `claude-opus-5-7`, or `gpt-5.9-codex-mini`) shows as unknown and is flagged with `?` in the Model column, rather than silently inheriting its predecessor's price. Unknown Claude models are estimated at Sonnet rates, unknown OpenAI models at GPT-5 rates. Pricing is date-aware, so any time-limited introductory price applies only to usage on the days it was in effect.
221
+
222
+ ## Accounting regression checks
223
+
224
+ Run the offline test suite with `PYTHONPATH=src python3 -m pytest`. Synthetic fixtures in `tests/fixtures/ccusage-parity.json` are pinned to ccusage 20.0.34, commit `e4f63baa4e2943d4588f1b644281d6c8325faa74`. They cover compactions, legacy snapshots, forks, speed tiers, message deduplication, advisor calls and model aliases. Additional tests cover sandbox/host copies, cumulative hook histories, context boundaries and attribution.
225
+
226
+ To repeat the comparison against an independently installed executable:
227
+
228
+ ```bash
229
+ PYTHONPATH=src python3 scripts/compare_ccusage.py --ccusage /path/to/ccusage
230
+ ```
193
231
 
194
- **Every model version has its own row.** A model only matches a row if it is that version or a dated snapshot of it — never a newer minor version. So a newly released model (say `claude-opus-5-7`, or `gpt-5.1-codex-mini`) shows as unknown and is flagged with `?` in the Model column, rather than silently inheriting its predecessor's price. Unknown Claude models are estimated at Sonnet rates, unknown OpenAI models at GPT-5 rates. Pricing is date-aware, so any time-limited introductory price applies only to usage on the days it was in effect.
232
+ The command requires exactly ccusage 20.0.34 and uses isolated temporary homes with offline pricing. Runtime cctrack and its normal tests do not depend on Node or ccusage. Provider documentation resolves pricing disagreements. Intentional differences are recorded in the fixture: Sonnet 4 uses whole-request context pricing, unknown models retain a flagged estimate, and cctrack's token-derived costs correspond to ccusage's `calculate` mode rather than its stored-`costUSD` `auto` mode.
195
233
 
196
234
  ## Energy estimate
197
235
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cctrack"
7
- version = "0.10.0"
7
+ version = "0.11.1"
8
8
  description = "Claude Code cost tracker — scans JSONL logs and reports token usage + estimated cost"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -34,3 +34,14 @@ cctrack = "cctrack:main"
34
34
  Homepage = "https://github.com/rappdw/cctrack"
35
35
  Repository = "https://github.com/rappdw/cctrack"
36
36
  Issues = "https://github.com/rappdw/cctrack/issues"
37
+
38
+ [tool.hatch.build.targets.sdist]
39
+ include = [
40
+ "/src",
41
+ "/tests",
42
+ "/scripts",
43
+ "/README.md",
44
+ "/CLAUDE.md",
45
+ "/LICENSE",
46
+ "/pyproject.toml",
47
+ ]
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env python3
2
+ """Run synthetic accounting fixtures against the pinned ccusage executable.
3
+
4
+ Install ccusage@20.0.34 separately, then run:
5
+ PYTHONPATH=src python3 scripts/compare_ccusage.py --ccusage /path/to/ccusage
6
+
7
+ The normal test suite needs neither ccusage nor network access. This optional
8
+ check verifies that its frozen reference values still match the pinned binary.
9
+ """
10
+ import argparse
11
+ import json
12
+ import math
13
+ import os
14
+ from pathlib import Path
15
+ import subprocess
16
+ import tempfile
17
+
18
+ import cctrack
19
+
20
+
21
+ def main():
22
+ parser = argparse.ArgumentParser(description=__doc__)
23
+ parser.add_argument('--ccusage', default='ccusage', help='Path to ccusage 20.0.34 executable')
24
+ args = parser.parse_args()
25
+ fixture = json.loads((Path(__file__).resolve().parents[1]
26
+ / 'tests/fixtures/ccusage-parity.json').read_text())
27
+ expected_version = fixture['reference']['package'].split('@')[-1]
28
+ version = subprocess.run([args.ccusage, '--version'], check=True, text=True,
29
+ capture_output=True).stdout.strip()
30
+ if version != f'ccusage {expected_version}':
31
+ parser.error(f'reference requires ccusage {expected_version}; found {version!r}')
32
+ failures = []
33
+ with tempfile.TemporaryDirectory(prefix='cctrack-parity-') as tmp:
34
+ for case in fixture['cases']:
35
+ home = Path(tmp) / case['name']
36
+ agent = case['agent']
37
+ directory = home / ('projects/p' if agent == 'claude' else 'sessions')
38
+ directory.mkdir(parents=True)
39
+ files = []
40
+ for i, rows in enumerate(case['files']):
41
+ path = directory / f'rollout-{i}.jsonl'
42
+ path.write_text('\n'.join(json.dumps(r, separators=(',', ':')) for r in rows) + '\n')
43
+ files.append(str(path))
44
+ env = dict(os.environ)
45
+ # Isolate all config/data discovery from the user's real usage.
46
+ env.update(HOME=str(home), CLAUDE_CONFIG_DIR=str(home), CODEX_HOME=str(home))
47
+ env.pop('CCUSAGE_MODEL_ALIASES', None)
48
+ command = [args.ccusage, agent, 'daily', '--offline', '--timezone', 'UTC', '--json']
49
+ if agent == 'claude':
50
+ command += ['--mode', 'calculate']
51
+ result = subprocess.run(command, env=env, cwd=home, check=True, text=True, capture_output=True)
52
+ totals = json.loads(result.stdout)['totals']
53
+ reference_cost = totals['totalCost' if agent == 'claude' else 'costUSD']
54
+ events = cctrack.parse_codex_events(files)[0] if agent == 'codex' else cctrack.parse_events(files)
55
+ daily, _ = cctrack.aggregate(events)
56
+ cost = sum(v['cost'] for v in daily.values())
57
+ tokens = sum(cctrack.total_tokens(v) for v in daily.values())
58
+ expected_reference = {'claude_long': 1.215, 'claude_unknown': 0}.get(
59
+ case['name'], case['expected_cost_usd'])
60
+ passed = (tokens == totals['totalTokens'] == case['expected_tokens']
61
+ and math.isclose(cost, case['expected_cost_usd'], abs_tol=1e-9)
62
+ and math.isclose(reference_cost, expected_reference, abs_tol=1e-9))
63
+ print(f"{'PASS' if passed else 'FAIL'} {case['name']}: "
64
+ f"{tokens} tokens, cctrack=${cost:.6f}, ccusage=${reference_cost:.6f}")
65
+ if not passed:
66
+ failures.append(case['name'])
67
+ if failures:
68
+ raise SystemExit(f"Accounting comparison failed: {', '.join(failures)}")
69
+ print(f"Verified {len(fixture['cases'])} cases against {version}.")
70
+
71
+
72
+ if __name__ == '__main__':
73
+ main()