burnoff 1.1.0 → 1.2.0

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 (38) hide show
  1. package/.github/workflows/burnoff-pr-gate.yml +3 -3
  2. package/README.md +66 -78
  3. package/bin/burnoff.mjs +67 -23
  4. package/hooks/hook-io.mjs +19 -7
  5. package/hooks/post-tool-use.mjs +33 -26
  6. package/hooks/pre-tool-use.mjs +43 -41
  7. package/hooks/session-lifecycle.mjs +40 -0
  8. package/package.json +7 -5
  9. package/src/ci/ci-gate.mjs +22 -0
  10. package/src/ci/pr-cost.mjs +42 -10
  11. package/src/ci/team-digest.mjs +5 -3
  12. package/src/cli/audit.mjs +103 -18
  13. package/src/cli/doctor.mjs +209 -14
  14. package/src/cli/init.mjs +349 -96
  15. package/src/cli/startup-audit.mjs +500 -24
  16. package/src/clients/antigravity.mjs +285 -0
  17. package/src/clients/claude-code.mjs +180 -0
  18. package/src/clients/detect.mjs +64 -0
  19. package/src/config/loader.mjs +11 -4
  20. package/src/config/paths.mjs +62 -2
  21. package/src/config/policy.mjs +34 -5
  22. package/src/config/pricing.mjs +16 -5
  23. package/src/guards/loop-breaker.mjs +198 -13
  24. package/src/guards/post-tool-engine.mjs +289 -29
  25. package/src/guards/pre-tool-engine.mjs +336 -129
  26. package/src/guards/read-clamp.mjs +78 -18
  27. package/src/guards/session-hook.mjs +207 -0
  28. package/src/guards/shell-guard.mjs +583 -73
  29. package/src/ipc/daemon.mjs +50 -8
  30. package/src/ipc/fast-client.mjs +62 -5
  31. package/src/ipc/protocol.mjs +1 -1
  32. package/src/storage/antigravity-parser.mjs +258 -0
  33. package/src/storage/file-lock.mjs +13 -4
  34. package/src/storage/fts5-archive.mjs +4 -4
  35. package/src/storage/jsonl-parser.mjs +7 -1
  36. package/src/storage/ledger.mjs +10 -3
  37. package/src/storage/sqlite-client.mjs +4 -2
  38. package/hooks/hooks.json +0 -12
@@ -17,6 +17,7 @@ import {
17
17
  tryTier1PreToolFastPath
18
18
  } from './hook-io.mjs';
19
19
  import { tryFastDaemonRpc } from '../src/ipc/fast-client.mjs';
20
+ import { getClientAdapter, normalizeHookEvent } from '../src/clients/detect.mjs';
20
21
 
21
22
  let _engineMod = null;
22
23
  if (!isCliEntrypoint(import.meta.url)) {
@@ -41,8 +42,19 @@ export function runPreToolUseHook(event = {}, options = {}) {
41
42
  return _engineMod.runPreToolUseHook(event, options);
42
43
  }
43
44
 
44
- function exitOnInternalFault(err, ioOverride = {}) {
45
+ function exitOnInternalFault(err, ioOverride = {}, client = 'claude-code') {
45
46
  const msg = err?.message || String(err);
47
+ if (client === 'antigravity') {
48
+ const adapter = getClientAdapter(client);
49
+ const failRes = adapter.renderFailOpen(msg, 'PreToolUse');
50
+ const writeStderr =
51
+ ioOverride.stderrWrite ||
52
+ ioOverride.writeStderr ||
53
+ ((s) => globalThis.process?.stderr?.write?.(s));
54
+ writeStderr(failRes.stderr);
55
+ exitWithStdoutJson(failRes.stdout, ioOverride);
56
+ return;
57
+ }
46
58
  const strict =
47
59
  String(globalThis.process?.env?.BURNOFF_PRETOOL_FAIL_MODE || '').toLowerCase() === 'closed';
48
60
  if (strict) {
@@ -52,78 +64,68 @@ function exitOnInternalFault(err, ioOverride = {}) {
52
64
  exitDiagnosticZero(`internal error, tool call allowed (fail-open): ${msg}`, 'PreToolUse', ioOverride);
53
65
  }
54
66
 
67
+ function emitPreToolResult(res, payload, traceBase, pathLabel, ioOverride) {
68
+ if (res.exitCode === 2) {
69
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'block', path: pathLabel, exitCode: 2 });
70
+ exitHardBlockStderr(res.stderr, 'PreToolUse', ioOverride);
71
+ } else if (res.stdout) {
72
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: pathLabel, exitCode: 0 });
73
+ exitWithStdoutJson(res.stdout, ioOverride);
74
+ } else {
75
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: pathLabel, exitCode: 0 });
76
+ exitPassThrough(ioOverride.exitFn);
77
+ }
78
+ }
79
+
55
80
  export async function executePreToolUseCli(cliOptions = {}) {
56
81
  const readPayload = cliOptions.readPayload || readStdinJsonAsync;
57
82
  const ioOverride = cliOptions.ioOverride || {};
58
83
  let payload = {};
84
+ let detectedClient = 'claude-code';
59
85
  try {
60
86
  payload = await readPayload(cliOptions.timeoutMs);
87
+ const { client, adapter, canonical } = normalizeHookEvent(payload, cliOptions.hookOptions);
88
+ detectedClient = client;
61
89
  const hasCustomOptions = Boolean(cliOptions.runHook || cliOptions.hookOptions);
62
90
  const traceBase = { tracePath: cliOptions.tracePath };
63
91
 
64
92
  if (cliOptions.runHook) {
65
93
  const res = cliOptions.runHook(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
66
- if (res.exitCode === 2) {
67
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'block', path: 'custom', exitCode: 2 });
68
- exitHardBlockStderr(res.stderr, 'PreToolUse', ioOverride);
69
- } else if (res.stdout) {
70
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'custom', exitCode: 0 });
71
- exitWithStdoutJson(res.stdout, ioOverride);
72
- } else {
73
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'custom', exitCode: 0 });
74
- exitPassThrough(ioOverride.exitFn);
75
- }
94
+ emitPreToolResult(res, payload, traceBase, 'custom', ioOverride);
76
95
  return;
