usagebench 0.2.0 → 0.2.4
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.
- package/README.md +45 -5
- package/dist/anon.js +3 -2
- package/dist/audit.js +132 -73
- package/dist/cli.js +24 -4
- package/dist/compare.d.ts +2 -2
- package/dist/compare.js +19 -8
- package/dist/diff.js +9 -3
- package/dist/doctor.js +54 -4
- package/dist/index.d.ts +2 -0
- package/dist/index.js +17 -7
- package/dist/logs.js +20 -3
- package/dist/repro.js +6 -1
- package/dist/secrets.js +2 -2
- package/fixtures/claude/2.1.321_compaction-zeroed-usage.continued.expected.json +21 -0
- package/fixtures/claude/2.1.321_compaction-zeroed-usage.continued.jsonl +3 -0
- package/fixtures/claude/2.1.321_compaction-zeroed-usage.original.expected.json +21 -0
- package/fixtures/claude/2.1.321_compaction-zeroed-usage.original.jsonl +2 -0
- package/fixtures/claude/2.1.334_main.expected.json +21 -21
- package/fixtures/claude/2.1.334_main.jsonl +162 -162
- package/fixtures/claude/2.1.335_sidechain.expected.json +21 -21
- package/fixtures/claude/2.1.335_sidechain.jsonl +60 -60
- package/fixtures/claude/2.1.335_stream-abort-tool-error.expected.json +21 -21
- package/fixtures/claude/2.1.335_stream-abort-tool-error.jsonl +200 -200
- package/fixtures/claude/synthetic_duplicate-id-partial-usage.expected.json +22 -22
- package/fixtures/codex/0.160.0_compacted.expected.json +38 -38
- package/fixtures/codex/0.160.0_compacted.jsonl +200 -200
- package/fixtures/codex/0.171.0-alpha.13.2_subagent-forked.expected.json +38 -38
- package/fixtures/codex/0.171.0-alpha.13.2_subagent-forked.jsonl +154 -154
- package/fixtures/codex/0.173.0-alpha.4.1_basic.expected.json +38 -38
- package/fixtures/codex/0.173.0-alpha.4.1_basic.jsonl +200 -200
- package/fixtures/codex/synthetic_total-reset.expected.json +39 -39
- 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:
|
|
@@ -33,6 +35,30 @@ Log directories are found automatically on Windows, macOS and Linux (`~/.claude/
|
|
|
33
35
|
Output is counts and ratios only. On one maintainer machine (11,454 Claude Code session files, 77 Codex sessions)
|
|
34
36
|
it reported that summing every usage line would overstate Claude Code output tokens 4.19x and Codex output 1.09x.
|
|
35
37
|
|
|
38
|
+
## Secret check after every Claude Code turn (Stop hook)
|
|
39
|
+
|
|
40
|
+
Add to `~/.claude/settings.json` (merge into an existing `"hooks"` key if you have one; `Stop` takes no matcher):
|
|
41
|
+
|
|
42
|
+
```json
|
|
43
|
+
{
|
|
44
|
+
"hooks": {
|
|
45
|
+
"Stop": [
|
|
46
|
+
{
|
|
47
|
+
"hooks": [
|
|
48
|
+
{ "type": "command", "command": "npx --yes usagebench@latest audit --latest --quiet", "timeout": 60 }
|
|
49
|
+
]
|
|
50
|
+
}
|
|
51
|
+
]
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`audit --latest --quiet` reads only the most recently modified session file. It prints nothing when that file is
|
|
57
|
+
clean; otherwise it exits 1 with one masked line per secret type (counts only, no values or paths), which Claude Code
|
|
58
|
+
shows as a non-blocking hook error. It never rewrites anything; run `usagebench audit --fix` yourself to redact.
|
|
59
|
+
The first `npx` run needs network to download the package. With `npm install -g usagebench`, use
|
|
60
|
+
`"command": "usagebench audit --latest --quiet"` instead (offline, faster).
|
|
61
|
+
|
|
36
62
|
## Tool compatibility
|
|
37
63
|
|
|
38
64
|
| tool | version | result | note |
|
|
@@ -41,15 +67,24 @@ it reported that summing every usage line would overstate Claude Code output tok
|
|
|
41
67
|
| tokscale | 4.24.0 | 8/8 | |
|
|
42
68
|
| 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
69
|
|
|
44
|
-
|
|
45
|
-
|
|
70
|
+
10 Claude Code and Codex fixture files, 2 of them synthetic; the claude-code#95555 case is one case made of two files
|
|
71
|
+
(`.original` + `.continued`), each with its own `.expected.json`. The tool results above cover the 8 fixtures that
|
|
72
|
+
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).
|
|
73
|
+
|
|
74
|
+
### Upstream issues & PRs
|
|
75
|
+
|
|
76
|
+
- [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)
|
|
77
|
+
- [Piebald-AI/splitrail#314](https://github.com/Piebald-AI/splitrail/pull/314): Codex re-emitted `token_count` events (open)
|
|
78
|
+
- [Piebald-AI/splitrail#313](https://github.com/Piebald-AI/splitrail/pull/313): `cleanupPeriodDays` warning (open)
|
|
79
|
+
- [phuryn/claude-usage#191](https://github.com/phuryn/claude-usage/pull/191): retired Opus 4 / 4.1 pricing (open)
|
|
80
|
+
- [kenn-io/agentsview#3666](https://github.com/kenn-io/agentsview/pull/3666): Antigravity CLI headless nudge (open)
|
|
46
81
|
|
|
47
82
|
### Badge for trackers
|
|
48
83
|
|
|
49
84
|
A tracker that passes every fixture can show it:
|
|
50
85
|
|
|
51
86
|
```md
|
|
52
|
-
[](https://github.com/logwright/usagebench/blob/
|
|
87
|
+
[](https://github.com/logwright/usagebench/blob/HEAD/reports/tool-comparison.md)
|
|
53
88
|
```
|
|
54
89
|
|
|
55
90
|
[](reports/tool-comparison.md)
|
|
@@ -61,6 +96,7 @@ npx usagebench --help
|
|
|
61
96
|
npx usagebench doctor # naive vs deduplicated totals on your logs
|
|
62
97
|
npx usagebench audit # plaintext secrets in your logs, masked (exit 1 if any)
|
|
63
98
|
npx usagebench audit --fix # dry run; add --yes to redact (backup: <file>.usagebench.bak)
|
|
99
|
+
npx usagebench audit --latest --quiet # newest session file only, silent when clean (Stop hook)
|
|
64
100
|
npx usagebench repro --latest --agent claude # repro.jsonl + expected.json + issue.md
|
|
65
101
|
npx usagebench compare # ccusage and tokscale vs the bundled fixtures (scorecard)
|
|
66
102
|
npx usagebench diff --ccusage "npx -y ccusage@latest" # a tracker vs usagebench on your last 7 days
|
|
@@ -116,8 +152,9 @@ AI coding agents write session logs as JSONL, and those logs hold token usage. A
|
|
|
116
152
|
number you find gives the wrong answer, and the error is large:
|
|
117
153
|
|
|
118
154
|
- **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
|
|
120
|
-
|
|
155
|
+
and copies the same `usage` object onto each line. Summing every line overstated output tokens 4.19x
|
|
156
|
+
and cache reads 4.24x in a full `usagebench doctor` run over 11,454 session files (an earlier 30-file sample,
|
|
157
|
+
used to write the dedup rules, gave 2.04x and 1.71x). The fix is to keep one line per
|
|
121
158
|
`(sessionId, message.id)`.
|
|
122
159
|
- **Codex** has two usage streams. `token_usage_record` holds per-response usage, but `compacted`
|
|
123
160
|
records carry a copy of the latest one, so counting both double counts. The older `token_count` events
|
|
@@ -127,6 +164,8 @@ number you find gives the wrong answer, and the error is large:
|
|
|
127
164
|
session id, message id, version, cache-write or reasoning counts in the log.
|
|
128
165
|
|
|
129
166
|
Details and the measurements behind each rule are in [docs/schema_draft.md](docs/schema_draft.md).
|
|
167
|
+
Why two trackers report different totals for the same logs: [docs/why-usage-trackers-disagree.md](docs/why-usage-trackers-disagree.md).
|
|
168
|
+
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
169
|
|
|
131
170
|
## What this repo provides
|
|
132
171
|
|
|
@@ -172,6 +211,7 @@ named `<cli version>_<feature>.jsonl`; agy logs have no version, so its fixture
|
|
|
172
211
|
| `claude/2.1.334_main` | content blocks of one response repeat the same `usage` (dedup by `message.id`) |
|
|
173
212
|
| `claude/2.1.335_sidechain` | subagent file, `isSidechain: true` on every line |
|
|
174
213
|
| `claude/2.1.335_stream-abort-tool-error` | a response interrupted mid-stream (`stop_reason` null, partial usage) followed by a tool error |
|
|
214
|
+
| `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
215
|
| `claude/synthetic_duplicate-id-partial-usage` | synthetic: first line of a message has a partial usage snapshot, the last one the final usage |
|
|
176
216
|
| `codex/0.160.0_compacted` | `compacted` copies of usage records; `token_count` events re-emitted with an unchanged total |
|
|
177
217
|
| `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
|
-
|
|
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
|
@@ -1,127 +1,186 @@
|
|
|
1
|
-
// `usagebench audit [--fix [--yes]]`: look for plaintext secrets in the local agent logs.
|
|
1
|
+
// `usagebench audit [--latest] [--quiet] [--fix [--yes]]`: look for plaintext secrets in the local agent logs.
|
|
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
|
-
|
|
6
|
-
import {
|
|
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
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
|
41
|
+
return { hits, placeholders };
|
|
25
42
|
}
|
|
26
|
-
// Replace each hit with [REDACTED:<type>]
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
const
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
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
|
}
|
|
44
66
|
export function audit(args) {
|
|
45
67
|
const fix = args.includes("--fix"), yes = args.includes("--yes");
|
|
46
|
-
const
|
|
47
|
-
|
|
68
|
+
const latest = args.includes("--latest"), quiet = args.includes("--quiet");
|
|
69
|
+
if (latest && fix) {
|
|
70
|
+
console.error("usagebench audit: --latest is read-only; run audit --fix without --latest to redact");
|
|
71
|
+
return 2;
|
|
72
|
+
}
|
|
73
|
+
let files = LOG_AGENTS.flatMap((a) => logFiles(a).map((f) => ({ ...f, agent: a })));
|
|
74
|
+
// --latest: only the most recently modified session file of either agent (e.g. from a Claude Code Stop hook)
|
|
75
|
+
if (latest)
|
|
76
|
+
files = files.reduce((b, f) => (!b.length || f.mtimeMs > b[0].mtimeMs ? [f] : b), []);
|
|
77
|
+
// --quiet: nothing on stdout; on findings one stderr line per type (counts only, no path, no preview)
|
|
78
|
+
const log = quiet ? (_) => { } : (s) => console.log(s);
|
|
79
|
+
log("usagebench audit: read-only scan" + (fix ? (yes ? " + redaction (--fix --yes)" : " (--fix dry run: nothing is written)") : "")
|
|
48
80
|
+ `; ${files.length} log files`);
|
|
49
81
|
const byType = new Map();
|
|
50
|
-
let placeholders = 0, skipped = 0, findings = 0, n = 0;
|
|
51
|
-
const fixPlan = [];
|
|
82
|
+
let placeholders = 0, skipped = 0, findings = 0, n = 0, fixed = 0, failed = 0;
|
|
52
83
|
const prog = progress(files.length);
|
|
53
84
|
for (const f of files) {
|
|
54
85
|
prog.tick(++n);
|
|
55
|
-
|
|
56
|
-
|
|
86
|
+
let r;
|
|
87
|
+
try {
|
|
88
|
+
r = scan(f.path);
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
57
91
|
skipped++;
|
|
58
92
|
continue;
|
|
59
93
|
}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
placeholders += all.length - hits.length;
|
|
63
|
-
if (!hits.length)
|
|
94
|
+
placeholders += r.placeholders;
|
|
95
|
+
if (!r.hits.size)
|
|
64
96
|
continue;
|
|
65
|
-
|
|
66
|
-
for (const
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
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)`;
|
|
97
|
+
let count = 0;
|
|
98
|
+
for (const [ln, hs] of r.hits)
|
|
99
|
+
for (const h of hs) {
|
|
100
|
+
count++;
|
|
101
|
+
findings++;
|
|
102
|
+
byType.set(h.type, (byType.get(h.type) ?? 0) + 1);
|
|
103
|
+
log(` ${f.agent}:${f.rel}:${ln} ${h.type} ${h.preview}`);
|
|
104
|
+
}
|
|
105
|
+
if (!fix)
|
|
106
|
+
continue;
|
|
107
|
+
// this file now, before the next one is read
|
|
108
|
+
const tag = `${f.rel}: ${count} secret(s)`;
|
|
82
109
|
if (Date.now() - f.mtimeMs < ACTIVE_MS) {
|
|
83
|
-
|
|
110
|
+
log(` skip (modified < 10 min ago, session may be active) ${tag}`);
|
|
84
111
|
continue;
|
|
85
112
|
}
|
|
86
|
-
const bak = f.path + ".usagebench.bak";
|
|
113
|
+
const bak = f.path + ".usagebench.bak", tmp = f.path + ".usagebench.tmp";
|
|
87
114
|
if (existsSync(bak)) {
|
|
88
|
-
|
|
115
|
+
log(` skip (backup already exists) ${tag}`);
|
|
89
116
|
failed++;
|
|
90
117
|
continue;
|
|
91
118
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
119
|
+
let broken = false, fd = null;
|
|
120
|
+
try {
|
|
121
|
+
if (yes)
|
|
122
|
+
fd = openSync(tmp, "w");
|
|
123
|
+
let ln = 0;
|
|
124
|
+
for (const { text, last } of lines(f.path)) {
|
|
125
|
+
const hs = r.hits.get(++ln);
|
|
126
|
+
const out = hs ? redactLine(text, hs) : text;
|
|
127
|
+
if (out === null) {
|
|
128
|
+
broken = true;
|
|
129
|
+
break;
|
|
130
|
+
}
|
|
131
|
+
if (fd !== null)
|
|
132
|
+
writeSync(fd, last ? out : out + "\n");
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
catch (e) {
|
|
136
|
+
if (fd !== null)
|
|
137
|
+
closeSync(fd);
|
|
138
|
+
rmSync(tmp, { force: true });
|
|
139
|
+
log(` failed ${tag}: ${e.message.split("\n")[0]}`);
|
|
140
|
+
failed++;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (fd !== null)
|
|
144
|
+
closeSync(fd);
|
|
145
|
+
if (broken) {
|
|
146
|
+
rmSync(tmp, { force: true });
|
|
147
|
+
log(` skip (redaction would break JSON) ${tag}`);
|
|
95
148
|
failed++;
|
|
96
149
|
continue;
|
|
97
150
|
}
|
|
98
151
|
if (!yes) {
|
|
99
|
-
|
|
152
|
+
log(` would redact ${tag}`);
|
|
100
153
|
continue;
|
|
101
154
|
}
|
|
102
|
-
const tmp = f.path + ".usagebench.tmp";
|
|
103
155
|
try {
|
|
104
156
|
copyFileSync(f.path, bak);
|
|
105
|
-
writeFileSync(tmp, out, "utf8");
|
|
106
157
|
renameSync(tmp, f.path);
|
|
107
158
|
}
|
|
108
159
|
catch (e) {
|
|
109
160
|
rmSync(tmp, { force: true });
|
|
110
|
-
|
|
161
|
+
log(` failed ${tag}: ${e.message.split("\n")[0]}`);
|
|
111
162
|
failed++;
|
|
112
163
|
continue;
|
|
113
164
|
}
|
|
114
|
-
const again =
|
|
115
|
-
if (again
|
|
165
|
+
const again = scan(f.path).hits.size;
|
|
166
|
+
if (again) {
|
|
116
167
|
copyFileSync(bak, f.path);
|
|
117
168
|
rmSync(bak, { force: true });
|
|
118
|
-
|
|
169
|
+
log(` restored original, re-scan still found secrets on ${again} line(s) ${tag}`);
|
|
119
170
|
failed++;
|
|
120
171
|
continue;
|
|
121
172
|
}
|
|
122
173
|
fixed++;
|
|
123
|
-
|
|
174
|
+
log(` redacted ${tag} (original kept at ${f.rel}.usagebench.bak; delete it once checked)`);
|
|
124
175
|
}
|
|
125
|
-
|
|
176
|
+
prog.done();
|
|
177
|
+
log(`\nfindings: ${findings}` + (findings ? ` (${[...byType].map(([t, c]) => `${t} ${c}`).join(", ")})` : "")
|
|
178
|
+
+ `; ignored as example/placeholder values: ${placeholders}` + (skipped ? `; files skipped (unreadable): ${skipped}` : ""));
|
|
179
|
+
if (quiet)
|
|
180
|
+
for (const [t, c] of byType)
|
|
181
|
+
console.error(`usagebench audit: ${c} ${t} in ${latest ? `the latest ${files[0].agent} session log` : "your agent logs"} (masked; run "usagebench audit${latest ? " --latest" : ""}" for line numbers)`);
|
|
182
|
+
if (!fix || !findings)
|
|
183
|
+
return findings ? 1 : 0;
|
|
184
|
+
log(yes ? `redacted files: ${fixed}, failed or skipped: ${failed}` : "dry run: rerun with --fix --yes to redact");
|
|
126
185
|
return 1;
|
|
127
186
|
}
|
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,8 +13,11 @@ 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)
|
|
19
|
+
usagebench audit --latest [--quiet] same, only the most recently modified session file (for a Stop hook;
|
|
20
|
+
--quiet: silent when clean, one stderr line per secret type otherwise)
|
|
18
21
|
usagebench repro [--latest|--session <id>] [--agent claude|codex] [--tracker <name>] [--out <dir>] [--max-kb 50]
|
|
19
22
|
anonymized minimal repro + expected.json + issue.md
|
|
20
23
|
usagebench diff [--days 7] installed trackers vs usagebench on a temp copy of your recent logs
|
|
@@ -26,10 +29,20 @@ usage:
|
|
|
26
29
|
compare, diff and repro --tracker run the trackers you have (ccusage, tokscale, splitrail); they may go online.`;
|
|
27
30
|
const [cmd, ...rest] = process.argv.slice(2);
|
|
28
31
|
const commands = { compare, doctor: () => doctor(), audit, repro, diff };
|
|
32
|
+
// `--version` / `-v` anywhere: the package version (package.json sits one level above both src/ and dist/).
|
|
33
|
+
if ([cmd, ...rest].some((a) => a === "--version" || a === "-v")) {
|
|
34
|
+
console.log(JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version);
|
|
35
|
+
process.exit(0);
|
|
36
|
+
}
|
|
29
37
|
if (!cmd || cmd === "--help" || cmd === "-h" || cmd === "help") {
|
|
30
38
|
console.log(HELP);
|
|
31
39
|
process.exit(cmd ? 0 : 2);
|
|
32
40
|
}
|
|
41
|
+
// `<cmd> --help` / `-h` prints help before any command code runs (no log scan, no file access).
|
|
42
|
+
if (rest.includes("--help") || rest.includes("-h")) {
|
|
43
|
+
console.log(HELP);
|
|
44
|
+
process.exit(0);
|
|
45
|
+
}
|
|
33
46
|
if (commands[cmd])
|
|
34
47
|
process.exit(commands[cmd](rest));
|
|
35
48
|
const file = rest[0];
|
|
@@ -39,7 +52,9 @@ try {
|
|
|
39
52
|
}
|
|
40
53
|
else if (cmd === "claude" || cmd === "codex") {
|
|
41
54
|
// All local logs of this agent; per file for Codex, (sessionId, message.id) across files for Claude.
|
|
42
|
-
|
|
55
|
+
// Claude: running naive sum + last non-zeroed tokens per key (same result as usage(), without keeping every record)
|
|
56
|
+
const agent = cmd, last = new Map();
|
|
57
|
+
const cNaive = { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 };
|
|
43
58
|
const sum = (ts) => ts.reduce((a, t) => { for (const k of Object.keys(a))
|
|
44
59
|
a[k] += t[k]; return a; }, { input: 0, output: 0, cache_write: 0, cache_read: 0, reasoning: 0 });
|
|
45
60
|
const naive = [], dedup = [], tcn = [], tcd = [];
|
|
@@ -51,7 +66,12 @@ try {
|
|
|
51
66
|
files++;
|
|
52
67
|
const { records } = parseLenient(agent, text);
|
|
53
68
|
if (agent === "claude")
|
|
54
|
-
|
|
69
|
+
for (const r of records) {
|
|
70
|
+
for (const k of Object.keys(cNaive))
|
|
71
|
+
cNaive[k] += r.tokens[k] ?? 0;
|
|
72
|
+
if (!zeroedTop(r.tokens))
|
|
73
|
+
last.set(JSON.stringify([r.session_id, r.message_id]), { ...r.tokens });
|
|
74
|
+
}
|
|
55
75
|
else {
|
|
56
76
|
naive.push(usage(agent, records, { dedup: false }));
|
|
57
77
|
dedup.push(usage(agent, records));
|
|
@@ -61,7 +81,7 @@ try {
|
|
|
61
81
|
}
|
|
62
82
|
const res = { agent, files };
|
|
63
83
|
if (agent === "claude")
|
|
64
|
-
Object.assign(res, { naive:
|
|
84
|
+
Object.assign(res, { naive: cNaive, dedup: sum([...last.values()]) });
|
|
65
85
|
else
|
|
66
86
|
Object.assign(res, { naive: sum(naive), dedup: sum(dedup), token_count_naive: sum(tcn), token_count_dedup: sum(tcd) });
|
|
67
87
|
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",
|
|
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
|
|
157
|
-
|
|
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
|
-
|
|
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 =
|
|
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
|
-
|
|
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)
|