usagebench 0.2.0 → 0.2.3

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.
Files changed (32) hide show
  1. package/README.md +20 -5
  2. package/dist/anon.js +3 -2
  3. package/dist/audit.js +110 -64
  4. package/dist/cli.js +22 -4
  5. package/dist/compare.d.ts +2 -2
  6. package/dist/compare.js +19 -8
  7. package/dist/diff.js +9 -3
  8. package/dist/doctor.js +33 -4
  9. package/dist/index.d.ts +2 -0
  10. package/dist/index.js +17 -7
  11. package/dist/logs.js +20 -3
  12. package/dist/repro.js +6 -1
  13. package/dist/secrets.js +2 -2
  14. package/fixtures/claude/2.1.321_compaction-zeroed-usage.continued.expected.json +21 -0
  15. package/fixtures/claude/2.1.321_compaction-zeroed-usage.continued.jsonl +3 -0
  16. package/fixtures/claude/2.1.321_compaction-zeroed-usage.original.expected.json +21 -0
  17. package/fixtures/claude/2.1.321_compaction-zeroed-usage.original.jsonl +2 -0
  18. package/fixtures/claude/2.1.334_main.expected.json +21 -21
  19. package/fixtures/claude/2.1.334_main.jsonl +162 -162
  20. package/fixtures/claude/2.1.335_sidechain.expected.json +21 -21
  21. package/fixtures/claude/2.1.335_sidechain.jsonl +60 -60
  22. package/fixtures/claude/2.1.335_stream-abort-tool-error.expected.json +21 -21
  23. package/fixtures/claude/2.1.335_stream-abort-tool-error.jsonl +200 -200
  24. package/fixtures/claude/synthetic_duplicate-id-partial-usage.expected.json +22 -22
  25. package/fixtures/codex/0.160.0_compacted.expected.json +38 -38
  26. package/fixtures/codex/0.160.0_compacted.jsonl +200 -200
  27. package/fixtures/codex/0.171.0-alpha.13.2_subagent-forked.expected.json +38 -38
  28. package/fixtures/codex/0.171.0-alpha.13.2_subagent-forked.jsonl +154 -154
  29. package/fixtures/codex/0.173.0-alpha.4.1_basic.expected.json +38 -38
  30. package/fixtures/codex/0.173.0-alpha.4.1_basic.jsonl +200 -200
  31. package/fixtures/codex/synthetic_total-reset.expected.json +39 -39
  32. package/package.json +16 -2
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # usagebench
2
2
 
3
+ Token-usage conformance tests for AI coding agent logs (Claude Code, Codex, Antigravity CLI).
4
+
3
5
  Stop guessing when AI coding agents break your token parser.
4
6
 
5
7
  usagebench is a test oracle for usage trackers that read Claude Code, Codex and antigravity-cli session logs:
@@ -41,15 +43,24 @@ it reported that summing every usage line would overstate Claude Code output tok
41
43
  | tokscale | 4.24.0 | 8/8 | |
