Skip to content

About

Conformance fixtures, log-format-change radar and secret audit for AI coding agent usage trackers (Claude Code, Codex, Antigravity CLI).

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

usagebench

Token-usage conformance tests for AI coding agent logs (Claude Code, Codex, Antigravity CLI).

Stop guessing when AI coding agents break your token parser.

usagebench is a test oracle for usage trackers that read Claude Code, Codex and antigravity-cli session logs: anonymized real logs with pinned expected totals, a reference parser, and a record of every log-format change that matters for token counting. The CLI has no network code and only reads your logs (the one exception, audit --fix --yes, rewrites a file you choose to redact and keeps a backup).

What it gives you:

  • Conformance fixtures with expected totals, cross-checked by the TypeScript parser, the Python fixture tool and an independent third computation (tools/verify_independent.py).
  • usagebench doctor: how much a tracker that sums every usage line would overcount on your own logs.
  • usagebench compare / diff: run ccusage, tokscale or splitrail against the fixtures, or against a temp copy of your own recent logs, and see the per-field delta.
  • usagebench repro: turn a session where a tracker is off into a small anonymized repro + expected totals + issue text.
  • usagebench audit: find plaintext API keys, private keys, DB passwords and seed phrases in your agent logs.
  • FORMAT_CHANGES.md: the log-format radar, per agent version.
  • A Node-free fixtures tarball on every release, for trackers written in Rust, Go or anything else.

Status: pre-release (0.x), schema draft.

Try it in 5 seconds

npx usagebench doctor

Log directories are found automatically on Windows, macOS and Linux (~/.claude/projects, ~/.config/claude/projects, ~/.codex/sessions); CLAUDE_CONFIG_DIR and CODEX_HOME override them. Output is counts and ratios only. On one maintainer machine (11,454 Claude Code session files, 77 Codex sessions) it reported that summing every usage line would overstate Claude Code output tokens 4.19x and Codex output 1.09x.

Secret check after every Claude Code turn (Stop hook)

Install once: npm install -g usagebench.

Add to ~/.claude/settings.json (merge into an existing "hooks" key if you have one; Stop takes no matcher):

{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "usagebench audit --latest --quiet", "timeout": 60 }
        ]
      }
    ]
  }
}

audit --latest --quiet reads only the most recently modified session file. It prints nothing when that file is clean; otherwise it exits 1 with one masked line per secret type (counts only, no values or paths), which Claude Code shows as a non-blocking hook error. It never rewrites anything; run usagebench audit --fix yourself to redact. Install once with npm install -g usagebench; the hook then runs offline and starts fast.

Tool compatibility

tool version result note
ccusage 20.1.2 10/10
tokscale 4.24.0 10/10
splitrail 3.13.1 edge case found in 3.13.1; fix proposed in Piebald-AI/splitrail#314 (in review)

10 Claude Code and Codex fixture files, 2 of them synthetic; the claude-code#95555 case is one case made of two files (.original + .continued), each with its own .expected.json. The tool results above cover all of them. agy is not compared because none of these tools reads its log format. Full numbers: reports/tool-comparison.md.

Upstream issues & PRs

Badge for trackers

A tracker that passes every fixture can show it:

