usagebench 0.2.3 → 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 CHANGED
@@ -35,6 +35,30 @@ Log directories are found automatically on Windows, macOS and Linux (`~/.claude/
35
35
  Output is counts and ratios only. On one maintainer machine (11,454 Claude Code session files, 77 Codex sessions)
36
36
  it reported that summing every usage line would overstate Claude Code output tokens 4.19x and Codex output 1.09x.
37
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
+
38
62
  ## Tool compatibility
39
63
 
40
64
  | tool | version | result | note |
@@ -72,6 +96,7 @@ npx usagebench --help
72
96
  npx usagebench doctor # naive vs deduplicated totals on your logs
73
97
  npx usagebench audit # plaintext secrets in your logs, masked (exit 1 if any)
74
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)
75
100
  npx usagebench repro --latest --agent claude # repro.jsonl + expected.json + issue.md
76
101
  npx usagebench compare # ccusage and tokscale vs the bundled fixtures (scorecard)
77
102
  npx usagebench diff --ccusage "npx -y ccusage@latest" # a tracker vs usagebench on your last 7 days
package/dist/audit.js CHANGED
@@ -1,4 +1,4 @@
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.
@@ -65,8 +65,18 @@ function redactLine(line, hits) {
65
65
  }
66
66
  export function audit(args) {
67
67
  const fix = args.includes("--fix"), yes = args.includes("--yes");
68
- const files = LOG_AGENTS.flatMap((a) => logFiles(a).map((f) => ({ ...f, agent: a })));
69
- console.log("usagebench audit: read-only scan" + (fix ? (yes ? " + redaction (--fix --yes)" : " (--fix dry run: nothing is written)") : "")
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)") : "")
70
80
  + `; ${files.length} log files`);
71
81
  const byType = new Map();
72
82
  let placeholders = 0, skipped = 0, findings = 0, n = 0, fixed = 0, failed = 0;
@@ -90,19 +100,19 @@ export function audit(args) {
90
100
  count++;
91
101
  findings++;
92
102
  byType.set(h.type, (byType.get(h.type) ?? 0) + 1);
93
- console.log(` ${f.agent}:${f.rel}:${ln} ${h.type} ${h.preview}`);
103
+ log(` ${f.agent}:${f.rel}:${ln} ${h.type} ${h.preview}`);
94
104
  }
95
105
  if (!fix)
96
106
  continue;
97
107
  // this file now, before the next one is read
98
108
  const tag = `${f.rel}: ${count} secret(s)`;
99
109
  if (Date.now() - f.mtimeMs < ACTIVE_MS) {
100
- console.log(` skip (modified < 10 min ago, session may be active) ${tag}`);
110
+ log(` skip (modified < 10 min ago, session may be active) ${tag}`);
101
111
  continue;
102
112
  }
103
113
  const bak = f.path + ".usagebench.bak", tmp = f.path + ".usagebench.tmp";
104
114
  if (existsSync(bak)) {
105
- console.log(` skip (backup already exists) ${tag}`);
115
+ log(` skip (backup already exists) ${tag}`);
106
116
  failed++;
107
117
  continue;
108
118
  }
@@ -126,7 +136,7 @@ export function audit(args) {
126
136
  if (fd !== null)
127
137
  closeSync(fd);
128
138
  rmSync(tmp, { force: true });
129
- console.log(` failed ${tag}: ${e.message.split("\n")[0]}`);
139
+ log(` failed ${tag}: ${e.message.split("\n")[0]}`);
130
140
  failed++;
131
141
  continue;
132
142
  }
@@ -134,12 +144,12 @@ export function audit(args) {
134
144
  closeSync(fd);
135
145
  if (broken) {
136
146
  rmSync(tmp, { force: true });
137
- console.log(` skip (redaction would break JSON) ${tag}`);
147
+ log(` skip (redaction would break JSON) ${tag}`);
138
148
  failed++;
139
149
  continue;
140
150
  }
141
151
  if (!yes) {
142
- console.log(` would redact ${tag}`);
152
+ log(` would redact ${tag}`);
143
153
  continue;
144
154
  }
145
155
  try {
@@ -148,7 +158,7 @@ export function audit(args) {
148
158
  }
149
159
  catch (e) {
150
160
  rmSync(tmp, { force: true });
151
- console.log(` failed ${tag}: ${e.message.split("\n")[0]}`);
161
+ log(` failed ${tag}: ${e.message.split("\n")[0]}`);
152
162
  failed++;
153
163
  continue;
154
164
  }
@@ -156,18 +166,21 @@ export function audit(args) {
156
166
  if (again) {
157
167
  copyFileSync(bak, f.path);
158
168
  rmSync(bak, { force: true });
159
- console.log(` restored original, re-scan still found secrets on ${again} line(s) ${tag}`);
169
+ log(` restored original, re-scan still found secrets on ${again} line(s) ${tag}`);
160
170
  failed++;
161
171
  continue;
162
172
  }
163
173
  fixed++;
164
- console.log(` redacted ${tag} (original kept at ${f.rel}.usagebench.bak; delete it once checked)`);
174
+ log(` redacted ${tag} (original kept at ${f.rel}.usagebench.bak; delete it once checked)`);
165
175
  }
166
176
  prog.done();
167
- console.log(`\nfindings: ${findings}` + (findings ? ` (${[...byType].map(([t, c]) => `${t} ${c}`).join(", ")})` : "")
177
+ log(`\nfindings: ${findings}` + (findings ? ` (${[...byType].map(([t, c]) => `${t} ${c}`).join(", ")})` : "")
168
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)`);
169
182
  if (!fix || !findings)
