burnoff 1.3.0 → 1.4.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "burnoff",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code and Google Antigravity.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -0,0 +1,252 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file scripts/bench-hooks.mjs
4
+ * Reproducible cold-spawn latency benchmark for Burnoff CLI hooks (`PreToolUse`, `PostToolUse`, `SessionStart`).
5
+ * Usage:
6
+ * node scripts/bench-hooks.mjs [--runs 7] [--json]
7
+ */
8
+
9
+ import { spawnSync } from 'node:child_process';
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { performance } from 'node:perf_hooks';
14
+ import { fileURLToPath } from 'node:url';
15
+
16
+ const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
17
+ const PROJECT_ROOT = path.resolve(SCRIPT_DIR, '..');
18
+ const PRE_TOOL_HOOK = path.join(PROJECT_ROOT, 'hooks', 'pre-tool-use.mjs');
19
+ const POST_TOOL_HOOK = path.join(PROJECT_ROOT, 'hooks', 'post-tool-use.mjs');
20
+ const SESSION_HOOK = path.join(PROJECT_ROOT, 'hooks', 'session-lifecycle.mjs');
21
+
22
+ /**
23
+ * Computes summary percentile timings from sample durations in milliseconds.
24
+ *
25
+ * @param {number[]} [samples=[]]
26
+ */
27
+ export function summarizeDurationsMs(samples = []) {
28
+ if (!Array.isArray(samples) || samples.length === 0) {
29
+ return { count: 0, minMs: 0, p50Ms: 0, p95Ms: 0, maxMs: 0, meanMs: 0 };
30
+ }
31
+ const sorted = [...samples].sort((a, b) => a - b);
32
+ const pick = (pct) => {
33
+ const idx = Math.min(sorted.length - 1, Math.max(0, Math.ceil((pct / 100) * sorted.length) - 1));
34
+ return Number(sorted[idx].toFixed(2));
35
+ };
36
+ const sum = sorted.reduce((acc, v) => acc + v, 0);
37
+ return {
38
+ count: sorted.length,
39
+ minMs: Number(sorted[0].toFixed(2)),
40
+ p50Ms: pick(50),
41
+ p95Ms: pick(95),
42
+ maxMs: Number(sorted[sorted.length - 1].toFixed(2)),
43
+ meanMs: Number((sum / sorted.length).toFixed(2))
44
+ };
45
+ }
46
+
47
+ function runColdHookSpawn(hookScript, payloadJson, env, cwd) {
48
+ const t0 = performance.now();
49
+ const res = spawnSync(process.execPath, [hookScript], {
50
+ cwd,
51
+ env,
52
+ input: payloadJson,
53
+ encoding: 'utf8',
54
+ windowsHide: true,
55
+ timeout: 15_000
56
+ });
57
+ const elapsedMs = performance.now() - t0;
58
+ if (res.error) {
59
+ throw res.error;
60
+ }
61
+ if (res.status !== 0) {
62
+ throw new Error(
63
+ `Hook ${path.basename(hookScript)} exited with code ${res.status}: ${String(res.stderr || res.stdout || '').trim()}`
64
+ );
65
+ }
66
+ return elapsedMs;
67
+ }
68
+
69
+ /**
70
+ * Runs cold-spawn hook latency benchmarks in an isolated temporary workspace + home directory.
71
+ *
72
+ * @param {{ runs?: number }} [options={}]
73
+ */
74
+ export function runHookBenchmarks(options = {}) {
75
+ const runs = Math.max(1, Math.floor(Number(options.runs) || 7));
76
+ const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'burnoff-bench-'));
77
+ const homeDir = path.join(tmpRoot, 'home');
78
+ const wsDir = path.join(tmpRoot, 'workspace');
79
+ fs.mkdirSync(path.join(wsDir, 'src'), { recursive: true });
80
+ fs.mkdirSync(homeDir, { recursive: true });
81
+
82
+ try {
83
+ const sampleLines = Array.from({ length: 100 }, (_, i) => `export const line_${i} = ${i};`).join('\n');
84
+ fs.writeFileSync(path.join(wsDir, 'src', 'sample.mjs'), `${sampleLines}\n`, 'utf8');
85
+
86
+ const baseEnv = {
87
+ ...process.env,
88
+ HOME: homeDir,
89
+ USERPROFILE: homeDir
90
+ };
91
+ delete baseEnv.BURNOFF_HOME;
92
+ delete baseEnv.BURNOFF_CLIENT;
93
+ delete baseEnv.BURNOFF_INSPECT_READONLY_TOOLS;
94
+
95
+ const agEnv = {
96
+ ...baseEnv,
97
+ BURNOFF_CLIENT: 'antigravity'
98
+ };
99
+
100
+ const scenarios = [
101
+ {
102
+ id: 'pre_claude_bash',
103
+ label: '`PreToolUse` (Claude `Bash`)',
104
+ hook: PRE_TOOL_HOOK,
105
+ env: baseEnv,
106
+ payload: JSON.stringify({
107
+ session_id: 'bench-claude-bash',
108
+ cwd: wsDir,
109
+ tool_name: 'Bash',
110
+ tool_input: { command: 'git status --short' }
111
+ })
112
+ },
113
+ {
114
+ id: 'pre_claude_read_bounded',
115
+ label: '`PreToolUse` (Claude `Read` bounded)',
116
+ hook: PRE_TOOL_HOOK,
117
+ env: baseEnv,
118
+ payload: JSON.stringify({
119
+ session_id: 'bench-claude-read',
120
+ cwd: wsDir,
121
+ tool_name: 'Read',
122
+ tool_input: { file_path: 'src/sample.mjs', offset: 1, limit: 80 }
123
+ })
124
+ },
125
+ {
126
+ id: 'pre_claude_grep_fast',
127
+ label: '`PreToolUse` (Claude `Grep` Tier-1 fast allow)',
128
+ hook: PRE_TOOL_HOOK,
129
+ env: baseEnv,
130
+ payload: JSON.stringify({
131
+ session_id: 'bench-claude-grep',
132
+ cwd: wsDir,
133
+ tool_name: 'Grep',
134
+ tool_input: { pattern: 'line_', path: 'src' }
135
+ })
136
+ },
137
+ {
138
+ id: 'pre_ag_run_command',
139
+ label: '`PreToolUse` (Antigravity `run_command`)',
140
+ hook: PRE_TOOL_HOOK,
141
+ env: agEnv,
142
+ payload: JSON.stringify({
143
+ conversationId: 'bench-ag-cmd',
144
+ workspacePaths: [wsDir],
145
+ toolCall: {
146
+ name: 'run_command',
147
+ args: { CommandLine: 'git status --short', Cwd: wsDir }
148
+ }
149
+ })
150
+ },
151
+ {
152
+ id: 'post_claude_bash',
153
+ label: '`PostToolUse` (Claude `Bash`)',
154
+ hook: POST_TOOL_HOOK,
155
+ env: baseEnv,
156
+ payload: JSON.stringify({
157
+ session_id: 'bench-post-bash',
158
+ cwd: wsDir,
159
+ tool_name: 'Bash',
160
+ tool_input: { command: 'git status --short' },
161
+ tool_response: { stdout: 'M src/sample.mjs\n', stderr: '' }
162
+ })
163
+ },
164
+ {
165
+ id: 'session_start_claude',
166
+ label: '`SessionStart` (Claude)',
167
+ hook: SESSION_HOOK,
168
+ env: baseEnv,
169
+ payload: JSON.stringify({
170
+ hook_event_name: 'SessionStart',
171
+ session_id: 'bench-session-start',
172
+ cwd: wsDir
173
+ })
174
+ }
175
+ ];
176
+
177
+ const results = scenarios.map((scenario) => {
178
+ // 1 untimed warmup spawn per hook scenario to settle filesystem cache
179
+ runColdHookSpawn(scenario.hook, scenario.payload, scenario.env, wsDir);
180
+ const samples = [];
181
+ for (let i = 0; i < runs; i += 1) {
182
+ samples.push(runColdHookSpawn(scenario.hook, scenario.payload, scenario.env, wsDir));
183
+ }
184
+ return {
185
+ id: scenario.id,
186
+ label: scenario.label,
187
+ stats: summarizeDurationsMs(samples)
188
+ };
189
+ });
190
+
191
+ const cpus = os.cpus();
192
+ return {
193
+ runs,
194
+ environment: {
195
+ platform: os.platform(),
196
+ release: os.release(),
197
+ arch: os.arch(),
198
+ nodeVersion: process.version,
199
+ cpuModel: cpus[0]?.model ? String(cpus[0].model).trim() : 'unknown'
200
+ },
201
+ results
202
+ };
203
+ } finally {
204
+ fs.rmSync(tmpRoot, { recursive: true, force: true });
205
+ }
206
+ }
207
+
208
+ export function formatBenchmarkMarkdown(report) {
209
+ const { environment: env, runs, results } = report;
210
+ const lines = [
211
+ `OS: ${env.platform} ${env.release} (${env.arch}) | CPU: ${env.cpuModel} | Node: ${env.nodeVersion} | Runs: ${runs}`,
212
+ '',
213
+ '| Scenario | p50 (ms) | p95 (ms) | min (ms) | max (ms) |',
214
+ '| :--- | :---: | :---: | :---: | :---: |'
215
+ ];
216
+ for (const row of results) {
217
+ lines.push(
218
+ `| ${row.label} | ${row.stats.p50Ms.toFixed(1)} | ${row.stats.p95Ms.toFixed(1)} | ${row.stats.minMs.toFixed(1)} | ${row.stats.maxMs.toFixed(1)} |`
219
+ );
220
+ }
221
+ return lines.join('\n');
222
+ }
223
+
224
+ function parseArgs(argv = process.argv.slice(2)) {
225
+ let runs = 7;
226
+ let json = false;
227
+ for (let i = 0; i < argv.length; i += 1) {
228
+ const arg = argv[i];
229
+ if (arg === '--json') {
230
+ json = true;
231
+ } else if (arg === '--runs' && argv[i + 1]) {
232
+ runs = Math.max(1, Number(argv[++i]) || 7);
233
+ } else if (arg.startsWith('--runs=')) {
234
+ runs = Math.max(1, Number(arg.slice('--runs='.length)) || 7);
235
+ }
236
+ }
237
+ return { runs, json };
238
+ }
239
+
240
+ const isEntry =
241
+ process.argv[1] &&
242
+ path.resolve(fileURLToPath(import.meta.url)) === path.resolve(process.argv[1]);
243
+
244
+ if (isEntry) {
245
+ const args = parseArgs();
246
+ const report = runHookBenchmarks({ runs: args.runs });
247
+ if (args.json) {
248
+ console.log(JSON.stringify(report, null, 2));
249
+ } else {
250
+ console.log(formatBenchmarkMarkdown(report));
251
+ }
252
+ }
@@ -61,6 +61,26 @@ export function renderBurnoffStatusLine(inputJson = {}, options = {}) {
61
61
  parts.push(`sess: ${formatUsd(sessionCost)}`);
62
62
  }
