cctrack 0.9.0__tar.gz → 0.11.0__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.
- {cctrack-0.9.0 → cctrack-0.11.0}/CLAUDE.md +12 -4
- {cctrack-0.9.0 → cctrack-0.11.0}/PKG-INFO +61 -7
- {cctrack-0.9.0 → cctrack-0.11.0}/README.md +60 -6
- {cctrack-0.9.0 → cctrack-0.11.0}/pyproject.toml +12 -1
- cctrack-0.11.0/scripts/compare_ccusage.py +73 -0
- {cctrack-0.9.0 → cctrack-0.11.0}/src/cctrack/__init__.py +1693 -271
- cctrack-0.11.0/tests/fixtures/ccusage-parity.json +717 -0
- cctrack-0.11.0/tests/test_accounting.py +400 -0
- {cctrack-0.9.0 → cctrack-0.11.0}/tests/test_cctrack.py +3 -2
- {cctrack-0.9.0 → cctrack-0.11.0}/tests/test_codex.py +5 -3
- cctrack-0.11.0/tests/test_detail.py +303 -0
- {cctrack-0.9.0 → cctrack-0.11.0}/tests/test_hook.py +163 -2
- cctrack-0.9.0/.github/workflows/ci.yml +0 -31
- cctrack-0.9.0/.github/workflows/publish.yml +0 -67
- {cctrack-0.9.0 → cctrack-0.11.0}/.gitignore +0 -0
- {cctrack-0.9.0 → cctrack-0.11.0}/LICENSE +0 -0
- {cctrack-0.9.0 → cctrack-0.11.0}/scripts/diagnose_session_cost.py +0 -0
- {cctrack-0.9.0 → cctrack-0.11.0}/scripts/trace_project.py +0 -0
- {cctrack-0.9.0 → cctrack-0.11.0}/src/cctrack/__main__.py +0 -0
- {cctrack-0.9.0 → cctrack-0.11.0}/tests/conftest.py +0 -0
- {cctrack-0.9.0 → cctrack-0.11.0}/tests/test_hook_reporting.py +0 -0
- {cctrack-0.9.0 → cctrack-0.11.0}/tests/test_sandy.py +0 -0
|
@@ -31,23 +31,25 @@ 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
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}`.
|
|
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
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.
|
|
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
|
-
|
|
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.
|
|
45
|
+
6b. **Detailed reports** (`run_detail_report`, `build_session_rows`, `build_bucket_rows`, `build_coverage`, `build_document`, `write_csv`; flags `--sessions --bucket --coverage --json --csv --since --until --redact --billing-mode`) - Everything UTC; `--since/--until` are a half-open window and are rejected without one of these views. Session key = (agent, host, sandbox, session id, subagent id): Claude sidechain turns (`isSidechain`, `agentId`, else the `agent-<id>.jsonl` filename) are separate rows linked to the parent sessionId; Codex threads use the record's `thread_id` (a fork's replayed records stay with the parent) and get a parent from `session_meta` (`source…parent_thread_id`, `forked_from_id`, or `session_id` ≠ `id`). Parsers fill per-file stats (`new_parse_stats`: lines, unparseable lines, records, timestamp range, compactions keyed by marker so resume replays don't double count) only when asked. Remote streams carry each file's path after the separator. Hook cost is day-granular, so it's attached only for day-aligned windows. Output is ids/paths/counts/money only; `SCHEMA_VERSION` must be bumped on any breaking field change.
|
|
44
46
|
|
|
45
47
|
Entry point: `cctrack:main` (registered in `pyproject.toml` as a console script).
|
|
46
48
|
|
|
47
49
|
## Key Design Decisions
|
|
48
50
|
|
|
49
51
|
- Zero external dependencies - stdlib only (json, argparse, subprocess, etc.)
|
|
50
|
-
- Deduplication is global
|
|
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.
|
|
51
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.
|
|
52
54
|
- Never let one machine's hook coverage suppress another machine's JSONL cost - compose per source.
|
|
53
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.
|
|
@@ -56,3 +58,9 @@ Entry point: `cctrack:main` (registered in `pyproject.toml` as a console script)
|
|
|
56
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.
|
|
57
59
|
- Build system is Hatch (`hatchling`)
|
|
58
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.
|
|
3
|
+
Version: 0.11.0
|
|
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
|
|
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,11 +94,14 @@ 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
|
-
- **
|
|
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
|
|
@@ -107,7 +110,8 @@ cctrack finds every [Sandy](https://github.com/rappdw/sandy) sandbox on the mach
|
|
|
107
110
|
|
|
108
111
|
- **Finding sandboxes:** `sandy --print-state` (`sandboxes[].path`) when sandy is installed, which follows `$SANDY_HOME`; otherwise `$SANDY_HOME/sandboxes/*` (default `~/.sandy/sandboxes`).
|
|
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
|
-
- **
|
|
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
|
|
|
@@ -139,6 +143,43 @@ cctrack --explore 2026-08-03 --project team-inbox
|
|
|
139
143
|
|
|
140
144
|
This restricts the view to that project and prints each session's full `cwd`, git branch, and the log file on disk (which reveals the host directory or the specific Sandy sandbox it came from). The unfiltered view flags this automatically when a `cwd` looks like a container path. `scripts/trace_project.py` and `scripts/diagnose_session_cost.py` are standalone versions of the trace and per-session cost diagnostics.
|
|
141
145
|
|
|
146
|
+
## Sessions, time buckets and coverage (JSON / CSV)
|
|
147
|
+
|
|
148
|
+
For attributing cost to sessions, roles or time windows. All times and day boundaries are **UTC**; output holds ids, paths, counts and money only, never prompt or response content.
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
cctrack --sessions --since 2026-10-11T02:30:04Z --until 2026-10-12 # per-session table
|
|
152
|
+
cctrack --bucket hour --since 2026-10-11 --until 2026-10-12 # cost per UTC hour
|
|
153
|
+
cctrack --coverage # what data exists, and gaps
|
|
154
|
+
cctrack --json --since 2026-10-11 > report.json # everything, one document
|
|
155
|
+
cctrack --csv sessions # or buckets | coverage | rates
|
|
156
|
+
cctrack --json --redact # hash paths and names
|
|
157
|
+
```
|
|
158
|
+
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
164
|
+
- JSON and CSV carry `schema_version` (currently 1). Field names are stable within a schema version.
|
|
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
|
+
|
|
142
183
|
## Remote aggregation
|
|
143
184
|
|
|
144
185
|
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.
|
|
@@ -164,7 +205,8 @@ Prices per million tokens. Claude prices are from [Anthropic's pricing page](htt
|
|
|
164
205
|
| Opus 4.1 / 4 | $15.00 | $75.00 | $1.50 | $18.75 | $30.00 |
|
|
165
206
|
| Sonnet 5.5 | $2.00 | $10.00 | $0.10 | $2.50 | $4.00 |
|
|
166
207
|
| Sonnet 5 | $2.00 | $10.00 | $0.20 | $2.50 | $4.00 |
|
|
167
|
-
| Sonnet 4.6 / 4.5 / 4 / 3.7 | $3.00 | $15.00 | $0.30 | $3.75 | $6.00 |
|
|
208
|
+
| Sonnet 4.6 / 4.5 / 4 / 3.7 (base) | $3.00 | $15.00 | $0.30 | $3.75 | $6.00 |
|
|
209
|
+
| Sonnet 4.5 / 4 (historical prompts > 200K) | $6.00 | $22.50 | $0.60 | $7.50 | $12.00 |
|
|
168
210
|
| Haiku 5.5 (prompt ≤ 100K) | $0.10 | $0.50 | $0.01 | $0.125 | $0.20 |
|
|
169
211
|
| Haiku 5.5 (prompt > 100K) | $0.50 | $2.50 | $0.05 | $0.625 | $1.00 |
|
|
170
212
|
| Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | $2.00 |
|
|
@@ -194,9 +236,21 @@ OpenAI prices (for Codex) are from [OpenAI's pricing page](https://developers.op
|
|
|
194
236
|
| gpt-5-mini | $0.25 | $0.025 | $2.00 | — | |
|
|
195
237
|
| gpt-5-nano | $0.05 | $0.005 | $0.40 | — | |
|
|
196
238
|
|
|
197
|
-
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
|
|
239
|
+
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.
|
|
240
|
+
|
|
241
|
+
**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.
|
|
242
|
+
|
|
243
|
+
## Accounting regression checks
|
|
244
|
+
|
|
245
|
+
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.
|
|
246
|
+
|
|
247
|
+
To repeat the comparison against an independently installed executable:
|
|
248
|
+
|
|
249
|
+
```bash
|
|
250
|
+
PYTHONPATH=src python3 scripts/compare_ccusage.py --ccusage /path/to/ccusage
|
|
251
|
+
```
|
|
198
252
|
|
|
199
|
-
|
|
253
|
+
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.
|
|
200
254
|
|
|
201
255
|
## Energy estimate
|
|
202
256
|
|
|
@@ -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
|
|
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,11 +69,14 @@ 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
|
-
- **
|
|
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
|
|
@@ -82,7 +85,8 @@ cctrack finds every [Sandy](https://github.com/rappdw/sandy) sandbox on the mach
|
|
|
82
85
|
|
|
83
86
|
- **Finding sandboxes:** `sandy --print-state` (`sandboxes[].path`) when sandy is installed, which follows `$SANDY_HOME`; otherwise `$SANDY_HOME/sandboxes/*` (default `~/.sandy/sandboxes`).
|
|
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
|
-
- **
|
|
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
|
|
|
@@ -114,6 +118,43 @@ cctrack --explore 2026-08-03 --project team-inbox
|
|
|
114
118
|
|
|
115
119
|
This restricts the view to that project and prints each session's full `cwd`, git branch, and the log file on disk (which reveals the host directory or the specific Sandy sandbox it came from). The unfiltered view flags this automatically when a `cwd` looks like a container path. `scripts/trace_project.py` and `scripts/diagnose_session_cost.py` are standalone versions of the trace and per-session cost diagnostics.
|
|
116
120
|
|
|
121
|
+
## Sessions, time buckets and coverage (JSON / CSV)
|
|
122
|
+
|
|
123
|
+
For attributing cost to sessions, roles or time windows. All times and day boundaries are **UTC**; output holds ids, paths, counts and money only, never prompt or response content.
|
|
124
|
+
|
|
125
|
+
```bash
|
|
126
|
+
cctrack --sessions --since 2026-10-11T02:30:04Z --until 2026-10-12 # per-session table
|
|
127
|
+
cctrack --bucket hour --since 2026-10-11 --until 2026-10-12 # cost per UTC hour
|
|
128
|
+
cctrack --coverage # what data exists, and gaps
|
|
129
|
+
cctrack --json --since 2026-10-11 > report.json # everything, one document
|
|
130
|
+
cctrack --csv sessions # or buckets | coverage | rates
|
|
131
|
+
cctrack --json --redact # hash paths and names
|
|
132
|
+
```
|
|
133
|
+
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
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.
|
|
139
|
+
- JSON and CSV carry `schema_version` (currently 1). Field names are stable within a schema version.
|
|
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
|
+
|
|
117
158
|
## Remote aggregation
|
|
118
159
|
|
|
119
160
|
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.
|
|
@@ -139,7 +180,8 @@ Prices per million tokens. Claude prices are from [Anthropic's pricing page](htt
|
|
|
139
180
|
| Opus 4.1 / 4 | $15.00 | $75.00 | $1.50 | $18.75 | $30.00 |
|
|
140
181
|
| Sonnet 5.5 | $2.00 | $10.00 | $0.10 | $2.50 | $4.00 |
|
|
141
182
|
| Sonnet 5 | $2.00 | $10.00 | $0.20 | $2.50 | $4.00 |
|
|
142
|
-
| Sonnet 4.6 / 4.5 / 4 / 3.7 | $3.00 | $15.00 | $0.30 | $3.75 | $6.00 |
|
|
183
|
+
| Sonnet 4.6 / 4.5 / 4 / 3.7 (base) | $3.00 | $15.00 | $0.30 | $3.75 | $6.00 |
|
|
184
|
+
| Sonnet 4.5 / 4 (historical prompts > 200K) | $6.00 | $22.50 | $0.60 | $7.50 | $12.00 |
|
|
143
185
|
| Haiku 5.5 (prompt ≤ 100K) | $0.10 | $0.50 | $0.01 | $0.125 | $0.20 |
|
|
144
186
|
| Haiku 5.5 (prompt > 100K) | $0.50 | $2.50 | $0.05 | $0.625 | $1.00 |
|
|
145
187
|
| Haiku 4.5 | $1.00 | $5.00 | $0.10 | $1.25 | $2.00 |
|
|
@@ -169,9 +211,21 @@ OpenAI prices (for Codex) are from [OpenAI's pricing page](https://developers.op
|
|
|
169
211
|
| gpt-5-mini | $0.25 | $0.025 | $2.00 | — | |
|
|
170
212
|
| gpt-5-nano | $0.05 | $0.005 | $0.40 | — | |
|
|
171
213
|
|
|
172
|
-
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
|
|
214
|
+
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.
|
|
215
|
+
|
|
216
|
+
**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.
|
|
217
|
+
|
|
218
|
+
## Accounting regression checks
|
|
219
|
+
|
|
220
|
+
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.
|
|
221
|
+
|
|
222
|
+
To repeat the comparison against an independently installed executable:
|
|
223
|
+
|
|
224
|
+
```bash
|
|
225
|
+
PYTHONPATH=src python3 scripts/compare_ccusage.py --ccusage /path/to/ccusage
|
|
226
|
+
```
|
|
173
227
|
|
|
174
|
-
|
|
228
|
+
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.
|
|
175
229
|
|
|
176
230
|
## Energy estimate
|
|
177
231
|
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "cctrack"
|
|
7
|
-
version = "0.
|
|
7
|
+
version = "0.11.0"
|
|
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()
|