42
44
  | splitrail | 3.13.1 | | edge case found in 3.13.1; fix proposed in [Piebald-AI/splitrail#314](https://github.com/Piebald-AI/splitrail/pull/314) (in review) |
43
45
 
44
- 8 Claude Code and Codex fixtures, 2 of them synthetic; agy is not compared because none of these tools reads its
45
- log format. Full numbers: [reports/tool-comparison.md](reports/tool-comparison.md).
46
+ 10 Claude Code and Codex fixture files, 2 of them synthetic; the claude-code#95555 case is one case made of two files
47
+ (`.original` + `.continued`), each with its own `.expected.json`. The tool results above cover the 8 fixtures that
48
+ predate that case. agy is not compared because none of these tools reads its log format. Full numbers: [reports/tool-comparison.md](reports/tool-comparison.md).
49
+
50
+ ### Upstream issues & PRs
51
+
52
+ - [anthropics/claude-code#95555](https://github.com/anthropics/claude-code/issues/95555): zeroed usage on compaction copies, reproduced on 2.1.321 and pinned as a fixture (open)
53
+ - [Piebald-AI/splitrail#314](https://github.com/Piebald-AI/splitrail/pull/314): Codex re-emitted `token_count` events (open)
54
+ - [Piebald-AI/splitrail#313](https://github.com/Piebald-AI/splitrail/pull/313): `cleanupPeriodDays` warning (open)
55
+ - [phuryn/claude-usage#191](https://github.com/phuryn/claude-usage/pull/191): retired Opus 4 / 4.1 pricing (open)
56
+ - [kenn-io/agentsview#3666](https://github.com/kenn-io/agentsview/pull/3666): Antigravity CLI headless nudge (open)
46
57
 
47
58
  ### Badge for trackers
48
59
 
49
60
  A tracker that passes every fixture can show it:
50
61
 
51
62
  ```md
52
- [![usagebench](https://img.shields.io/badge/usagebench-8%2F8%20fixtures-brightgreen)](https://github.com/logwright/usagebench/blob/master/reports/tool-comparison.md)
63
+ [![usagebench](https://img.shields.io/badge/usagebench-8%2F8%20fixtures-brightgreen)](https://github.com/logwright/usagebench/blob/HEAD/reports/tool-comparison.md)
53
64
  ```
54
65
 
55
66
  [![usagebench](https://img.shields.io/badge/usagebench-8%2F8%20fixtures-brightgreen)](reports/tool-comparison.md)
@@ -116,8 +127,9 @@ AI coding agents write session logs as JSONL, and those logs hold token usage. A
116
127
  number you find gives the wrong answer, and the error is large:
117
128
 
118
129
  - **Claude Code** writes one line per content block (thinking, text, tool call) of a single API response,
119
- and copies the same `usage` object onto each line. Summing every line overstated output tokens about
120
- 2x (2.04x) and cache reads 1.71x on the logs we measured. The fix is to keep one line per
130
+ and copies the same `usage` object onto each line. Summing every line overstated output tokens 4.19x
131
+ and cache reads 4.24x in a full `usagebench doctor` run over 11,454 session files (an earlier 30-file sample,
132
+ used to write the dedup rules, gave 2.04x and 1.71x). The fix is to keep one line per
121
133
  `(sessionId, message.id)`.
122
134
  - **Codex** has two usage streams. `token_usage_record` holds per-response usage, but `compacted`
123
135
  records carry a copy of the latest one, so counting both double counts. The older `token_count` events
@@ -127,6 +139,8 @@ number you find gives the wrong answer, and the error is large:
127
139
  session id, message id, version, cache-write or reasoning counts in the log.
128
140
 
129
141
  Details and the measurements behind each rule are in [docs/schema_draft.md](docs/schema_draft.md).
142
+ Why two trackers report different totals for the same logs: [docs/why-usage-trackers-disagree.md](docs/why-usage-trackers-disagree.md).
143
+ How Claude Code records tokens (repeated usage blocks, cache pricing, zeroed rows, transcript retention): [docs/claude-code-token-accounting.md](docs/claude-code-token-accounting.md).
130
144
 
131
145
  ## What this repo provides
132
146
 
@@ -172,6 +186,7 @@ named `<cli version>_<feature>.jsonl`; agy logs have no version, so its fixture
172
186
  | `claude/2.1.334_main` | content blocks of one response repeat the same `usage` (dedup by `message.id`) |
173
187
  | `claude/2.1.335_sidechain` | subagent file, `isSidechain: true` on every line |
174
188
  | `claude/2.1.335_stream-abort-tool-error` | a response interrupted mid-stream (`stop_reason` null, partial usage) followed by a tool error |
189
+ | `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 |
175
190
  | `claude/synthetic_duplicate-id-partial-usage` | synthetic: first line of a message has a partial usage snapshot, the last one the final usage |
176
191
  | `codex/0.160.0_compacted` | `compacted` copies of usage records; `token_count` events re-emitted with an unchanged total |
177
192
  | `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 |
package/dist/anon.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // TypeScript port of tools/make_fixture.py: the same anonymization rules and the same expected-totals file,
2
2
  // so `usagebench repro` output can go straight into fixtures/. Keep both in step.
3
3
  import { sensitive } from "./secrets.js";
4
- import { parse, report } from "./index.js";
4
+ import { parse, report, zeroedTop } from "./index.js";
5
5
  const ENUM_KEYS = new Set(["type", "subtype", "role", "stop_reason", "model", "requestedModel", "advisorModel",
6
6
  "version", "cli_version", "source", "originator", "model_provider", "service_tier", "userType", "level", "status",
7
7
  "plan_type", "speed", "inference_geo", "reasoning_effort", "effort", "approval_policy"]);
@@ -83,7 +83,8 @@ export function expectedFor(agent, text) {
83
83
  const r = report(agent, text);
84
84
  const res = { agent };
85
85
  if (agent === "claude") {
86
- const keys = new Set(recs.map((x) => JSON.stringify([x.session_id, x.message_id])));
86
+ // zeroed copies (claude-code#95555) bill nothing and are not counted as messages (as in make_fixture.py)
87
+ const keys = new Set(recs.filter((x) => !zeroedTop(x.tokens)).map((x) => JSON.stringify([x.session_id, x.message_id])));
87
88
  Object.assign(res, { usage_lines: recs.length, unique_messages: keys.size, rule: "claude_last_per_message_id",
88
89
  is_sidechain: recs.length > 0 && recs.every((x) => x.is_sidechain) });
89
90
  }
package/dist/audit.js CHANGED
@@ -2,42 +2,64 @@
2
2
  // Prints type, file (relative to the log root), line and a masked preview (first 4 chars + length), never a value.
3
3
  // Without --fix nothing is written. --fix is a dry run unless --yes is given; with --yes each affected file is
4
4
  // copied to <file>.usagebench.bak, rewritten through a temp file + rename, and re-scanned.
5
- import { copyFileSync, existsSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
- import { logFiles, progress, readText, LOG_AGENTS } from "./logs.js";
5
+ // Files are handled one at a time and read line by line (no size cap, no whole-file text kept in memory).
6
+ import { closeSync, copyFileSync, existsSync, openSync, readSync, renameSync, rmSync, writeSync } from "node:fs";
7
+ import { StringDecoder } from "node:string_decoder";
8
+ import { logFiles, progress, LOG_AGENTS } from "./logs.js";
7
9
  import { findSecrets } from "./secrets.js";
8
10
  const ACTIVE_MS = 10 * 60 * 1000; // a file written in the last 10 minutes may belong to a running session
9
- function lineStarts(text) {
10
- const s = [0];
11
- for (let i = text.indexOf("\n"); i !== -1; i = text.indexOf("\n", i + 1))
12
- s.push(i + 1);
13
- return s;
11
+ // Lines of a file without the "\n" ("\r" stays on the line); `last` is true for a final line with no "\n".
12
+ function* lines(path) {
13
+ const fd = openSync(path, "r"), buf = Buffer.alloc(4 << 20), dec = new StringDecoder("utf8");
14
+ let rest = "";
15
+ try {
16
+ for (let n; (n = readSync(fd, buf, 0, buf.length, null)) > 0;) {
17
+ const parts = (rest + dec.write(buf.subarray(0, n))).split("\n");
18
+ rest = parts.pop();
19
+ for (const p of parts)
20
+ yield { text: p, last: false };
21
+ }
22
+ }
23
+ finally {
24
+ closeSync(fd);
25
+ }
26
+ rest += dec.end();
27
+ if (rest)
28
+ yield { text: rest, last: true };
14
29
  }
15
- function lineOf(starts, index) {
16
- let lo = 0, hi = starts.length - 1;
17
- while (lo < hi) {
18
- const mid = (lo + hi + 1) >> 1;
19
- if (starts[mid] <= index)
20
- lo = mid;
21
- else
22
- hi = mid - 1;
30
+ // Hits per line number (1-based); only lines with a real (non-placeholder) secret are kept.
31
+ function scan(path) {
32
+ const hits = new Map();
33
+ let placeholders = 0, ln = 0;
34
+ for (const { text } of lines(path)) {
35
+ ln++;
36
+ const all = findSecrets(text), real = all.filter((h) => !h.placeholder);
37
+ placeholders += all.length - real.length;
38
+ if (real.length)
39
+ hits.set(ln, real);
23
40
  }
24
- return lo + 1;
41
+ return { hits, placeholders };
25
42
  }
26
- // Replace each hit with [REDACTED:<type>]; returns null if any touched line would stop being valid JSON.
27
- function redact(text, hits) {
28
- let out = text;
29
- for (const h of [...hits].sort((a, b) => b.index - a.index))
30
- out = out.slice(0, h.index) + `[REDACTED:${h.type}]` + out.slice(h.index + h.length);
31
- const before = new Set(text.split("\n"));
32
- for (const l of out.split("\n")) {
33
- if (!l.trim() || before.has(l))
34
- continue;
35
- try {
36
- JSON.parse(l);
37
- }
38
- catch {
39
- return null;
43
+ // Replace each hit with [REDACTED:<type>], widened so it never cuts a JSON escape (\" \\ \n \uXXXX) in half;
44
+ // returns null if the line would stop being valid JSON.
45
+ function redactLine(line, hits) {
46
+ const esc = [...line.matchAll(/\\(?:u[0-9a-fA-F]{4}|[^])/g)].map((m) => [m.index, m.index + m[0].length]);
47
+ let out = line;
48
+ for (const h of [...hits].sort((a, b) => b.index - a.index)) {
49
+ let s = h.index, e = h.index + h.length;
50
+ for (const [a, b] of esc) {
51
+ if (a < s && s < b)
52
+ s = a;
53
+ if (a < e && e < b)
54
+ e = b;
40
55
  }
56
+ out = out.slice(0, s) + `[REDACTED:${h.type}]` + out.slice(e);
57
+ }
58
+ try {
59
+ JSON.parse(out);
60
+ }
61
+ catch {
62
+ return null;
41
63
  }
42
64
  return out;
43
65
  }
@@ -47,50 +69,71 @@ export function audit(args) {
47
69
  console.log("usagebench audit: read-only scan" + (fix ? (yes ? " + redaction (--fix --yes)" : " (--fix dry run: nothing is written)") : "")
48
70
  + `; ${files.length} log files`);
49
71
  const byType = new Map();
50
- let placeholders = 0, skipped = 0, findings = 0, n = 0;
51
- const fixPlan = [];
72
+ let placeholders = 0, skipped = 0, findings = 0, n = 0, fixed = 0, failed = 0;
52
73
  const prog = progress(files.length);
53
74
  for (const f of files) {
54
75
  prog.tick(++n);
55
- const text = readText(f);
56
- if (text === null) {
76
+ let r;
77
+ try {
78
+ r = scan(f.path);
79
+ }
80
+ catch {
57
81
  skipped++;
58
82
  continue;
59
83
  }
60
- const all = findSecrets(text);
61
- const hits = all.filter((h) => !h.placeholder);
62
- placeholders += all.length - hits.length;
63
- if (!hits.length)
84
+ placeholders += r.placeholders;
85
+ if (!r.hits.size)
64
86
  continue;
65
- const starts = lineStarts(text);
66
- for (const h of hits) {
67
- findings++;
68
- byType.set(h.type, (byType.get(h.type) ?? 0) + 1);
69
- console.log(` ${f.agent}:${f.rel}:${lineOf(starts, h.index)} ${h.type} ${h.preview}`);
70
- }
71
- if (fix)
72
- fixPlan.push({ f, text, hits });
73
- }
74
- prog.done();
75
- console.log(`\nfindings: ${findings}` + (findings ? ` (${[...byType].map(([t, c]) => `${t} ${c}`).join(", ")})` : "")
76
- + `; ignored as example/placeholder values: ${placeholders}` + (skipped ? `; files skipped (unreadable or > size cap): ${skipped}` : ""));
77
- if (!fix || !findings)
78
- return findings ? 1 : 0;
79
- let fixed = 0, failed = 0;
80
- for (const { f, text, hits } of fixPlan) {
81
- const tag = `${f.rel}: ${hits.length} secret(s)`;
87
+ let count = 0;
88
+ for (const [ln, hs] of r.hits)
89
+ for (const h of hs) {
90
+ count++;
91
+ findings++;
92
+ byType.set(h.type, (byType.get(h.type) ?? 0) + 1);
93
+ console.log(` ${f.agent}:${f.rel}:${ln} ${h.type} ${h.preview}`);
94
+ }
95
+ if (!fix)
96
+ continue;
97
+ // this file now, before the next one is read
98
+ const tag = `${f.rel}: ${count} secret(s)`;
82
99
  if (Date.now() - f.mtimeMs < ACTIVE_MS) {
83
100
  console.log(` skip (modified < 10 min ago, session may be active) ${tag}`);
84
101
  continue;
85
102
  }
86
- const bak = f.path + ".usagebench.bak";
103
+ const bak = f.path + ".usagebench.bak", tmp = f.path + ".usagebench.tmp";
87
104
  if (existsSync(bak)) {
88
105
  console.log(` skip (backup already exists) ${tag}`);
89
106
  failed++;
90
107
  continue;
91
108
  }
92
- const out = redact(text, hits);
93
- if (out === null) {
109
+ let broken = false, fd = null;
110
+ try {
111
+ if (yes)
112
+ fd = openSync(tmp, "w");
113
+ let ln = 0;
114
+ for (const { text, last } of lines(f.path)) {
115
+ const hs = r.hits.get(++ln);
116
+ const out = hs ? redactLine(text, hs) : text;
117
+ if (out === null) {
118
+ broken = true;
119
+ break;
120
+ }
121
+ if (fd !== null)
122
+ writeSync(fd, last ? out : out + "\n");
123
+ }
124
+ }
125
+ catch (e) {
126
+ if (fd !== null)
127
+ closeSync(fd);
128
+ rmSync(tmp, { force: true });
129
+ console.log(` failed ${tag}: ${e.message.split("\n")[0]}`);
130
+ failed++;
131
+ continue;
132
+ }
133
+ if (fd !== null)
134
+ closeSync(fd);
135
+ if (broken) {
136
+ rmSync(tmp, { force: true });
94
137
  console.log(` skip (redaction would break JSON) ${tag}`);
95
138
  failed++;
96
139
  continue;
@@ -99,10 +142,8 @@ export function audit(args) {
99
142
  console.log(` would redact ${tag}`);
100
143
  continue;
101
144
  }
102
- const tmp = f.path + ".usagebench.tmp";
103
145
  try {
104
146
  copyFileSync(f.path, bak);
105
- writeFileSync(tmp, out, "utf8");
106
147
  renameSync(tmp, f.path);
107
148
  }
108
149
  catch (e) {
@@ -111,17 +152,22 @@ export function audit(args) {
111
152
  failed++;
112
153
  continue;
113
154
  }
114
- const again = findSecrets(readText({ ...f, size: 0 }) ?? "").filter((h) => !h.placeholder);
115
- if (again.length) {
155
+ const again = scan(f.path).hits.size;
156
+ if (again) {
116
157
  copyFileSync(bak, f.path);
117
158
  rmSync(bak, { force: true });
118
- console.log(` restored original, re-scan still found ${again.length} ${tag}`);
159
+ console.log(` restored original, re-scan still found secrets on ${again} line(s) ${tag}`);
119
160
  failed++;
120
161
  continue;
121
162
  }
122
163
  fixed++;
123
164
  console.log(` redacted ${tag} (original kept at ${f.rel}.usagebench.bak; delete it once checked)`);
124
165
  }
125
- console.log(yes ? `\nredacted files: ${fixed}, failed or skipped: ${failed}` : "\ndry run: rerun with --fix --yes to redact");
166
+ prog.done();
167
+ console.log(`\nfindings: ${findings}` + (findings ? ` (${[...byType].map(([t, c]) => `${t} ${c}`).join(", ")})` : "")
168
+ + `; ignored as example/placeholder values: ${placeholders}` + (skipped ? `; files skipped (unreadable): ${skipped}` : ""));
169
+ if (!fix || !findings)
170
+ return findings ? 1 : 0;
171
+ console.log(yes ? `redacted files: ${fixed}, failed or skipped: ${failed}` : "dry run: rerun with --fix --yes to redact");
126
172
  return 1;
127
173
  }
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { readFileSync } from "node:fs";
3
3
  import { basename } from "node:path";
4
- import { report, usage } from "./index.js";
4
+ import { report, usage, zeroedTop } from "./index.js";
5
5
  import { compare } from "./compare.js";
6
6
  import { doctor } from "./doctor.js";
7
7
  import { audit } from "./audit.js";
@@ -13,6 +13,7 @@ No network code; read-only (only \`audit --fix --yes\` writes, and keeps a backu
13
13
  Log directories are found automatically (~/.claude/projects, ~/.codex/sessions; CLAUDE_CONFIG_DIR / CODEX_HOME override).
14
14
 
15
15
  usage:
16
+ usagebench --version | -v package version
16
17
  usagebench doctor how much a naive tracker would overcount on your logs
17
18
  usagebench audit [--fix [--yes]] plaintext secrets in your logs (masked; --fix redacts, dry run without --yes)
18
19
  usagebench repro [--latest|--session <id>] [--agent claude|codex] [--tracker <name>] [--out <dir>] [--max-kb 50]
@@ -26,10 +27,20 @@ usage:
26
27
  compare, diff and repro --tracker run the trackers you have (ccusage, tokscale, splitrail); they may go online.`;
27
28
  const [cmd, ...rest] = process.argv.slice(2);
28
29
  const commands = { compare, doctor: () => doctor(), audit, repro, diff };
30
+ // `--version` / `-v` anywhere: the package version (package.json sits one level above both src/ and dist/).
31
+ if ([cmd, ...rest].some((a) => a === "--version" || a === "-v")) {
32
+ console.log(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
33
+ process.exit(0);
34
+ }
29
35
  if (!cmd || cmd === "--help" || cmd === "-h" || cmd === "help") {
30
36
  console.log(HELP);
31
37
  process.exit(cmd ? 0 : 2);
32
38
  }
39
+ // `<cmd> --help` / `-h` prints help before any command code runs (no log scan, no file access).
40
+ if (rest.includes("--help") || rest.includes("-h")) {
41
+ console.log(HELP);
42
+ process.exit(0);
43
+ }
33
44
  if (commands[cmd])
34
45
  process.exit(commands[cmd](rest));
35
46
  const file = rest[0];
@@ -39,7 +50,9 @@ try {
39
50
  }
40
51
  else if (cmd === "claude" || cmd === "codex") {
41
52
  // All local logs of this agent; per file for Codex, (sessionId, message.id) across files for Claude.
42
- const agent = cmd, all = [];
53
+ // Claude: running naive sum + last non-zeroed tokens per key (same result as usage(), without keeping every record)
54
+ const agent = cmd, last = new Map();
55
+ const cNaive = { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 };
43
56
  const sum = (ts) => ts.reduce((a, t) => { for (const k of Object.keys(a))
44
57
  a[k] += t[k]; return a; }, { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 });
45
58
  const naive = [], dedup = [], tcn = [], tcd = [];
@@ -51,7 +64,12 @@ try {
51
64
  files++;
52
65
  const { records } = parseLenient(agent, text);
53
66
  if (agent === "claude")
54
- all.push(...records);
67
+ for (const r of records) {
68
+ for (const k of Object.keys(cNaive))
69
+ cNaive[k] += r.tokens[k] ?? 0;
70
+ if (!zeroedTop(r.tokens))
71
+ last.set(JSON.stringify([r.session_id, r.message_id]), { ...r.tokens });
72
+ }
55
73
  else {
56
74
  naive.push(usage(agent, records, { dedup: false }));
57
75
  dedup.push(usage(agent, records));
@@ -61,7 +79,7 @@ try {
61
79
  }
62
80
  const res = { agent, files };
63
81
  if (agent === "claude")
64
- Object.assign(res, { naive: usage(agent, all, { dedup: false }), dedup: usage(agent, all) });
82
+ Object.assign(res, { naive: cNaive, dedup: sum([...last.values()]) });
65
83
  else
66
84
  Object.assign(res, { naive: sum(naive), dedup: sum(dedup), token_count_naive: sum(tcn), token_count_dedup: sum(tcd) });
67
85
  console.log(JSON.stringify(res, null, 1));
package/dist/compare.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  export type Totals = Record<string, number | null | undefined>;
2
- export declare function place(agent: string, fixture: string, home: string): void;
2
+ export declare function place(agent: string, fixture: string, home: string, n?: number): void;
3
3
  export declare const ccusage: (cmd: string) => (agent: string, env: NodeJS.ProcessEnv) => Totals;
4
4
  export declare const tokscale: (cmd: string) => (agent: string, env: NodeJS.ProcessEnv) => Totals;
5
5
  export declare const splitrail: (bin: string) => (agent: string, env: NodeJS.ProcessEnv) => Totals;
6
6
  export declare function version(cmd: string): string;
7
7
  export declare function expectedInToolTerms(agent: string, exp: any): Totals;
8
8
  export declare function homeEnv(home: string): NodeJS.ProcessEnv;
9
- export declare function delta(got: Totals, e: Totals): string;
9
+ export declare function delta(got: Totals | null | undefined, e: Totals): string;
10
10
  export declare function onPath(name: string): string | null;
11
11
  export type Tracker = {
12
12
  fn: (a: string, env: NodeJS.ProcessEnv) => Totals;
package/dist/compare.js CHANGED
@@ -28,15 +28,15 @@ function runJson(cmd, env) {
28
28
  const out = run(cmd, env, env.HOME); // cwd = throwaway home: tokscale writes .tokscale/ into it
29
29
  return JSON.parse(out.slice(out.indexOf("{"))); // ccusage/tokscale may print a notice first
30
30
  }
31
- export function place(agent, fixture, home) {
31
+ export function place(agent, fixture, home, n = 0) {
32
32
  let dst;
33
33
  if (agent === "claude") {
34
34
  const lines = readFileSync(fixture, "utf8").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
35
35
  const sid = lines.find((o) => o.sessionId)?.sessionId ?? "session";
36
- dst = join(home, ".claude", "projects", "fixture", `${sid}.jsonl`);
36
+ dst = join(home, ".claude", "projects", "fixture", `${sid}${n ? "-" + n : ""}.jsonl`);
37
37
  }
38
38
  else {
39
- dst = join(home, ".codex", "sessions", "2026", "01", "01", "rollout-2026-01-01T00-00-00-0199a000-0000-7000-8000-000000000001.jsonl");
39
+ dst = join(home, ".codex", "sessions", "2026", "01", "01", `rollout-2026-01-01T00-00-00-0199a000-0000-7000-8000-00000000000${n + 1}.jsonl`);
40
40
  }
41
41
  mkdirSync(dirname(dst), { recursive: true });
42
42
  copyFileSync(fixture, dst);
@@ -89,7 +89,8 @@ export function expectedInToolTerms(agent, exp) {
89
89
  // Environment that points every tracker at a throwaway home holding only the logs placed there.
90
90
  export function homeEnv(home) {
91
91
  const env = { ...process.env, HOME: home, USERPROFILE: home,
92
- CLAUDE_CONFIG_DIR: join(home, ".claude"), CODEX_HOME: join(home, ".codex") };
92
+ CLAUDE_CONFIG_DIR: join(home, ".claude"), CODEX_HOME: join(home, ".codex"),
93
+ XDG_CONFIG_HOME: join(home, ".config"), XDG_CACHE_HOME: join(home, ".cache"), XDG_DATA_HOME: join(home, ".local", "share") };
93
94
  // keep npx's cache where it was (on Linux/macOS it lives under HOME)
94
95
  if (process.platform !== "win32" && !env.npm_config_cache)
95
96
  env.npm_config_cache = join(homedir(), ".npm");
@@ -97,6 +98,9 @@ export function homeEnv(home) {
97
98
  }
98
99
  // "match", or "diff <field> +n, ..." (tool minus expected).
99
100
  export function delta(got, e) {
101
+ // empty/undefined totals (tracker printed nothing usable) are a mismatch, never a crash or a silent match
102
+ if (!got || typeof got !== "object" || F.every((k) => k === "reasoning" || got[k] == null))
103
+ return "diff: no totals reported";
100
104
  const diff = F.filter((k) => got[k] != null && got[k] !== e[k]);
101
105
  // A tool that does not report reasoning (null/0 while expected > 0) is not a diff.
102
106
  const real = diff.filter((k) => !(k === "reasoning" && !got[k]));
@@ -152,13 +156,20 @@ export function compare(args) {
152
156
  const dir = join(fx, agent);
153
157
  if (!existsSync(dir))
154
158
  continue;
159
+ // `<case>.original.*` + `<case>.continued.*` are one case: both logs go into one home, expected = their sum
160
+ const cases = new Map();
155
161
  for (const f of readdirSync(dir).filter((n) => n.endsWith(".expected.json")).sort()) {
156
- const exp = JSON.parse(readFileSync(join(dir, f), "utf8"));
157
- const stem = f.replace(/\.expected\.json$/, "");
162
+ const stem = f.replace(/\.expected\.json$/, ""), key = stem.replace(/\.(original|continued)$/, "");
163
+ cases.set(key, [...(cases.get(key) ?? []), stem]);
164
+ }
165
+ for (const [stem, members] of cases) {
158
166
  const home = join(tmp, stem, "home");
159
- place(agent, join(dir, `${stem}.jsonl`), home);
167
+ const exps = members.map((m, i) => {
168
+ place(agent, join(dir, `${m}.jsonl`), home, i);
169
+ return expectedInToolTerms(agent, JSON.parse(readFileSync(join(dir, `${m}.expected.json`), "utf8")));
170
+ });
160
171
  const env = homeEnv(home);
161
- const e = expectedInToolTerms(agent, exp);
172
+ const e = Object.fromEntries(F.map((k) => [k, exps.reduce((s, x) => s + (x[k] ?? 0), 0)]));
162
173
  for (const [tool, { fn }] of Object.entries(tools)) {
163
174
  score[tool].n++;
164
175
  let result;
package/dist/diff.js CHANGED
@@ -5,12 +5,16 @@ import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import { logFiles, parseLenient, readText, MAX_FILE_BYTES, LOG_AGENTS } from "./logs.js";
8
- import { usage } from "./index.js";
8
+ import { usage, zeroedTop } from "./index.js";
9
9
  import { delta, expectedInToolTerms, homeEnv, installedTrackers } from "./compare.js";
10
10
  const F = ["input", "output", "cache_write", "cache_read", "reasoning"];
11
11
  export function diff(args) {
12
12
  const opt = (k) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
13
13
  const days = Number(opt("--days") ?? 7);
14
+ if (!Number.isFinite(days) || days < 0) {
15
+ console.error("--days must be a number >= 0 (0 = any time)");
16
+ return 2;
17
+ }
14
18
  const since = days > 0 ? Date.now() - days * 86400_000 : 0;
15
19
  const tools = installedTrackers(args);
16
20
  if (!Object.keys(tools).length) {
@@ -41,9 +45,11 @@ export function diff(args) {
41
45
  bytes += f.size;
42
46
  used++;
43
47
  const { records } = parseLenient(agent, text);
44
- if (agent === "claude")
48
+ if (agent === "claude") {
45
49
  for (const r of records)
46
- last.set(JSON.stringify([r.session_id, r.message_id]), r);
50
+ if (!zeroedTop(r.tokens))
51
+ last.set(JSON.stringify([r.session_id, r.message_id]), r);
52
+ }
47
53
  else {
48
54
  const t = usage("codex", records, { dedup: true, source: "token_count" });
49
55
  for (const k of F)
package/dist/doctor.js CHANGED
@@ -1,8 +1,10 @@
1
1
  // `usagebench doctor`: how much would a naive tracker overcount on this machine's own logs?
2
2
  // Read-only, offline. Prints counts and ratios only: no log content, no paths below the log root.
3
+ import { existsSync, readFileSync } from "node:fs";
3
4
  import { homedir } from "node:os";
5
+ import { join } from "node:path";
4
6
  import { logFiles, logRoots, parseLenient, progress, readText } from "./logs.js";
5
- import { usage } from "./index.js";
7
+ import { usage, zeroedTop } from "./index.js";
6
8
  const F = ["input", "output", "cache_write", "cache_read", "reasoning"];
7
9
  const zero = () => ({ input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 });
8
10
  const add = (a, b) => { for (const k of F)
@@ -14,7 +16,7 @@ const fmt = (n) => n.toLocaleString("en-US");
14
16
  function scanAgent(agent, files, tick) {
15
17
  const s = { files: 0, skipped: 0, bad: 0, naive: zero(), dedup: zero(), extra: {} };
16
18
  const claudeLast = new Map();
17
- let usageLines = 0, repeated = 0, compactedSessions = 0, tcEvents = 0, tcReemit = 0, sessions = 0;
19
+ let usageLines = 0, repeated = 0, zeroedCopies = 0, compactedSessions = 0, tcEvents = 0, tcReemit = 0, sessions = 0;
18
20
  const tc = { naive: zero(), dedup: zero() };
19
21
  for (const f of files) {
20
22
  tick();
@@ -32,7 +34,10 @@ function scanAgent(agent, files, tick) {
32
34
  usageLines++;
33
35
  if (claudeLast.has(k))
34
36
  repeated++;
35
- claudeLast.set(k, r);
37
+ if (r.zeroed_copy)
38
+ zeroedCopies++;
39
+ if (!zeroedTop(r.tokens))
40
+ claudeLast.set(k, r);
36
41
  for (const x of F)
37
42
  s.naive[x] += r.tokens[x] ?? 0;
38
43
  }
@@ -55,7 +60,7 @@ function scanAgent(agent, files, tick) {
55
60
  for (const r of claudeLast.values())
56
61
  for (const x of F)
57
62
  s.dedup[x] += r.tokens[x] ?? 0;
58
- s.extra = { usageLines, repeated };
63
+ s.extra = { usageLines, repeated, zeroedCopies };
59
64
  }
60
65
  else {
61
66
  s.extra = { sessions, compactedSessions, tcEvents, tcReemit };
@@ -63,6 +68,27 @@ function scanAgent(agent, files, tick) {
63
68
  }
64
69
  return s;
65
70
  }
71
+ // Claude Code deletes transcripts older than cleanupPeriodDays (default 30, by file mtime, silently) and rejects 0
72
+ // (code.claude.com/docs/en/settings-reference#cleanupperioddays). settings.json is only read.
73
+ function retention(files) {
74
+ const dirs = process.env.CLAUDE_CONFIG_DIR?.split(",").map((d) => d.trim()).filter(Boolean);
75
+ const vals = (dirs?.length ? dirs : [join(homedir(), ".claude")]).map((d) => join(d, "settings.json")).filter((p) => existsSync(p))
76
+ .map((p) => { try {
77
+ return JSON.parse(readFileSync(p, "utf8"))?.cleanupPeriodDays;
78
+ }
79
+ catch {
80
+ return undefined;
81
+ } });
82
+ if (vals.includes(0))
83
+ return [" WARNING: settings.json sets cleanupPeriodDays to 0. Current Claude Code rejects 0 (minimum 1); "
84
+ + "older versions stopped writing transcripts at all with it (anthropics/claude-code#23710)."];
85
+ if (vals.some((v) => v !== undefined))
86
+ return [];
87
+ const old = files.filter((f) => Date.now() - f.mtimeMs >= 25 * 86400_000).length;
88
+ return old ? [` NOTE: cleanupPeriodDays is not set (default 30): ${fmt(old)} transcript file(s) last modified 25+ days ago; `
89
+ + "Claude Code deletes them without a message once they pass 30 days (anthropics/claude-code#62250). "
90
+ + "Set a larger cleanupPeriodDays in settings.json to keep them."] : [];
91
+ }
66
92
  export function doctor() {
67
93
  const out = ["usagebench doctor: read-only, offline; counts and ratios only"];
68
94
  const all = { claude: logFiles("claude"), codex: logFiles("codex") };
@@ -86,6 +112,9 @@ export function doctor() {
86
112
  out.push(` usage lines: ${fmt(usageLines)}; repeating an earlier (sessionId, message.id): ${fmt(repeated)} (${pct(repeated, usageLines)})`);
87
113
  out.push(` naive vs dedup: output ${fmt(s.naive.output)} vs ${fmt(s.dedup.output)} (${ratio(s.naive.output, s.dedup.output)}), `
88
114
  + `cache_read ${fmt(s.naive.cache_read)} vs ${fmt(s.dedup.cache_read)} (${ratio(s.naive.cache_read, s.dedup.cache_read)})`);
115
+ out.push(` rows with all 4 top-level usage counters 0 but usage.cache_creation or usage.iterations[0] non-zero: `
116
+ + `${fmt(s.extra.zeroedCopies)} (see anthropics/claude-code#95555)`);
117
+ out.push(...retention(all.claude));
89
118
  if (s.dedup.output)
90
119
  verdict.push(`Claude Code output by ${ratio(s.naive.output, s.dedup.output)}`);
91
120
  }
package/dist/index.d.ts CHANGED
@@ -23,6 +23,7 @@ export interface UsageRecord {
23
23
  source_line: number;
24
24
  raw_type: string;
25
25
  total_changed?: boolean;
26
+ zeroed_copy?: boolean;
26
27
  }
27
28
  export interface Totals {
28
29
  input: number;
@@ -39,6 +40,7 @@ export interface UsageOptions {
39
40
  dedup?: boolean;
40
41
  source?: "record" | "token_count";
41
42
  }
43
+ export declare const zeroedTop: (t: Tokens) => boolean;
42
44
  export declare function agentName(name: string): Agent;
43
45
  export declare function parse(agentIn: string, jsonlText: string, opts?: ParseOptions): UsageRecord[];
44
46
  export declare function usage(agentIn: string, records: UsageRecord[], opts?: UsageOptions): Totals;