63
63
 
64
+ const telemetryOpt = options.telemetry || payload.telemetry || payload.metrics || {};
65
+ const ttftMs = Number(
66
+ telemetryOpt.medianTtftMs ?? telemetryOpt.ttftMs ?? telemetryOpt.ttft_ms ?? payload.ttft_ms ?? payload.ttftMs
67
+ );
68
+ if (Number.isFinite(ttftMs) && ttftMs > 0) {
69
+ const ttftLabel = ttftMs >= 1000 ? `${(ttftMs / 1000).toFixed(1)}s` : `${Math.round(ttftMs)}ms`;
70
+ parts.push(`ttft: ${ttftLabel}`);
71
+ }
72
+
73
+ const tokensPerSec = Number(
74
+ telemetryOpt.medianTokensPerSec ??
75
+ telemetryOpt.tokensPerSec ??
76
+ telemetryOpt.tokens_per_sec ??
77
+ payload.tokens_per_sec ??
78
+ payload.tokensPerSec
79
+ );
80
+ if (Number.isFinite(tokensPerSec) && tokensPerSec > 0) {
81
+ parts.push(`${tokensPerSec.toFixed(1)} tok/s`);
82
+ }
83
+
64
84
  return parts.join(' | ');
65
85
  }
66
86
 
package/src/cli/audit.mjs CHANGED
@@ -20,6 +20,14 @@ import {
20
20
  import { getSavedQuotaReceiptSummary } from '../storage/ledger.mjs';
21
21
  import { attributeUncachedTokens } from '../config/uncached-attribution.mjs';
22
22
  import { valuateBatch } from '../config/pricing.mjs';
23
+ import {
24
+ discoverAntigravityConversationDbs,
25
+ readAntigravityConversationDbMetrics,
26
+ discoverLocalOtelFiles,
27
+ parseOtelGenAiSpans,
28
+ extractStepTimingMetrics,
29
+ aggregateTelemetryMetrics
30
+ } from '../storage/telemetry-metrics.mjs';
23
31
 
24
32
  function summarizeParsedSession(meta, parsed, options = {}) {
25
33
  const steps = Array.isArray(parsed?.steps) ? parsed.steps : [];
@@ -111,6 +119,8 @@ function summarizeParsedSession(meta, parsed, options = {}) {
111
119
  const uncachedAttribution = attributeUncachedTokens(attributionCalls, {
112
120
  claudeCodeVersion: options.claudeCodeVersion || null
113
121
  });
122
+ const stepTimings = steps.map(extractStepTimingMetrics);
123
+ const sessionTelemetry = aggregateTelemetryMetrics({ stepTimings });
114
124
 
115
125
  return {
116
126
  sessionId,
@@ -134,6 +144,13 @@ function summarizeParsedSession(meta, parsed, options = {}) {
134
144
  : 0,
135
145
  entrypoint,
136
146
  mtimeMs: meta.mtimeMs || 0,
147
+ telemetry: {
148
+ ttftSampleCount: sessionTelemetry.ttftSampleCount,
149
+ tpsSampleCount: sessionTelemetry.tpsSampleCount,
150
+ medianTtftMs: sessionTelemetry.medianTtftMs,
151
+ medianTokensPerSec: sessionTelemetry.medianTokensPerSec
152
+ },
153
+ _stepTimings: stepTimings,
137
154
  attributionCalls,
138
155
  uncachedAttribution
139
156
  };
@@ -148,6 +165,9 @@ export function auditClaudeSessions(options = {}) {
148
165
  : null;
149
166
  const homeDir = explicitHomeDir || getHomeDir();
150
167
  const limit = Math.max(1, Number(options.limit ?? 20));
168
+ const clientOpt = String(options.client || 'auto').trim().toLowerCase();
169
+ const includeAg =
170
+ clientOpt === 'antigravity' || clientOpt === 'ag' || clientOpt === 'both' || clientOpt === 'auto';
151
171
  let candidates;
152
172
  if (options.sessionPath) {
153
173
  const abs = path.resolve(options.sessionPath);
@@ -162,10 +182,7 @@ export function auditClaudeSessions(options = {}) {
162
182
  }
163
183
  ];
164
184
  } else {
165
- const clientOpt = String(options.client || 'auto').trim().toLowerCase();
166
185
  const includeClaude = clientOpt !== 'antigravity' && clientOpt !== 'ag';
167
- const includeAg =
168
- clientOpt === 'antigravity' || clientOpt === 'ag' || clientOpt === 'both' || clientOpt === 'auto';
169
186
  const claudeList = includeClaude ? discoverClaudeCodeSessions(homeDir, options) : [];
170
187
  const agList = includeAg ? discoverAntigravityTranscripts({ homeDir, cwd: options.cwd }) : [];
171
188
  candidates = [...claudeList, ...agList]
@@ -232,11 +249,53 @@ export function auditClaudeSessions(options = {}) {
232
249
  const uncachedAttribution = attributeUncachedTokens(allAttributionCalls, {
233
250
  claudeCodeVersion: options.claudeCodeVersion || null
234
251
  });
235
- const cleanSessions = sessions.map(({ attributionCalls: _calls, ...rest }) => rest);
252
+
253
+ const otelFiles =
254
+ options.otelPath || !options.sessionPath
255
+ ? discoverLocalOtelFiles({ homeDir, otelPath: options.otelPath || null })
256
+ : [];
257
+ const otelSpans = [];
258
+ for (const otelFile of otelFiles) {
259
+ otelSpans.push(...parseOtelGenAiSpans(otelFile).spans);
260
+ }
261
+
262
+ let dbPaths = [];
263
+ if (Array.isArray(options.antigravityDbPath)) {
264
+ dbPaths = options.antigravityDbPath.filter(Boolean);
265
+ } else if (typeof options.antigravityDbPath === 'string' && options.antigravityDbPath.trim()) {
266
+ dbPaths = [options.antigravityDbPath.trim()];
267
+ } else if (options.antigravityDbDir || (includeAg && !options.sessionPath)) {
268
+ dbPaths = discoverAntigravityConversationDbs({
269
+ homeDir,
270
+ conversationDirs: options.antigravityDbDir ? [options.antigravityDbDir] : null,
271
+ maxDbs: Math.min(limit, 50)
272
+ });
273
+ }
274
+ const antigravityDbSteps = [];
275
+ let antigravityDbsScanned = 0;
276
+ for (const dbPath of dbPaths) {
277
+ const dbRes = readAntigravityConversationDbMetrics(dbPath);
278
+ if (dbRes.ok) {
279
+ antigravityDbsScanned += 1;
280
+ antigravityDbSteps.push(...dbRes.steps);
281
+ }
282
+ }
283
+
284
+ const allStepTimings = sessions.flatMap((s) => s._stepTimings || []);
285
+ const telemetry = aggregateTelemetryMetrics({
286
+ stepTimings: allStepTimings,
287
+ otelSpans,
288
+ antigravityDbSteps,
289
+ otelFilesScanned: otelFiles.length,
290
+ antigravityDbsScanned
291
+ });
292
+
293
+ const cleanSessions = sessions.map(({ attributionCalls: _calls, _stepTimings: _timings, ...rest }) => rest);
236
294
 
237
295
  return {
238
296
  ok: true,
239
297
  totals,
298
+ telemetry,
240
299
  valuation,
241
300
  uncachedAttribution,
242
301
  ledger: {
@@ -263,6 +322,25 @@ export function formatAuditReport(report = {}) {
263
322
  ` Estimated Cost : $${Number(t.estimatedCostUsd || 0).toFixed(4)} | 200k-cliff turns=${t.cliffTurns ?? 0} | rewind branches=${t.rewindBranches ?? 0}${quotaTag}`,
264
323
  ` Guard Savings : $${Number(report.ledger?.avoidedWriteUSD || 0).toFixed(4)} avoided (${(report.ledger?.avoidedWriteTokens || 0).toLocaleString('en-US')} tok)`
265
324
  ];
325
+ const perf = report.telemetry;
326
+ if (perf) {
327
+ const perfParts = [];
328
+ if (perf.medianTtftMs !== null && perf.medianTtftMs !== undefined) {
329
+ const label = perf.medianTtftMs >= 1000
330
+ ? `${(perf.medianTtftMs / 1000).toFixed(2)}s`
331
+ : `${Math.round(perf.medianTtftMs)}ms`;
332
+ perfParts.push(`TTFT p50=${label}`);
333
+ }
334
+ if (perf.medianTokensPerSec !== null && perf.medianTokensPerSec !== undefined) {
335
+ perfParts.push(`${perf.medianTokensPerSec.toFixed(1)} tok/s (p50)`);
336
+ }
337
+ if (Number(perf.otel?.spanCount || 0) > 0) {
338
+ perfParts.push(`OTel gen_ai spans=${perf.otel.spanCount}`);
339
+ }
340
+ if (perfParts.length > 0) {
341
+ lines.push(` Performance : ${perfParts.join(' | ')}`);
342
+ }
343
+ }
266
344
  if (t.sdkCliSessions > 0 || t.sdkCliHeuristicApplied) {
267
345
  lines.push(
268
346
  ` Quota Heuristic: headless sdk-cli (claude -p) observed in ${t.sdkCliSessions || 1} session(s) (~1.8x 5h quota burn heuristic per #97074; observational estimate, not a guaranteed constant).`