77
96
  }
78
97
 
79
98
  if (!hasCustomOptions) {
80
- if (tryTier1PreToolFastPath(payload)) {
81
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'tier1_fast', exitCode: 0 });
82
- exitPassThrough(ioOverride.exitFn);
99
+ const tier1 = tryTier1PreToolFastPath(canonical);
100
+ if (tier1) {
101
+ const rendered = client === 'antigravity' ? adapter.renderPre(tier1) : tier1;
102
+ emitPreToolResult(rendered, payload, traceBase, 'tier1_fast', ioOverride);
83
103
  return;
84
104
  }
85
105
 
86
106
  const ipcRes = await tryFastDaemonRpc(
87
- 'hook.claude.preToolUse',
88
- { event: payload },
107
+ 'hook.preToolUse',
108
+ { client, event: payload },
89
109
  { ipcPath: cliOptions.ipcPath }
90
110
  );
91
111
  if (ipcRes && ipcRes.fullVerdict === true) {
92
- if (ipcRes.exitCode === 2) {
93
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'block', path: 'daemon_ipc', exitCode: 2 });
94
- exitHardBlockStderr(ipcRes.stderr, 'PreToolUse', ioOverride);
95
- } else if (ipcRes.stdout) {
96
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'daemon_ipc', exitCode: 0 });
97
- exitWithStdoutJson(ipcRes.stdout, ioOverride);
98
- } else {
99
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'daemon_ipc', exitCode: 0 });
100
- exitPassThrough(ioOverride.exitFn);
101
- }
112
+ emitPreToolResult(ipcRes, payload, traceBase, 'daemon_ipc', ioOverride);
102
113
  return;
103
114
  }
104
115
 
105
- if (canFastAllowBoundedRead(payload, { cwd: payload?.cwd })) {
106
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'bounded_read_fast', exitCode: 0 });
107
- exitPassThrough(ioOverride.exitFn);
116
+ if (canFastAllowBoundedRead(payload, { cwd: canonical.cwd })) {
117
+ const fastRes = client === 'antigravity' ? adapter.renderPre({ exitCode: 0, stdout: '', stderr: '', verdict: { decision: 'allow' } }) : { exitCode: 0, stdout: '', stderr: '' };
118
+ emitPreToolResult(fastRes, payload, traceBase, 'bounded_read_fast', ioOverride);
108
119
  return;
109
120
  }
110
121
  }
111
122
 
112
123
  const { runPreToolUseHook: runCore } = await import('../src/guards/pre-tool-engine.mjs');
113
124
  const res = runCore(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
114
-
115
- if (res.exitCode === 2) {
116
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'block', path: 'core', exitCode: 2 });
117
- exitHardBlockStderr(res.stderr, 'PreToolUse', ioOverride);
118
- } else if (res.stdout) {
119
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'core', exitCode: 0 });
120
- exitWithStdoutJson(res.stdout, ioOverride);
121
- } else {
122
- recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'core', exitCode: 0 });
123
- exitPassThrough(ioOverride.exitFn);
124
- }
125
+ emitPreToolResult(res, payload, traceBase, 'core', ioOverride);
125
126
  } catch (err) {
126
127
  const strict =
128
+ detectedClient !== 'antigravity' &&
127
129
  String(globalThis.process?.env?.BURNOFF_PRETOOL_FAIL_MODE || '').toLowerCase() === 'closed';
128
130
  recordHookTrace('PreToolUse', payload, {
129
131
  tracePath: cliOptions.tracePath,
@@ -132,7 +134,7 @@ export async function executePreToolUseCli(cliOptions = {}) {
132
134
  exitCode: strict ? 2 : 0,
133
135
  error: err?.message || String(err)
134
136
  });
135
- exitOnInternalFault(err, ioOverride);
137
+ exitOnInternalFault(err, ioOverride, detectedClient);
136
138
  }
137
139
  }
138
140
 
@@ -0,0 +1,40 @@
1
+ /**
2
+ * @file hooks/session-lifecycle.mjs
3
+ * Thin Tier-2 command hook entrypoint for `SessionStart` and `PreCompact`.
4
+ * Fails open (`exitCode: 0`) so session startup or compaction is never blocked.
5
+ */
6
+
7
+ import {
8
+ isCliEntrypoint,
9
+ readStdinJsonAsync,
10
+ exitPassThrough,
11
+ exitDiagnosticZero,
12
+ exitWithStdoutJson
13
+ } from './hook-io.mjs';
14
+ import { runSessionLifecycleHook } from '../src/guards/session-hook.mjs';
15
+
16
+ export async function executeSessionLifecycleCli(cliOptions = {}) {
17
+ const readPayload = cliOptions.readPayload || readStdinJsonAsync;
18
+ const ioOverride = cliOptions.ioOverride || {};
19
+ try {
20
+ const payload = await readPayload(cliOptions.timeoutMs);
21
+ const res = runSessionLifecycleHook(payload, cliOptions.hookOptions || {});
22
+ if (res.stdout) {
23
+ exitWithStdoutJson(res.stdout, ioOverride);
24
+ } else {
25
+ exitPassThrough(ioOverride.exitFn);
26
+ }
27
+ } catch (err) {
28
+ exitDiagnosticZero(err?.message || String(err), 'SessionStart', ioOverride);
29
+ }
30
+ }
31
+
32
+ if (isCliEntrypoint(import.meta.url)) {
33
+ executeSessionLifecycleCli().catch((err) => {
34
+ exitDiagnosticZero(err?.message || String(err), 'SessionStart');
35
+ });
36
+ }
37
+
38
+ export default {
39
+ executeSessionLifecycleCli
40
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "burnoff",
3
- "version": "1.1.0",
4
- "description": "Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code.",
3
+ "version": "1.2.0",
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",
7
7
  "author": "Gizzant",
@@ -15,6 +15,8 @@
15
15
  },
16
16
  "keywords": [
17
17
  "claude-code",
18
+ "antigravity",
19
+ "google-antigravity",
18
20
  "hooks",
19
21
  "circuit-breaker",
20
22
  "finops",
@@ -29,7 +31,7 @@
29
31
  },
30
32
  "files": [
31
33
  "bin/",
32
- "hooks/",
34
+ "hooks/*.mjs",
33
35
  "src/",
34
36
  ".github/workflows/burnoff-pr-gate.yml",
35
37
  "LICENSE",
@@ -37,9 +39,9 @@
37
39
  ],
38
40
  "dependencies": {},
39
41
  "scripts": {
40
- "test": "node --test test/*.test.mjs",
42
+ "test": "node --test --test-concurrency=1",
41
43
  "test:bench": "node --test test/ipc-daemon-bench.test.mjs",
42
44
  "doctor": "node bin/burnoff.mjs doctor",
43
- "check:brands": "node -e \"import('node:fs').then(async fs=>{const p=await import('node:path');const bad=new RegExp(['ctx'+'top','high'+'beam','attention[-_]'+'horizon','ga-visual'+'izer-v2','anti'+'gravity','pro_'+'license','ah-status'+'line','\\\\bHB'+'-(?:CFG|MCP|SEC)-','\\\\ba'+'gy','default'+'_api:','phase0'+'_' ].join('|'),'i');const dirs=['bin','hooks','src','.github'];let hits=[];const walk=(d)=>{if(!fs.existsSync(d))return;for(const e of fs.readdirSync(d,{withFileTypes:true})){const f=p.join(d,e.name);if(e.isDirectory())walk(f);else if(/\\.(mjs|json|ya?ml|md)$/.test(e.name)){const t=fs.readFileSync(f,'utf8');if(bad.test(t))hits.push(f);}}};dirs.forEach(walk);['package.json','README.md'].forEach(f=>{if(fs.existsSync(f)&&bad.test(fs.readFileSync(f,'utf8')))hits.push(f);});if(hits.length){console.error('Brand leaks:',hits);process.exit(1);}console.log('Zero legacy brand strings found.');})\""
45
+ "check:brands": "node -e \"import('node:fs').then(async fs=>{const p=await import('node:path');const bad=new RegExp(['ctx'+'top','high'+'beam','attention[-_]'+'horizon','ga-visual'+'izer-v2','pro_'+'license','ah-status'+'line','\\\\bHB'+'-(?:CFG|MCP|SEC)-','\\\\ba'+'gy','default'+'_api:','phase0'+'_' ].join('|'),'i');const dirs=['bin','hooks','src','.github'];let hits=[];const walk=(d)=>{if(!fs.existsSync(d))return;for(const e of fs.readdirSync(d,{withFileTypes:true})){const f=p.join(d,e.name);if(e.isDirectory())walk(f);else if(/\\.(mjs|json|ya?ml|md)$/.test(e.name)){const t=fs.readFileSync(f,'utf8');if(bad.test(t))hits.push(f);}}};dirs.forEach(walk);['package.json','README.md'].forEach(f=>{if(fs.existsSync(f)&&bad.test(fs.readFileSync(f,'utf8')))hits.push(f);});if(hits.length){console.error('Brand leaks:',hits);process.exit(1);}console.log('Zero legacy brand strings found.');})\""
44
46
  }
45
47
  }
@@ -78,11 +78,24 @@ export function loadCiBudgetPolicy(cwd, overrides = {}) {
78
78
  }
79
79
  };
80
80
 
81
+ const hasFileFailOnMissing =
82
+ loaded.exists &&
83
+ !loaded.parseError &&
84
+ typeof filePolicy?.failOnMissingTranscripts === 'boolean';
85
+ const hasOverrideFailOnMissing = typeof overrides?.failOnMissingTranscripts === 'boolean';
86
+ const isCiEnv = Boolean(
87
+ overrides?.isCi ?? (globalThis.process?.env?.CI || globalThis.process?.env?.GITHUB_ACTIONS)
88
+ );
89
+
81
90
  if (loaded.exists) {
82
91
  applyLayer(filePolicy);
83
92
  }
84
93
  applyLayer(overrides);
85
94
 
95
+ if (!hasFileFailOnMissing && !hasOverrideFailOnMissing) {
96
+ merged.failOnMissingTranscripts = isCiEnv;
97
+ }
98
+
86
99
  if (overrides?.strict === true) {
87
100
  merged.mode = 'enforce';
88
101
  }