[![usagebench](https://img.shields.io/badge/usagebench-10%2F10%20fixtures-brightgreen)](https://github.com/logwright/usagebench/blob/HEAD/reports/tool-comparison.md)

usagebench

Quick start

npx usagebench --help
npx usagebench doctor                 # naive vs deduplicated totals on your logs
npx usagebench audit                  # plaintext secrets in your logs, masked (exit 1 if any)
npx usagebench audit --fix            # dry run; add --yes to redact (backup: <file>.usagebench.bak)
npx usagebench audit --latest --quiet  # newest session file only, silent when clean (Stop hook)
npx usagebench repro --latest --agent claude   # repro.jsonl + expected.json + issue.md
npx usagebench compare                # ccusage and tokscale vs the bundled fixtures (scorecard)
npx usagebench diff --ccusage "npx -y ccusage@latest"   # a tracker vs usagebench on your last 7 days
npx usagebench codex path/to/rollout-....jsonl         # totals for one file

Every command above was run from the packed tarball in an empty folder before release (compare and diff fetch the trackers through npx; usagebench itself does not go online). audit --fix skips files modified in the last 10 minutes (a session may still be writing them) and re-scans each file after redacting; JSON lines stay valid.

Use the fixtures in your tracker's CI (no Node needed)

Each release (from 0.2.0) has fixtures.tar.gz: fixtures/ plus manifest.json (path, agent, version, sha256 and expected totals for every fixture).

curl -sL https://github.com/logwright/usagebench/releases/latest/download/fixtures.tar.gz | tar xz

GitHub Actions:

  usagebench:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: curl -sL https://github.com/logwright/usagebench/releases/latest/download/fixtures.tar.gz | tar xz -C /tmp
      - run: |   # place each fixture where your tool looks, run it, compare with manifest.json
          jq -c '.fixtures[] | select(.agent != "agy")' /tmp/manifest.json | while read -r f; do
            echo "$f" | jq -r '.path, .expected'   # replace with: run your tracker on /tmp/<path>, compare
          done

Watch for log-format changes

FORMAT_CHANGES.md lists what changed per agent version. Watch this repo (Watch → Custom → Releases) to get notified when a new entry or fixture lands.

Contributing a fixture

npx usagebench repro --session <id> --agent claude --out my-repro   # anonymized; exit 3 if a secret would survive
python tools/make_fixture.py claude <session.jsonl> fixtures/claude/<version>_<feature>.jsonl   # from a clone

Details in CONTRIBUTING.md. Pull requests that add fixtures run the schema check, the leak scan and the TS vs Python expected-total cross-check; a failure gets one comment saying which file and check failed.

The problem

AI coding agents write session logs as JSONL, and those logs hold token usage. Adding up every usage number you find gives the wrong answer, and the error is large:

  • Claude Code writes one line per content block (thinking, text, tool call) of a single API response, and copies the same usage object onto each line. Summing every line overstated output tokens 4.19x and cache reads 4.24x in a full usagebench doctor run over 11,454 session files (an earlier 30-file sample, used to write the dedup rules, gave 2.04x and 1.71x). The fix is to keep one line per (sessionId, message.id).
  • Codex has two usage streams. token_usage_record holds per-response usage, but compacted records carry a copy of the latest one, so counting both double counts. The older token_count events carry a cumulative total_token_usage plus a per-response last_token_usage, and about a third of them are re-emitted with an unchanged total; adding last_token_usage each time overcounts.
  • Antigravity CLI (agy, Gemini family) writes per-call tokens on PLANNER_RESPONSE steps. It has no session id, message id, version, cache-write or reasoning counts in the log.

Details and the measurements behind each rule are in docs/schema_draft.md. Why two trackers report different totals for the same logs: docs/why-usage-trackers-disagree.md. How Claude Code records tokens (repeated usage blocks, cache pricing, zeroed rows, transcript retention): docs/claude-code-token-accounting.md.

What this repo provides

  • docs/schema_draft.md: a draft normalized event schema (usagebench/0), one record per billable model response, with a field mapping for each agent and the dedup rules.
  • fixtures/: small anonymized real logs, each with an .expected.json holding naive and deduplicated totals (format: docs/expected.schema.json).
  • tools/make_fixture.py: turns a real log into an anonymized fixture and computes its expected totals. It refuses (exit 3, no output) when an id field or a kept value holds a key, a path or an e-mail address.
  • tools/check_leaks.py: scans fixtures for user names, paths, e-mail addresses, URLs, API keys (Anthropic, OpenAI, GitHub, AWS, Google, Slack), private keys, sentences and native ids. CI fails on any hit.
  • tools/compare_tools.py: runs ccusage, tokscale and splitrail on every fixture in a throwaway home and writes reports/tool-comparison.md.
  • tools/build_fixtures.py: rebuilds every fixture from pinned source paths and checks they come out byte-identical.
  • parser/: a reference TypeScript parser with no runtime dependencies.

Fixture format

A fixture is the first 200 lines of a real session log, anonymized: keys, record order, value types, numbers, booleans, type enums, model names and version strings are kept; ids become consistent fake ids (id_fake000001, msg_fake000002, ...); timestamps are shifted so the first one is 2026-01-01T00:00:00Z; every other string becomes <redacted>.

Next to each name.jsonl sits name.expected.json:

{
 "agent": "claude",
 "usage_lines": 120,
 "unique_messages": 61,
 "rule": "claude_last_per_message_id",
 "naive": {"input": 0, "output": 0, "cache_write": 0, "cache_read": 0, "reasoning": 0},
 "dedup": {"input": 0, "output": 0, "cache_write": 0, "cache_read": 0, "reasoning": 0}
}

naive is what summing every usage line gives; dedup is the correct total. Codex fixtures also have compacted_copies, token_count_events, token_count_naive and token_count_dedup. Fixture files are named <cli version>_<feature>.jsonl; agy logs have no version, so its fixture is transcript_basic.jsonl.

fixture what it pins
claude/2.1.334_main content blocks of one response repeat the same usage (dedup by message.id)
claude/2.1.335_sidechain subagent file, isSidechain: true on every line
claude/2.1.335_stream-abort-tool-error a response interrupted mid-stream (stop_reason null, partial usage) followed by a tool error
claude/2.1.321_compaction-zeroed-usage.{original,continued} two-file case: the continued session repeats a response of the original with all four top-level usage counters 0 (real numbers only in usage.cache_creation / usage.iterations[0], claude-code#95555); together they count the original once
claude/synthetic_duplicate-id-partial-usage synthetic: first line of a message has a partial usage snapshot, the last one the final usage
codex/0.160.0_compacted compacted copies of usage records; token_count events re-emitted with an unchanged total
codex/0.171.0-alpha.13.2_subagent-forked forked subagent: the parent's session_meta repeated on line 2 must not replace the file's own
codex/0.173.0-alpha.4.1_basic plain session with token_usage_record and token_count
codex/synthetic_total-reset synthetic: re-emitted event, info: null, and a cumulative total that goes down
agy/transcript_basic antigravity-cli PLANNER_RESPONSE steps

synthetic_* fixtures are hand-written because the case was not found in real logs; their .expected.json says "synthetic": true. Everything else is cut from a real log.

Using the fixtures in another tool's CI

Each fixture is a self-contained log. Copy it where your tool looks (for example $CLAUDE_CONFIG_DIR/projects/x/<sessionId>.jsonl or $CODEX_HOME/sessions/2026/01/01/rollout-...jsonl), run your tool, and compare with dedup (Claude) or token_count_dedup (Codex, if you read token_count events). tools/compare_tools.py does exactly this for ccusage, tokscale and splitrail.

Usage

From npm (the package is usagebench, the command is usagebench):

npx usagebench claude path/to/session.jsonl
npx usagebench codex path/to/rollout-....jsonl
npm install usagebench   # then: import { parse, usage } from "usagebench"

From a clone, Node 23.6 or newer runs the TypeScript source directly (built-in type stripping):

cd parser
node src/cli.ts claude path/to/session.jsonl
node src/cli.ts codex path/to/rollout-....jsonl
node src/cli.ts agy path/to/transcript.jsonl
npm test   # runs the parser on every fixture and compares with .expected.json

CI (.github/workflows/ci.yml) runs the build, npm test, tools/check_leaks.py fixtures, tools/test_tools.py (fault injection for the scanner and the anonymizer) and tools/verify_independent.py.

From code:

import { parse, usage } from "./parser/src/index.ts";
const records = parse("claude", text, { sourceFile: "session.jsonl" });
usage("claude", records, { dedup: true });   // {input, output, cache_write, cache_read, reasoning}
usage("codex", records, { dedup: true, source: "token_count" });   // Codex fallback path

npm test writes parser/e2e_result.json with the result for each fixture.

Known gaps

  • Codex tokens.input is the raw input_tokens, which already includes cache_read (ccusage, tokscale and splitrail all treat it that way; issue #1). Uncached input = input - cache_read.
  • agy: whether input_tokens includes cache_read_tokens is unknown; the session id must be passed in (it comes from the brain/<id> folder name).
  • Fixtures cut at 200 lines can end on a token_usage_record whose matching token_count event was cut off, so dedup and token_count_dedup differ slightly in codex/0.160.0_compacted.

License

MIT, see LICENSE.

About

Conformance fixtures, log-format-change radar and secret audit for AI coding agent usage trackers (Claude Code, Codex, Antigravity CLI).

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages