burnoff 1.1.0 → 1.3.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 (45) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/.github/workflows/burnoff-pr-gate.yml +3 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +37 -0
  4. package/README.md +90 -75
  5. package/bin/burnoff.mjs +185 -24
  6. package/commands/burnoff.md +16 -0
  7. package/docs/CLAUDE_CODE_PLUGIN.md +67 -0
  8. package/docs/DESIGN_PARTNER_INTAKE.md +44 -0
  9. package/hooks/hook-io.mjs +19 -7
  10. package/hooks/post-tool-use.mjs +33 -26
  11. package/hooks/pre-tool-use.mjs +43 -41
  12. package/hooks/session-lifecycle.mjs +40 -0
  13. package/package.json +15 -7
  14. package/scripts/burnoff-statusline.mjs +84 -0
  15. package/src/ci/ci-gate.mjs +22 -0
  16. package/src/ci/pr-cost.mjs +42 -10
  17. package/src/ci/team-digest.mjs +5 -3
  18. package/src/cli/audit.mjs +103 -18
  19. package/src/cli/doctor.mjs +209 -14
  20. package/src/cli/init.mjs +349 -96
  21. package/src/cli/startup-audit.mjs +712 -62
  22. package/src/clients/antigravity.mjs +285 -0
  23. package/src/clients/claude-code.mjs +180 -0
  24. package/src/clients/detect.mjs +64 -0
  25. package/src/config/loader.mjs +11 -4
  26. package/src/config/paths.mjs +62 -2
  27. package/src/config/policy.mjs +34 -5
  28. package/src/config/pricing.mjs +16 -5
  29. package/src/guards/loop-breaker.mjs +198 -13
  30. package/src/guards/post-tool-engine.mjs +289 -29
  31. package/src/guards/pre-tool-engine.mjs +382 -151
  32. package/src/guards/read-clamp.mjs +78 -18
  33. package/src/guards/session-hook.mjs +207 -0
  34. package/src/guards/shell-guard.mjs +583 -73
  35. package/src/guards/snooze.mjs +360 -0
  36. package/src/ipc/daemon.mjs +50 -8
  37. package/src/ipc/fast-client.mjs +62 -5
  38. package/src/ipc/protocol.mjs +1 -1
  39. package/src/storage/antigravity-parser.mjs +258 -0
  40. package/src/storage/file-lock.mjs +13 -4
  41. package/src/storage/fts5-archive.mjs +4 -4
  42. package/src/storage/jsonl-parser.mjs +7 -1
  43. package/src/storage/ledger.mjs +10 -3
  44. package/src/storage/sqlite-client.mjs +4 -2
  45. 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,13 +1,13 @@
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.3.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",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "https://github.com/Gizzant/burnoff.git"
10
+ "url": "git+https://github.com/Gizzant/burnoff.git"
11
11
  },
12
12
  "homepage": "https://github.com/Gizzant/burnoff#readme",
13
13
  "bugs": {
@@ -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",
@@ -22,24 +24,30 @@
22
24
  "guardrails"
23
25
  ],
24
26
  "bin": {
25
- "burnoff": "./bin/burnoff.mjs"
27
+ "burnoff": "bin/burnoff.mjs"
26
28
  },
27
29
  "engines": {
28
30
  "node": ">=20.19.0"
29
31
  },
30
32
  "files": [
31
33
  "bin/",
32
- "hooks/",
34
+ "hooks/*.mjs",
33
35
  "src/",
36
+ ".claude-plugin/",
37
+ "commands/",
38
+ "scripts/",
34
39
  ".github/workflows/burnoff-pr-gate.yml",
40
+ ".github/workflows/burnoff-startup-lint.yml",
41
+ "docs/CLAUDE_CODE_PLUGIN.md",
42
+ "docs/DESIGN_PARTNER_INTAKE.md",
35
43
  "LICENSE",
36
44
  "README.md"
37
45
  ],
38
46
  "dependencies": {},