@@ -97,6 +110,15 @@ export function loadCiBudgetPolicy(cwd, overrides = {}) {
97
110
  */
98
111
  export function evaluateCiBudgetGate(options = {}) {
99
112
  const cwd = path.resolve(options.cwd || process.cwd());
113
+ const loadedPolicy = loadBurnoffPolicy(cwd);
114
+ if (loadedPolicy.exists && loadedPolicy.parseError) {
115
+ return {
116
+ ok: false,
117
+ verdict: 'ERROR',
118
+ exitCode: 1,
119
+ error: `Failed to parse ${path.basename(loadedPolicy.sourcePath || '.burnoff.yaml')}: ${loadedPolicy.parseErrorMessage || 'Invalid YAML syntax'}`
120
+ };
121
+ }
100
122
  const policyOverrides = {
101
123
  ...(options.policyOverrides || options),
102
124
  ...(options.strict ? { strict: true, mode: 'enforce' } : {})
@@ -12,13 +12,17 @@ import fs from 'node:fs';
12
12
  import os from 'node:os';
13
13
  import path from 'node:path';
14
14
  import { getHomeDir } from '../config/paths.mjs';
15
- import { DEFAULT_UNMAPPED_CACHED_WEIGHT, valuateCall } from '../config/pricing.mjs';
15
+ import { DEFAULT_UNMAPPED_CACHED_WEIGHT, resolveModelRateCard, valuateCall } from '../config/pricing.mjs';
16
16
  import { attributeUncachedTokens } from '../config/uncached-attribution.mjs';
17
17
  import { readLedgerEntries } from '../storage/ledger.mjs';
18
18
  import {
19
19
  discoverClaudeCodeSessions,
20
20
  parseTranscriptIncremental
21
21
  } from '../storage/jsonl-parser.mjs';
22
+ import {
23
+ discoverAntigravityTranscripts,
24
+ parseAntigravityTranscript
25
+ } from '../storage/antigravity-parser.mjs';
22
26
 
23
27
  export const PR_ATTRIBUTION_FORMAT = 'burnoff-pr-attribution/v1';
24
28
 
@@ -236,9 +240,15 @@ function extractStepFields(step = {}, cwd = '') {
236
240
  const cacheReadTok = Number(
237
241
  step.cacheReadTokens ?? step.cache_read_input_tokens ?? usage.cacheReadTokens ?? 0
238
242
  );
239
- const outTok =
240
- Number(step.outputTokens ?? step.output_tokens ?? usage.outputTokens ?? 0) +
241
- Number(step.thinkingTokens ?? step.thinking_tokens ?? usage.thinkingTokens ?? 0);
243
+ const rawOutTok = Number(step.outputTokens ?? step.output_tokens ?? usage.outputTokens ?? 0);
244
+ const thinkTok = Number(step.thinkingTokens ?? step.thinking_tokens ?? usage.thinkingTokens ?? 0);
245
+ const stepModel = step.model || step.modelId || usage.model || null;
246
+ const rateCard = stepModel ? resolveModelRateCard({ model: stepModel, label: step.label || '' }) : null;
247
+ const includesThinking =
248
+ step.outputIncludesThinking !== undefined
249
+ ? Boolean(step.outputIncludesThinking)
250
+ : (rateCard ? rateCard.outputIncludesThinking !== false : true);
251
+ const outTok = includesThinking ? rawOutTok : rawOutTok + thinkTok;
242
252
  const hasExplicitWaste =
243
253
  step.wasteTokens !== undefined || step.wastedTokens !== undefined;
244
254
  const wasteTok = Number(step.wasteTokens ?? step.wastedTokens ?? 0);
@@ -283,6 +293,7 @@ function extractStepFields(step = {}, cwd = '') {
283
293
  cacheWriteTok,
284
294
  cacheReadTok,
285
295
  outTok,
296
+ thinkingTok: thinkTok,
286
297
  wasteTok,
287
298
  hasExplicitWaste,
288
299
  totalTok: inTok + cacheWriteTok + cacheReadTok + outTok,
@@ -329,7 +340,10 @@ function computeStepUsdWithModel(st, pricePerMillionUsd, hasExplicitPriceOverrid
329
340
  */
330
341
  export function buildPrCostAttribution(options = {}) {
331
342
  const cwd = path.resolve(options.cwd || process.cwd());
332
- const homeDir = options.homeDir || getHomeDir();
343
+ const explicitHomeDir = typeof options.homeDir === 'string' && options.homeDir.trim()
344
+ ? options.homeDir.trim()
345
+ : null;
346
+ const homeDir = explicitHomeDir || getHomeDir();
333
347
  const base = String(options.base || 'main');
334
348
  const head = String(options.head || 'HEAD');
335
349
  const hasExplicitPriceOverride = options.pricePerMillionUsd !== undefined && options.pricePerMillionUsd !== null;
@@ -364,10 +378,28 @@ export function buildPrCostAttribution(options = {}) {
364
378
  }
365
379
  if (!Array.isArray(options.steps) && !Array.isArray(options.sessions) && options.readSessions !== false) {
366
380
  const maxSessions = Math.max(1, Number(options.maxSessions ?? 20));
367
- const discovered = discoverClaudeCodeSessions(homeDir, { cwd }).slice(0, maxSessions);
368
- sessionCount = discovered.length;
369
- for (const meta of discovered) {
370
- const parsed = parseTranscriptIncremental(meta.filePath, { homeDir });
381
+ const clientOpt = String(options.client || 'auto').trim().toLowerCase();
382
+ const includeClaude = clientOpt !== 'antigravity' && clientOpt !== 'ag';
383
+ const includeAg = clientOpt === 'antigravity' || clientOpt === 'ag' || clientOpt === 'both' || clientOpt === 'auto';
384
+
385
+ const claudeDiscovered = includeClaude ? discoverClaudeCodeSessions(homeDir, { cwd }).slice(0, maxSessions) : [];
386
+ const agDiscovered = includeAg ? discoverAntigravityTranscripts({ homeDir, cwd }).slice(0, maxSessions) : [];
387
+ sessionCount = claudeDiscovered.length + agDiscovered.length;
388
+
389
+ for (const meta of claudeDiscovered) {
390
+ const parsed = parseTranscriptIncremental(meta.filePath, { homeDir: explicitHomeDir });
391
+ if (Array.isArray(parsed?.steps)) {
392
+ rawSteps.push(
393
+ ...parsed.steps.map((st) => ({
394
+ ...st,
395
+ sessionId: st.sessionId || meta.sessionId || 'default'
396
+ }))
397
+ );
398
+ }
399
+ }
400
+
401
+ for (const meta of agDiscovered) {
402
+ const parsed = parseAntigravityTranscript(meta.filePath, { sessionId: meta.sessionId });
371
403
  if (Array.isArray(parsed?.steps)) {
372
404
  rawSteps.push(
373
405
  ...parsed.steps.map((st) => ({
@@ -383,7 +415,7 @@ export function buildPrCostAttribution(options = {}) {
383
415
  const rawLedger = Array.isArray(options.ledgerEntries)
384
416
  ? options.ledgerEntries
385
417
  : options.readLedger !== false
386
- ? readLedgerEntries({ homeDir, cwd })
418
+ ? readLedgerEntries({ homeDir: explicitHomeDir, cwd })
387
419
  : [];
388
420
 
389
421
  const validTimestamps = commits.map((c) => c.timestampMs).filter((t) => Number.isFinite(t) && t > 0);
@@ -15,19 +15,21 @@ import { loadCiBudgetPolicy } from './ci-gate.mjs';
15
15
  */
16
16
  export function buildTeamDigest(options = {}) {
17
17
  const cwd = path.resolve(options.cwd || process.cwd());
18
- const homeDir = options.homeDir || getHomeDir();
18
+ const explicitHomeDir = typeof options.homeDir === 'string' && options.homeDir.trim()
19
+ ? options.homeDir.trim()
20
+ : null;
19
21
  const days = Math.max(1, Number(options.days ?? 7));
20
22
  const nowMs = Number(options.nowMs || Date.now());
21
23
  const cutoffMs = nowMs - days * 24 * 60 * 60 * 1000;
22
24
 
23
25
  let sessions = Array.isArray(options.sessions) ? options.sessions : null;
24
26
  if (!sessions) {
25
- const audited = auditClaudeSessions({ cwd, homeDir, limit: options.limit ?? 50 });
27
+ const audited = auditClaudeSessions({ cwd, homeDir: explicitHomeDir, limit: options.limit ?? 50 });
26
28
  sessions = audited.sessions.filter((s) => !s.mtimeMs || s.mtimeMs >= cutoffMs);
27
29
  }
28
30
 
29
31
  const prReports = Array.isArray(options.prReports) ? options.prReports : [];
30
- const ledgerSummary = options.ledgerSummary || getSavedQuotaReceiptSummary({ homeDir, nowMs });
32
+ const ledgerSummary = options.ledgerSummary || getSavedQuotaReceiptSummary({ homeDir: explicitHomeDir, nowMs });
31
33
  const policy = loadCiBudgetPolicy(cwd, options.policyOverrides || {});
32
34
 
33
35
  let totalSpendUsd = 0;
package/src/cli/audit.mjs CHANGED
@@ -12,6 +12,11 @@ import {
12
12
  discoverClaudeCodeSessions,
13
13
  parseTranscriptIncremental
14
14
  } from '../storage/jsonl-parser.mjs';
15
+ import {
16
+ discoverAntigravityTranscripts,
17
+ isAntigravityTranscriptFile,
18
+ parseAntigravityTranscript
19
+ } from '../storage/antigravity-parser.mjs';
15
20
  import { getSavedQuotaReceiptSummary } from '../storage/ledger.mjs';
16
21
  import { attributeUncachedTokens } from '../config/uncached-attribution.mjs';
17
22
  import { valuateBatch } from '../config/pricing.mjs';
@@ -23,6 +28,7 @@ function summarizeParsedSession(meta, parsed, options = {}) {
23
28
  let cacheReadTokens = 0;
24
29
  let outputTokens = 0;
25
30
  let thinkingTokens = 0;
31
+ let billedOutputTokens = 0;
26
32
  let estimatedCostUsd = 0;
27
33
  let cliffTurns = 0;
28
34
  let unknownModelTurns = 0;
@@ -88,6 +94,7 @@ function summarizeParsedSession(meta, parsed, options = {}) {
88
94
  cacheReadTokens += crTok;
89
95
  outputTokens += outTok;
90
96
  thinkingTokens += thinkTok;
97
+ billedOutputTokens += Number(costRes?.tokens?.totalOutput ?? outTok);
91
98
 
92
99
  if (costRes.unknownModel) {
93
100
  unknownModelTurns += 1;
@@ -97,7 +104,7 @@ function summarizeParsedSession(meta, parsed, options = {}) {
97
104
  }
98
105
  }
99
106
 
100
- const totalTokens = inputTokens + cacheWriteTokens + cacheReadTokens + outputTokens + thinkingTokens;
107
+ const totalTokens = inputTokens + cacheWriteTokens + cacheReadTokens + billedOutputTokens;
101
108
  const cacheDenom = inputTokens + cacheWriteTokens + cacheReadTokens;
102
109
  const cacheHitPct = cacheDenom > 0 ? Math.round((cacheReadTokens / cacheDenom) * 100) : 0;
103
110
 
@@ -133,28 +140,48 @@ function summarizeParsedSession(meta, parsed, options = {}) {
133
140
  }
134
141
 
135
142
  /**
136
- * Audits local Claude Code JSONL transcripts (or a single `--session <path>` file).
143
+ * Audits local Claude Code and/or Google Antigravity JSONL transcripts (or a single `--session <path>` file).
137
144
  */
138
145
  export function auditClaudeSessions(options = {}) {
139
- const homeDir = options.homeDir || getHomeDir();
146
+ const explicitHomeDir = typeof options.homeDir === 'string' && options.homeDir.trim()
147
+ ? options.homeDir.trim()
148
+ : null;
149
+ const homeDir = explicitHomeDir || getHomeDir();
140
150
  const limit = Math.max(1, Number(options.limit ?? 20));
141
- const candidates = options.sessionPath
142
- ? [
143
- {
144
- filePath: path.resolve(options.sessionPath),
145
- sessionId: path.basename(options.sessionPath, '.jsonl'),
146
- projectSlug: '',
147
- mtimeMs: 0
148
- }
149
- ]
150
- : discoverClaudeCodeSessions(homeDir, options).slice(0, limit);
151
+ let candidates;
152
+ if (options.sessionPath) {
153
+ const abs = path.resolve(options.sessionPath);
154
+ const isAg = isAntigravityTranscriptFile(abs);
155
+ candidates = [
156
+ {
157
+ filePath: abs,
158
+ sessionId: path.basename(options.sessionPath, '.jsonl'),
159
+ projectSlug: isAg ? 'antigravity' : '',
160
+ client: isAg ? 'antigravity' : 'claude-code',
161
+ mtimeMs: 0
162
+ }
163
+ ];
164
+ } else {
165
+ const clientOpt = String(options.client || 'auto').trim().toLowerCase();
166
+ const includeClaude = clientOpt !== 'antigravity' && clientOpt !== 'ag';
167
+ const includeAg =
168
+ clientOpt === 'antigravity' || clientOpt === 'ag' || clientOpt === 'both' || clientOpt === 'auto';
169
+ const claudeList = includeClaude ? discoverClaudeCodeSessions(homeDir, options) : [];
170
+ const agList = includeAg ? discoverAntigravityTranscripts({ homeDir, cwd: options.cwd }) : [];
171
+ candidates = [...claudeList, ...agList]
172
+ .sort((a, b) => (b.mtimeMs || 0) - (a.mtimeMs || 0))
173
+ .slice(0, limit);
174
+ }
151
175
 
152
176
  const sessions = [];
153
177
  for (const meta of candidates) {
154
- const parsed = parseTranscriptIncremental(meta.filePath, {
155
- homeDir,
156
- tailBytes: options.tailBytes
157
- });
178
+ const useAg = meta.client === 'antigravity' || isAntigravityTranscriptFile(meta.filePath);
179
+ const parsed = useAg
180
+ ? parseAntigravityTranscript(meta.filePath, { sessionId: meta.sessionId })
181
+ : parseTranscriptIncremental(meta.filePath, {
182
+ homeDir: explicitHomeDir,
183
+ tailBytes: options.tailBytes
184
+ });
158
185
  sessions.push(summarizeParsedSession(meta, parsed, options));
159
186
  }
160
187
 
@@ -191,7 +218,7 @@ export function auditClaudeSessions(options = {}) {
191
218
  const denom = totals.inputTokens + totals.cacheWriteTokens + totals.cacheReadTokens;
192
219
  totals.cacheHitPct = denom > 0 ? Math.round((totals.cacheReadTokens / denom) * 100) : 0;
193
220
 
194
- const ledger = getSavedQuotaReceiptSummary({ homeDir });
221
+ const ledger = getSavedQuotaReceiptSummary({ homeDir: explicitHomeDir });
195
222
  const allAttributionCalls = sessions.flatMap((s) => s.attributionCalls || []);
196
223
  const valuation = valuateBatch(allAttributionCalls, {
197
224
  nowMs: options.nowMs ?? Date.now(),
@@ -247,6 +274,64 @@ export function formatAuditReport(report = {}) {
247
274
  ` Provider Quirk : Claude 5.5 /compact warm-cache miss (#99624): ${claude55Miss.calls} calls, ${claude55Miss.tokens.toLocaleString('en-US')} uncached tok`
248
275
  );
249
276
  }
277
+ const buckets = report.uncachedAttribution?.buckets || {};
278
+ const thrash = buckets.model_or_effort_switch?.orchestratorThrash;
279
+ if (thrash && thrash.calls > 0) {
280
+ lines.push(
281
+ ` Provider Quirk : Orchestrator/model ping-pong thrash (${thrash.issueRef || '#1638'}): ${thrash.calls} calls, ${thrash.tokens.toLocaleString('en-US')} uncached tok — ${thrash.guidance}`
282
+ );
283
+ }
284
+ if (Number(report.uncachedAttribution?.totalUncachedTokens || 0) > 0) {
285
+ const driverLines = [];
286
+ const idleMiss = buckets.idle_ttl_miss;
287
+ if (idleMiss && idleMiss.tokens > 0) {
288
+ driverLines.push(
289
+ ` - idle_ttl_miss: ${idleMiss.calls} calls, ${idleMiss.tokens.toLocaleString('en-US')} tok (${idleMiss.sharePct}%, ~$${Number(idleMiss.estimatedUsd || 0).toFixed(2)}) — consider 1h cache TTL for >5m review pauses`
290
+ );
291
+ }
292
+ const modelSwitch = buckets.model_or_effort_switch;
293
+ if (modelSwitch && modelSwitch.tokens > 0) {
294
+ driverLines.push(
295
+ ` - model_or_effort_switch: ${modelSwitch.calls} calls, ${modelSwitch.tokens.toLocaleString('en-US')} tok (${modelSwitch.sharePct}%, ~$${Number(modelSwitch.estimatedUsd || 0).toFixed(2)})`
296
+ );
297
+ }
298
+ const unexplained = buckets.unexplained_prefix_reset;
299
+ if (unexplained && unexplained.tokens > 0) {
300
+ const act = unexplained.subBuckets?.actionable_prefix_reset;
301
+ const up = unexplained.subBuckets?.upstream_provider_eviction;
302
+ let emittedSub = false;
303
+ if (act && act.tokens > 0) {
304
+ const likelyHint = Array.isArray(unexplained.likelyCauses) && unexplained.likelyCauses.length > 0
305
+ ? ` (e.g., ${unexplained.likelyCauses[0]})`
306
+ : '';
307
+ driverLines.push(
308
+ ` - unexplained_prefix_reset (actionable): ${act.calls} calls, ${act.tokens.toLocaleString('en-US')} tok (${act.shareOfBucketPct ?? unexplained.sharePct}%, ~$${Number(act.estimatedUsd || 0).toFixed(2)})${likelyHint}`
309
+ );
310
+ emittedSub = true;
311
+ }
312
+ if (up && up.tokens > 0) {
313
+ const adviceHint = up.advice ? ` — ${up.advice}` : '';
314
+ driverLines.push(
315
+ ` - unexplained_prefix_reset (upstream eviction): ${up.calls} calls, ${up.tokens.toLocaleString('en-US')} tok (${up.shareOfBucketPct ?? unexplained.sharePct}%, ~$${Number(up.estimatedUsd || 0).toFixed(2)})${adviceHint}`
316
+ );
317
+ emittedSub = true;
318
+ }
319
+ if (!emittedSub) {
320
+ driverLines.push(
321
+ ` - unexplained_prefix_reset: ${unexplained.calls} calls, ${unexplained.tokens.toLocaleString('en-US')} tok (${unexplained.sharePct}%, ~$${Number(unexplained.estimatedUsd || 0).toFixed(2)})`
322
+ );
323
+ }
324
+ }
325
+ const compaction = buckets.compaction_rebuild;
326
+ if (compaction && compaction.tokens > 0) {
327
+ driverLines.push(
328
+ ` - compaction_rebuild: ${compaction.calls} calls, ${compaction.tokens.toLocaleString('en-US')} tok (${compaction.sharePct}%, ~$${Number(compaction.estimatedUsd || 0).toFixed(2)})`
329
+ );
330
+ }
331
+ if (driverLines.length > 0) {
332
+ lines.push('', ' Uncached Drivers:', ...driverLines);
333
+ }
334
+ }
250
335
  if (Array.isArray(report.sessions) && report.sessions.length > 0) {
251
336
  lines.push('', ' Recent Sessions:');
252
337
  for (const s of report.sessions.slice(0, 10)) {