170
183
  return findings ? 1 : 0;
171
- console.log(yes ? `redacted files: ${fixed}, failed or skipped: ${failed}` : "dry run: rerun with --fix --yes to redact");
184
+ log(yes ? `redacted files: ${fixed}, failed or skipped: ${failed}` : "dry run: rerun with --fix --yes to redact");
172
185
  return 1;
173
186
  }
package/dist/cli.js CHANGED
@@ -16,6 +16,8 @@ usage:
16
16
  usagebench --version | -v package version
17
17
  usagebench doctor how much a naive tracker would overcount on your logs
18
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)
19
21
  usagebench repro [--latest|--session <id>] [--agent claude|codex] [--tracker <name>] [--out <dir>] [--max-kb 50]
20
22
  anonymized minimal repro + expected.json + issue.md
21
23
  usagebench diff [--days 7] installed trackers vs usagebench on a temp copy of your recent logs
package/dist/doctor.js CHANGED
@@ -17,6 +17,8 @@ function scanAgent(agent, files, tick) {
17
17
  const s = { files: 0, skipped: 0, bad: 0, naive: zero(), dedup: zero(), extra: {} };
18
18
  const claudeLast = new Map();
19
19
  let usageLines = 0, repeated = 0, zeroedCopies = 0, compactedSessions = 0, tcEvents = 0, tcReemit = 0, sessions = 0;
20
+ let sideRows = 0, sideFiles = 0;
21
+ const serverToolMsgs = new Set();
20
22
  const tc = { naive: zero(), dedup: zero() };
21
23
  for (const f of files) {
22
24
  tick();
@@ -29,6 +31,22 @@ function scanAgent(agent, files, tick) {
29
31
  const { records, bad } = parseLenient(agent, text);
30
32
  s.bad += bad;
31
33
  if (agent === "claude") {
34
+ // compact JSON as Claude Code writes it; inside a string these would be escaped (\"), so text never matches
35
+ const side = text.split('"isSidechain":true').length - 1;
36
+ sideRows += side;
37
+ if (side || f.rel.includes("/subagents/"))
38
+ sideFiles++;
39
+ if (text.includes('"type":"server_tool_use"') || text.includes('"type":"web_search_tool_result"'))
40
+ for (const l of text.split("\n")) {
41
+ if (!/"type":"(?:server_tool_use|web_search_tool_result)"/.test(l))
42
+ continue;
43
+ try {
44
+ const o = JSON.parse(l), c = o?.message?.content;
45
+ if (o?.type === "assistant" && Array.isArray(c) && c.some((b) => b?.type === "server_tool_use" || b?.type === "web_search_tool_result"))
46
+ serverToolMsgs.add(String(o.message.id ?? o.uuid));
47
+ }
48
+ catch { /* counted as invalid elsewhere */ }
49
+ }
32
50
  for (const r of records) {
33
51
  const k = JSON.stringify([r.session_id, r.message_id]);
34
52
  usageLines++;
@@ -60,7 +78,7 @@ function scanAgent(agent, files, tick) {
60
78
  for (const r of claudeLast.values())
61
79
  for (const x of F)
62
80
  s.dedup[x] += r.tokens[x] ?? 0;
63
- s.extra = { usageLines, repeated, zeroedCopies };
81
+ s.extra = { usageLines, repeated, zeroedCopies, sideRows, sideFiles, serverToolMsgs: serverToolMsgs.size };
64
82
  }
65
83
  else {
66
84
  s.extra = { sessions, compactedSessions, tcEvents, tcReemit };
@@ -114,6 +132,9 @@ export function doctor() {
114
132
  + `cache_read ${fmt(s.naive.cache_read)} vs ${fmt(s.dedup.cache_read)} (${ratio(s.naive.cache_read, s.dedup.cache_read)})`);
115
133
  out.push(` rows with all 4 top-level usage counters 0 but usage.cache_creation or usage.iterations[0] non-zero: `
116
134
  + `${fmt(s.extra.zeroedCopies)} (see anthropics/claude-code#95555)`);
135
+ out.push(` sidechain (subagent) rows: ${fmt(s.extra.sideRows)}; files with isSidechain rows or under subagents/: ${fmt(s.extra.sideFiles)}`);
136
+ out.push(` assistant messages with server tool blocks (server_tool_use / web_search_tool_result): ${fmt(s.extra.serverToolMsgs)}`
137
+ + (s.extra.serverToolMsgs ? "; on the Claude API web searches are billed per search, outside the token fields (usage.server_tool_use.web_search_requests)" : ""));
117
138
  out.push(...retention(all.claude));
118
139
  if (s.dedup.output)
119
140
  verdict.push(`Claude Code output by ${ratio(s.naive.output, s.dedup.output)}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "usagebench",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "license": "MIT",
5
5
  "description": "Conformance fixtures, log-format-change radar, doctor and secret audit for AI coding agent usage logs (Claude Code, Codex, antigravity-cli)",
6
6
  "keywords": [