39
47
  "scripts": {
40
- "test": "node --test test/*.test.mjs",
48
+ "test": "node --test --test-concurrency=1",
41
49
  "test:bench": "node --test test/ipc-daemon-bench.test.mjs",
42
50
  "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.');})\""
51
+ "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','.claude-plugin','commands','scripts'];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','docs/CLAUDE_CODE_PLUGIN.md','docs/DESIGN_PARTNER_INTAKE.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
52
  }
45
53
  }
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file scripts/burnoff-statusline.mjs
4
+ * Zero-dependency, fail-silent status-line renderer for Claude Code `settings.json` `"statusLine"`.
5
+ * Summarizes Burnoff ledger savings + guard interventions alongside live stdin context metrics.
6
+ */
7
+
8
+ import fs from 'node:fs';
9
+ import { readLedgerSummary } from '../src/storage/ledger.mjs';
10
+ import { isCliEntrypoint } from '../hooks/hook-io.mjs';
11
+
12
+ function formatCompactTokens(tokens = 0) {
13
+ const n = Math.max(0, Number(tokens || 0));
14
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
15
+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
16
+ return String(Math.round(n));
17
+ }
18
+
19
+ function formatUsd(usd = 0) {
20
+ const n = Math.max(0, Number(usd || 0));
21
+ return `$${n.toFixed(2)}`;
22
+ }
23
+
24
+ /**
25
+ * Renders a single compact terminal status line from Claude Code stdin JSON + Burnoff ledger.
26
+ */
27
+ export function renderBurnoffStatusLine(inputJson = {}, options = {}) {
28
+ const payload = inputJson && typeof inputJson === 'object' ? inputJson : {};
29
+ const cwd = options.cwd || payload.workspace?.current_dir || payload.cwd || process.cwd();
30
+ const homeDir = options.homeDir;
31
+
32
+ let summary = null;
33
+ try {
34
+ summary = readLedgerSummary({
35
+ cwd,
36
+ homeDir,
37
+ windowDays: options.windowDays ?? 7,
38
+ nowMs: options.nowMs
39
+ });
40
+ } catch {
41
+ summary = null; // ignore: unreadable ledger fails silent on statusLine
42
+ }
43
+
44
+ const savedTokens = Number(summary?.totalSavedTokens || 0);
45
+ const savedUsd = Number(summary?.totalSavedUSD || 0);
46
+ const guardCount = Number(summary?.categories?.loopAndReadGuarded?.count || 0);
47
+
48
+ const parts = [
49
+ `burnoff`,
50
+ `saved: ${formatCompactTokens(savedTokens)} tok (${formatUsd(savedUsd)})`,
51
+ `guards: ${guardCount}`
52
+ ];
53
+
54
+ const usedPct = Number(payload.context_window?.used_percentage);
55
+ if (Number.isFinite(usedPct) && usedPct >= 0) {
56
+ parts.push(`ctx: ${Math.round(usedPct)}%`);
57
+ }
58
+
59
+ const sessionCost = Number(payload.cost?.total_cost_usd);
60
+ if (Number.isFinite(sessionCost) && sessionCost > 0) {
61
+ parts.push(`sess: ${formatUsd(sessionCost)}`);
62
+ }
63
+
64
+ return parts.join(' | ');
65
+ }
66
+
67
+ function readStdinSyncSafe() {
68
+ try {
69
+ const raw = fs.readFileSync(0, 'utf8').trim();
70
+ if (!raw) return {};
71
+ return JSON.parse(raw);
72
+ } catch {
73
+ return {}; // ignore: malformed or empty stdin falls back cleanly
74
+ }
75
+ }
76
+
77
+ if (isCliEntrypoint(import.meta.url)) {
78
+ const stdinPayload = readStdinSyncSafe();
79
+ process.stdout.write(`${renderBurnoffStatusLine(stdinPayload)}\n`);
80
+ }
81
+
82
+ export default {
83
+ renderBurnoffStatusLine
84
+ };
@@ -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;