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
@@ -0,0 +1,285 @@
1
+ /**
2
+ * @file src/clients/antigravity.mjs
3
+ * Google Antigravity hook adapter (supports both Antigravity 2.0 CLI/App and IDE v1/Cascade).
4
+ * Normalizes camelCase/PascalCase `toolCall` payloads into Burnoff's `CanonicalEvent` and
5
+ * renders verdicts strictly in Antigravity's `exitCode: 0` JSON stdout contract.
6
+ */
7
+
8
+ export const CLIENT_ID = 'antigravity';
9
+
10
+ const ANTIGRAVITY_TOOL_MAP = Object.freeze({
11
+ run_command: 'Bash',
12
+ read_file: 'Read',
13
+ view_file: 'Read',
14
+ write_file: 'Write',
15
+ write_to_file: 'Write',
16
+ edit_file: 'Edit',
17
+ replace_file_content: 'Edit',
18
+ multi_replace_file_content: 'Edit',
19
+ grep_search: 'Grep',
20
+ find_by_name: 'Glob',
21
+ list_dir: 'Glob',
22
+ invoke_subagent: 'Task',
23
+ read_url_content: 'WebFetch'
24
+ });
25
+
26
+ /**
27
+ * Returns true if the payload matches Google Antigravity's camelCase `toolCall` / `conversationId` contract.
28
+ */
29
+ export function detect(payload = {}) {
30
+ if (!payload || typeof payload !== 'object') return false;
31
+ if (payload.toolCall && typeof payload.toolCall === 'object') return true;
32
+ if (typeof payload.conversationId === 'string' && payload.conversationId.length > 0) return true;
33
+ if (Array.isArray(payload.workspacePaths) && payload.workspacePaths.length > 0) return true;
34
+ return false;
35
+ }
36
+
37
+ function mapToolName(rawName, args = {}) {
38
+ const key = String(rawName || '').trim();
39
+ if (!key) return '';
40
+ const lower = key.toLowerCase();
41
+ if (ANTIGRAVITY_TOOL_MAP[lower]) {
42
+ return ANTIGRAVITY_TOOL_MAP[lower];
43
+ }
44
+ if (lower === 'call_mcp_tool') {
45
+ const server = String(args.ServerName || args.serverName || args.server || 'server').trim();
46
+ const tool = String(args.ToolName || args.toolName || args.tool || 'tool').trim();
47
+ return `mcp__${server}__${tool}`;
48
+ }
49
+ if (lower.startsWith('mcp_') && !lower.startsWith('mcp__')) {
50
+ const rest = key.slice(4);
51
+ const sep = rest.indexOf('_');
52
+ if (sep > 0) {
53
+ return `mcp__${rest.slice(0, sep)}__${rest.slice(sep + 1)}`;
54
+ }
55
+ return `mcp__${rest}`;
56
+ }
57
+ return key;
58
+ }
59
+
60
+ function mapToolArgs(rawName, args = {}, payload = {}) {
61
+ const lower = String(rawName || '').trim().toLowerCase();
62
+ const mapped = { ...(args && typeof args === 'object' ? args : {}) };
63
+
64
+ if (lower === 'run_command') {
65
+ if (mapped.CommandLine !== undefined && mapped.command === undefined) {
66
+ mapped.command = String(mapped.CommandLine);
67
+ }
68
+ if (mapped.Cwd !== undefined && mapped.cwd === undefined) {
69
+ mapped.cwd = String(mapped.Cwd);
70
+ } else if (mapped.cwd === undefined && payload.cwd) {
71
+ mapped.cwd = String(payload.cwd);
72
+ }
73
+ return mapped;
74
+ }
75
+
76
+ if (lower === 'read_file' || lower === 'view_file') {
77
+ const targetPath = mapped.Path ?? mapped.AbsolutePath ?? mapped.path ?? mapped.file_path ?? '';
78
+ if (targetPath && mapped.file_path === undefined) {
79
+ mapped.file_path = String(targetPath);
80
+ }
81
+ const startRaw = mapped.StartLine ?? mapped.start_line ?? mapped.offset;
82
+ const endRaw = mapped.EndLine ?? mapped.end_line;
83
+ if (startRaw !== undefined && startRaw !== null) {
84
+ const startNum = Math.max(1, Math.floor(Number(startRaw) || 1));
85
+ if (mapped.offset === undefined) mapped.offset = startNum;
86
+ if (endRaw !== undefined && endRaw !== null && mapped.limit === undefined) {
87
+ const endNum = Math.floor(Number(endRaw) || startNum);
88
+ mapped.limit = Math.max(1, endNum - startNum + 1);
89
+ }
90
+ } else if (endRaw !== undefined && endRaw !== null && mapped.limit === undefined) {
91
+ const endNum = Math.max(1, Math.floor(Number(endRaw) || 1));
92
+ mapped.offset = 1;
93
+ mapped.limit = endNum;
94
+ }
95
+ return mapped;
96
+ }
97
+
98
+ if (
99
+ lower === 'write_file' ||
100
+ lower === 'write_to_file' ||
101
+ lower === 'edit_file' ||
102
+ lower === 'replace_file_content' ||
103
+ lower === 'multi_replace_file_content'
104
+ ) {
105
+ const targetPath =
106
+ mapped.Path ?? mapped.AbsolutePath ?? mapped.TargetFile ?? mapped.path ?? mapped.file_path ?? '';
107
+ if (targetPath && mapped.file_path === undefined) {
108
+ mapped.file_path = String(targetPath);
109
+ }
110
+ return mapped;
111
+ }
112
+
113
+ if (lower === 'grep_search') {
114
+ if (mapped.SearchPath !== undefined && mapped.path === undefined) {
115
+ mapped.path = String(mapped.SearchPath);
116
+ }
117
+ if (mapped.Query !== undefined && mapped.pattern === undefined) {
118
+ mapped.pattern = String(mapped.Query);
119
+ }
120
+ return mapped;
121
+ }
122
+
123
+ if (lower === 'find_by_name' || lower === 'list_dir') {
124
+ const dir = mapped.SearchDirectory ?? mapped.DirectoryPath ?? mapped.path;
125
+ if (dir !== undefined && mapped.path === undefined) {
126
+ mapped.path = String(dir);
127
+ }
128
+ if (mapped.Pattern !== undefined && mapped.pattern === undefined) {
129
+ mapped.pattern = String(mapped.Pattern);
130
+ }
131
+ return mapped;
132
+ }
133
+
134
+ if (lower === 'read_url_content') {
135
+ if (mapped.Url !== undefined && mapped.url === undefined) {
136
+ mapped.url = String(mapped.Url);
137
+ }
138
+ return mapped;
139
+ }
140
+
141
+ return mapped;
142
+ }
143
+
144
+ /**
145
+ * Normalizes a Google Antigravity hook payload into Burnoff's `CanonicalEvent`.
146
+ */
147
+ export function normalize(payload = {}, options = {}) {
148
+ if (payload && payload.__canonical === true && payload.client === CLIENT_ID) {
149
+ return payload;
150
+ }
151
+ const toolCall = payload.toolCall && typeof payload.toolCall === 'object' ? payload.toolCall : {};
152
+ const rawToolName = String(toolCall.name || payload.toolName || payload.tool_name || '');
153
+ const rawArgs =
154
+ toolCall.args && typeof toolCall.args === 'object'
155
+ ? { ...toolCall.args }
156
+ : payload.args && typeof payload.args === 'object'
157
+ ? { ...payload.args }
158
+ : {};
159
+ const toolInput = mapToolArgs(rawToolName, rawArgs, payload);
160
+ const canonicalToolName = mapToolName(rawToolName, rawArgs);
161
+
162
+ const firstWorkspace = Array.isArray(payload.workspacePaths) && payload.workspacePaths[0]
163
+ ? String(payload.workspacePaths[0])
164
+ : '';
165
+ const cwd = String(payload.cwd || firstWorkspace || options.cwd || '');
166
+ const hasErrorStr = typeof payload.error === 'string' && payload.error.trim().length > 0;
167
+
168
+ return {
169
+ __canonical: true,
170
+ client: CLIENT_ID,
171
+ hookEventName: String(payload.hookEventName || payload.hook_event_name || ''),
172
+ sessionId: String(payload.conversationId || payload.sessionId || payload.session_id || 'default'),
173
+ cwd,
174
+ toolName: canonicalToolName,
175
+ rawToolName,
176
+ toolInput,
177
+ rawArgs,
178
+ toolUseId: String(toolCall.id || payload.toolUseId || payload.tool_use_id || ''),
179
+ model: String(payload.modelName || (typeof payload.model === 'string' ? payload.model : payload.model?.id) || ''),
180
+ lastUserInput: String(payload.lastUserInput || payload.prompt || ''),
181
+ transcriptPath: String(payload.transcriptPath || payload.transcript_path || ''),
182
+ failed: hasErrorStr || payload.isError === true || payload.is_error === true,
183
+ raw: payload
184
+ };
185
+ }
186
+
187
+ /**
188
+ * Renders a `PreToolUse` engine result into Antigravity's JSON stdout contract.
189
+ * Always exits with code 0 and never emits `hookSpecificOutput`.
190
+ */
191
+ export function renderPre(engineResult = {}) {
192
+ const verdict = engineResult.verdict || null;
193
+
194
+ if (engineResult.exitCode === 2 || verdict?.decision === 'deny') {
195
+ const reason = String(engineResult.stderr || verdict?.reason || 'Blocked by Burnoff guardrail').trim();
196
+ return {
197
+ ...engineResult,
198
+ exitCode: 0,
199
+ stdout: JSON.stringify({ decision: 'deny', reason }),
200
+ stderr: ''
201
+ };
202
+ }
203
+
204
+ if (verdict?.decision === 'ask' || verdict?.decision === 'force_ask') {
205
+ const decision = verdict.decision === 'force_ask' ? 'force_ask' : 'ask';
206
+ const reason = String(verdict?.reason || 'Requires user confirmation').trim();
207
+ return {
208
+ ...engineResult,
209
+ exitCode: 0,
210
+ stdout: JSON.stringify({ decision, reason }),
211
+ stderr: ''
212
+ };
213
+ }
214
+
215
+ if (
216
+ verdict?.updatedInput &&
217
+ (verdict.updatedInput.offset !== undefined || verdict.updatedInput.limit !== undefined)
218
+ ) {
219
+ const startLine = Math.max(1, Math.floor(Number(verdict.updatedInput.offset || 1)));
220
+ const limit = Math.max(1, Math.floor(Number(verdict.updatedInput.limit || 250)));
221
+ const endLine = startLine + limit - 1;
222
+ const out = {
223
+ decision: 'allow',
224
+ overwrite: {
225
+ StartLine: startLine,
226
+ EndLine: endLine
227
+ }
228
+ };
229
+ if (verdict.reason) {
230
+ out.reason = String(verdict.reason).trim();
231
+ }
232
+ return {
233
+ ...engineResult,
234
+ exitCode: 0,
235
+ stdout: JSON.stringify(out),
236
+ stderr: ''
237
+ };
238
+ }
239
+
240
+ const out = { decision: 'allow' };
241
+ const advisory = verdict?.additionalContext || verdict?.reason;
242
+ if (advisory) {
243
+ out.reason = String(advisory).trim();
244
+ }
245
+ return {
246
+ ...engineResult,
247
+ exitCode: 0,
248
+ stdout: JSON.stringify(out),
249
+ stderr: ''
250
+ };
251
+ }
252
+
253
+ /**
254
+ * Renders a `PostToolUse` result into Antigravity's `{}` stdout contract.
255
+ */
256
+ export function renderPost(engineResult = {}) {
257
+ return {
258
+ ...engineResult,
259
+ exitCode: 0,
260
+ stdout: '{}',
261
+ stderr: ''
262
+ };
263
+ }
264
+
265
+ /**
266
+ * Renders a fail-open JSON response on internal hook faults so Antigravity receives valid JSON.
267
+ */
268
+ export function renderFailOpen(reason, hookEventName = 'PreToolUse') {
269
+ const msg = String(reason || 'Unexpected hook diagnostic').trim();
270
+ const stdout = hookEventName === 'PostToolUse' ? '{}' : JSON.stringify({ decision: 'allow' });
271
+ return {
272
+ exitCode: 0,
273
+ stdout,
274
+ stderr: `[Burnoff ${hookEventName} Diagnostic] ${msg}\n`
275
+ };
276
+ }
277
+
278
+ export default {
279
+ CLIENT_ID,
280
+ detect,
281
+ normalize,
282
+ renderPre,
283
+ renderPost,
284
+ renderFailOpen
285
+ };
@@ -0,0 +1,180 @@
1
+ /**
2
+ * @file src/clients/claude-code.mjs
3
+ * Claude Code hook adapter: normalizes Claude Code `stdin` payloads into Burnoff's
4
+ * canonical event shape and renders verdicts in Claude Code's exit-code/JSON contract.
5
+ */
6
+
7
+ export const CLIENT_ID = 'claude-code';
8
+
9
+ /**
10
+ * Returns true if the payload resembles a Claude Code hook event.
11
+ */
12
+ export function detect(payload = {}) {
13
+ if (!payload || typeof payload !== 'object') return false;
14
+ if (payload.toolCall && typeof payload.toolCall === 'object') return false;
15
+ if (payload.conversationId || Array.isArray(payload.workspacePaths)) return false;
16
+ return Boolean(
17
+ payload.tool_name ||
18
+ payload.toolName ||
19
+ payload.session_id ||
20
+ payload.sessionId ||
21
+ payload.hook_event_name
22
+ );
23
+ }
24
+
25
+ /**
26
+ * Normalizes a Claude Code hook payload into Burnoff's `CanonicalEvent`.
27
+ */
28
+ export function normalize(payload = {}, options = {}) {
29
+ if (payload && payload.__canonical === true && payload.client === CLIENT_ID) {
30
+ return payload;
31
+ }
32
+ const hookEventName = String(payload.hook_event_name || payload.hookEventName || '');
33
+ const rawToolName = String(payload.tool_name || payload.toolName || '');
34
+ const toolInput =
35
+ payload.tool_input && typeof payload.tool_input === 'object'
36
+ ? payload.tool_input
37
+ : payload.toolInput && typeof payload.toolInput === 'object'
38
+ ? payload.toolInput
39
+ : payload.args && typeof payload.args === 'object'
40
+ ? payload.args
41
+ : {};
42
+ const model =
43
+ typeof payload.model === 'string'
44
+ ? payload.model
45
+ : payload.model?.id || payload.model?.model_id || payload.modelId || payload.model_id || '';
46
+
47
+ return {
48
+ __canonical: true,
49
+ client: CLIENT_ID,
50
+ hookEventName,
51
+ sessionId: String(payload.session_id || payload.sessionId || 'default'),
52
+ cwd: String(payload.cwd || options.cwd || ''),
53
+ toolName: rawToolName,
54
+ rawToolName,
55
+ toolInput,
56
+ rawArgs: toolInput,
57
+ toolUseId: String(payload.tool_use_id || payload.toolUseId || payload.turn_id || payload.turnId || ''),
58
+ agentId: payload.agent_id ?? payload.agentId ?? null,
59
+ parentToolUseId: payload.parent_tool_use_id ?? payload.parentToolUseId ?? null,
60
+ isSidechain: Boolean(payload.isSidechain ?? payload.is_sidechain),
61
+ model: String(model || ''),
62
+ lastUserInput: String(payload.prompt || payload.lastUserInput || ''),
63
+ transcriptPath: String(payload.transcript_path || payload.transcriptPath || ''),
64
+ failed: hookEventName === 'PostToolUseFailure' ? true : undefined,
65
+ raw: payload
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Renders a `PreToolUse` engine result into Claude Code's stdout/stderr/exitCode contract.
71
+ */
72
+ export function renderPre(engineResult = {}) {
73
+ const verdict = engineResult.verdict || null;
74
+ if (engineResult.exitCode === 2 || verdict?.decision === 'deny') {
75
+ const reason = String(engineResult.stderr || verdict?.reason || 'Blocked by Burnoff guardrail').trim();
76
+ return {
77
+ ...engineResult,
78
+ exitCode: 2,
79
+ stdout: '',
80
+ stderr: reason
81
+ };
82
+ }
83
+
84
+ if (engineResult.stdout) {
85
+ return {
86
+ ...engineResult,
87
+ exitCode: 0,
88
+ stderr: ''
89
+ };
90
+ }
91
+
92
+ if (verdict?.decision === 'ask') {
93
+ const askOut = {
94
+ hookSpecificOutput: {
95
+ hookEventName: 'PreToolUse',
96
+ permissionDecision: 'ask',
97
+ permissionDecisionReason: String(verdict.reason || 'Requires confirmation').trim()
98
+ }
99
+ };
100
+ return {
101
+ ...engineResult,
102
+ exitCode: 0,
103
+ stdout: JSON.stringify(askOut),
104
+ stderr: ''
105
+ };
106
+ }
107
+
108
+ if (verdict?.updatedInput) {
109
+ const allowOut = {
110
+ hookSpecificOutput: {
111
+ hookEventName: 'PreToolUse',
112
+ permissionDecision: 'allow',
113
+ updatedInput: verdict.updatedInput,
114
+ ...(verdict.reason ? { additionalContext: verdict.reason } : {})
115
+ }
116
+ };
117
+ return {
118
+ ...engineResult,
119
+ exitCode: 0,
120
+ stdout: JSON.stringify(allowOut),
121
+ stderr: ''
122
+ };
123
+ }
124
+
125
+ if (verdict?.additionalContext || verdict?.reason) {
126
+ const advOut = {
127
+ hookSpecificOutput: {
128
+ hookEventName: 'PreToolUse',
129
+ permissionDecision: 'allow',
130
+ additionalContext: String(verdict.additionalContext || verdict.reason)
131
+ }
132
+ };
133
+ return {
134
+ ...engineResult,
135
+ exitCode: 0,
136
+ stdout: JSON.stringify(advOut),
137
+ stderr: ''
138
+ };
139
+ }
140
+
141
+ return {
142
+ ...engineResult,
143
+ exitCode: 0,
144
+ stdout: '',
145
+ stderr: ''
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Renders a `PostToolUse` engine result into Claude Code's stdout/stderr/exitCode contract.
151
+ */
152
+ export function renderPost(engineResult = {}) {
153
+ return {
154
+ ...engineResult,
155
+ exitCode: 0,
156
+ stdout: engineResult.stdout || '',
157
+ stderr: ''
158
+ };
159
+ }
160
+
161
+ /**
162
+ * Renders a fail-open diagnostic response on internal hook errors.
163
+ */
164
+ export function renderFailOpen(reason, hookEventName = 'PreToolUse') {
165
+ const msg = String(reason || 'Unexpected hook diagnostic').trim();
166
+ return {
167
+ exitCode: 0,
168
+ stdout: '',
169
+ stderr: `[Burnoff ${hookEventName} Diagnostic] ${msg}\n`
170
+ };
171
+ }
172
+
173
+ export default {
174
+ CLIENT_ID,
175
+ detect,
176
+ normalize,
177
+ renderPre,
178
+ renderPost,
179
+ renderFailOpen
180
+ };
@@ -0,0 +1,64 @@
1
+ /**
2
+ * @file src/clients/detect.mjs
3
+ * Client detection and normalization dispatcher for Burnoff hook adapters.
4
+ */
5
+
6
+ import claudeCodeAdapter from './claude-code.mjs';
7
+ import antigravityAdapter from './antigravity.mjs';
8
+
9
+ function parseClientName(raw) {
10
+ const s = String(raw || '').trim().toLowerCase();
11
+ if (!s) return '';
12
+ if (s === 'antigravity' || s === 'ag') return 'antigravity';
13
+ if (s === 'claude' || s === 'claude-code' || s === 'claudecode') return 'claude-code';
14
+ return '';
15
+ }
16
+
17
+ /**
18
+ * Detects the active host client (`'antigravity'` or `'claude-code'`) from `options.client`,
19
+ * `BURNOFF_CLIENT` environment variable, or payload shape.
20
+ */
21
+ export function detectClient(payload = {}, options = {}) {
22
+ const explicit = parseClientName(options?.client);
23
+ if (explicit) return explicit;
24
+
25
+ if (payload && payload.__canonical === true && payload.client) {
26
+ const fromCanonical = parseClientName(payload.client);
27
+ if (fromCanonical) return fromCanonical;
28
+ }
29
+
30
+ const envClient = parseClientName(globalThis.process?.env?.BURNOFF_CLIENT);
31
+ if (envClient) return envClient;
32
+
33
+ if (antigravityAdapter.detect(payload)) {
34
+ return antigravityAdapter.CLIENT_ID;
35
+ }
36
+ return claudeCodeAdapter.CLIENT_ID;
37
+ }
38
+
39
+ /**
40
+ * Returns the adapter module matching a client name or raw hook payload.
41
+ */
42
+ export function getClientAdapter(clientOrPayload = {}, options = {}) {
43
+ const client =
44
+ typeof clientOrPayload === 'string'
45
+ ? parseClientName(clientOrPayload) || claudeCodeAdapter.CLIENT_ID
46
+ : detectClient(clientOrPayload, options);
47
+ return client === antigravityAdapter.CLIENT_ID ? antigravityAdapter : claudeCodeAdapter;
48
+ }
49
+
50
+ /**
51
+ * Detects the host client and normalizes a raw `stdin` hook payload into `CanonicalEvent`.
52
+ */
53
+ export function normalizeHookEvent(payload = {}, options = {}) {
54
+ const client = detectClient(payload, options);
55
+ const adapter = getClientAdapter(client);
56
+ const canonical = adapter.normalize(payload, options);
57
+ return { client, adapter, canonical };
58
+ }
59
+
60
+ export default {
61
+ detectClient,
62
+ getClientAdapter,
63
+ normalizeHookEvent
64
+ };
@@ -528,6 +528,7 @@ export function resolveEffectiveRates(modelId = 'claude-sonnet-5-5', totalPrompt
528
528
  preCliffWarningTriggered: false,
529
529
  cliffThresholdTokens: null,
530
530
  cliffMultiplier: 1.0,
531
+ outputIncludesThinking: true,
531
532
  advisory: spec.advisory || formatUnknownModelAdvisory(modelId)
532
533
  };
533
534
  }
@@ -581,7 +582,8 @@ export function resolveEffectiveRates(modelId = 'claude-sonnet-5-5', totalPrompt
581
582
  cliffThresholdTokens: cliff ? cliff.thresholdTokens : null,
582
583
  cliffMultiplier: cliffTriggered ? cliff.multiplier : 1.0,
583
584
  cliffCachedReadMultiplier: cliffTriggered ? (cliff.cachedReadMultiplier ?? cliff.multiplier) : 1.0,
584
- cliffOutputMultiplier: cliffTriggered ? (cliff.outputMultiplier ?? cliff.multiplier) : 1.0
585
+ cliffOutputMultiplier: cliffTriggered ? (cliff.outputMultiplier ?? cliff.multiplier) : 1.0,
586
+ outputIncludesThinking: spec.outputIncludesThinking !== false
585
587
  };
586
588
  }
587
589
 
@@ -598,6 +600,11 @@ export function calculateTurnCostUSD(usage = {}, options = {}) {
598
600
 
599
601
  const rawModel = usage.model || usage.modelId || 'claude-sonnet-5-5';
600
602
  const rates = resolveEffectiveRates(rawModel, totalPromptTokens, options);
603
+ const includesThinking =
604
+ usage.outputIncludesThinking !== undefined
605
+ ? Boolean(usage.outputIncludesThinking)
606
+ : rates.outputIncludesThinking !== false;
607
+ const billedOutputTokens = includesThinking ? outputTokens : outputTokens + thinkingTokens;
601
608
 
602
609
  if (rates.unknownModel) {
603
610
  return {
@@ -615,7 +622,7 @@ export function calculateTurnCostUSD(usage = {}, options = {}) {
615
622
  totalPrompt: totalPromptTokens,
616
623
  output: outputTokens,
617
624
  thinking: thinkingTokens,
618
- totalOutput: outputTokens + thinkingTokens
625
+ totalOutput: billedOutputTokens
619
626
  },
620
627
  costsUSD: {
621
628
  uncachedInput: null,
@@ -638,7 +645,7 @@ export function calculateTurnCostUSD(usage = {}, options = {}) {
638
645
  const write5mCostUSD = (write5mTokens / 1_000_000) * rates.write5mPer1M;
639
646
  const write1hCostUSD = (write1hTokens / 1_000_000) * rates.write1hPer1M;
640
647
  const readCostUSD = (cacheReadTokens / 1_000_000) * rates.readPer1M;
641
- const outputCostUSD = ((outputTokens + thinkingTokens) / 1_000_000) * rates.outputPer1M;
648
+ const outputCostUSD = (billedOutputTokens / 1_000_000) * rates.outputPer1M;
642
649
 
643
650
  const actualCacheSpendUSD = write5mCostUSD + write1hCostUSD + readCostUSD;
644
651
  const uncachedCacheEquivalentUSD = ((totalCacheWriteTokens + cacheReadTokens) / 1_000_000) * rates.inputPer1M;
@@ -660,7 +667,7 @@ export function calculateTurnCostUSD(usage = {}, options = {}) {
660
667
  totalPrompt: totalPromptTokens,
661
668
  output: outputTokens,
662
669
  thinking: thinkingTokens,
663
- totalOutput: outputTokens + thinkingTokens
670
+ totalOutput: billedOutputTokens
664
671
  },
665
672
  costsUSD: {
666
673
  uncachedInput: Number(inputCostUSD.toFixed(6)),
@@ -1,3 +1,4 @@
1
+ import crypto from 'node:crypto';
1
2
  import fs from 'node:fs';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
@@ -89,14 +90,17 @@ export function getHomeDir() {
89
90
 
90
91
  /**
91
92
  * Resolves `~/.burnoff/` (or `BURNOFF_HOME` override) dynamically on every call.
93
+ * Explicit `homeDirOverride` takes precedence over `process.env.BURNOFF_HOME`.
92
94
  */
93
95
  export function getBurnoffHomeDir(homeDirOverride = null) {
96
+ if (typeof homeDirOverride === 'string' && homeDirOverride.trim()) {
97
+ return path.join(path.resolve(homeDirOverride.trim()), '.burnoff');
98
+ }
94
99
  const envOverride = typeof process !== 'undefined' && process.env?.BURNOFF_HOME
95
100
  ? String(process.env.BURNOFF_HOME).trim()
96
101
  : '';
97
102
  if (envOverride) return path.resolve(envOverride);
98
- const home = homeDirOverride || getHomeDir();
99
- return path.join(home, '.burnoff');
103
+ return path.join(getHomeDir(), '.burnoff');
100
104
  }
101
105
 
102
106
  export function getBurnoffCacheDir(homeDirOverride = null) {
@@ -115,11 +119,64 @@ export function getBurnoffRunDir(homeDirOverride = null) {
115
119
  return path.join(getBurnoffHomeDir(homeDirOverride), 'run');
116
120
  }
117
121
 
122
+ /**
123
+ * Computes a deterministic 10-char SHA-1 workspace hash matching IPC pipe naming.
124
+ */
125
+ export function getWorkspaceHash(cwd = process.cwd()) {
126
+ const wsTarget = path.resolve(String(cwd || process.cwd()));
127
+ return crypto.createHash('sha1').update(wsTarget.toLowerCase()).digest('hex').slice(0, 10);
128
+ }
129
+
130
+ /**
131
+ * Resolves `~/.burnoff/state/<wshash>/` for per-workspace runtime state isolation.
132
+ */
133
+ export function getWorkspaceStateDir(cwd = process.cwd(), homeDirOverride = null) {
134
+ return path.join(getBurnoffHomeDir(homeDirOverride), 'state', getWorkspaceHash(cwd));
135
+ }
136
+
118
137
  export function getClaudeProjectsDir(homeDirOverride = null) {
119
138
  const home = homeDirOverride || getHomeDir();
120
139
  return path.join(home, '.claude', 'projects');
121
140
  }
122
141
 
142
+ /**
143
+ * Resolves Google Antigravity configuration, rules, MCP, and transcript paths for a workspace.
144
+ */
145
+ export function resolveAntigravityConfigPaths({
146
+ homeDir = getHomeDir(),
147
+ cwd = process.cwd(),
148
+ platform = process.platform
149
+ } = {}) {
150
+ const resolvedHome = homeDir || getHomeDir();
151
+ const resolvedCwd = path.resolve(cwd || process.cwd());
152
+ const geminiConfigDir = path.join(resolvedHome, '.gemini', 'config');
153
+ const geminiRootDir = path.join(resolvedHome, '.gemini');
154
+ return {
155
+ homeDir: resolvedHome,
156
+ cwd: resolvedCwd,
157
+ platform,
158
+ geminiConfigDir,
159
+ userHooksJson: path.join(geminiConfigDir, 'hooks.json'),
160
+ userMcpJson: path.join(geminiConfigDir, 'mcp_config.json'),
161
+ projectAgentsDir: path.join(resolvedCwd, '.agents'),
162
+ projectHooksJson: path.join(resolvedCwd, '.agents', 'hooks.json'),
163
+ projectMcpJson: path.join(resolvedCwd, '.agents', 'mcp_config.json'),
164
+ projectRulesDir: path.join(resolvedCwd, '.agents', 'rules'),
165
+ globalRulesDir: path.join(geminiConfigDir, 'rules'),
166
+ brainDirs: [
167
+ path.join(geminiRootDir, 'antigravity', 'brain'),
168
+ path.join(geminiRootDir, 'antigravity-cli', 'brain'),
169
+ path.join(geminiRootDir, 'antigravity-ide', 'brain')
170
+ ],
171
+ rulesFiles: [
172
+ path.join(geminiConfigDir, 'GEMINI.md'),
173
+ path.join(geminiConfigDir, 'AGENTS.md'),
174
+ path.join(resolvedCwd, 'GEMINI.md'),
175
+ path.join(resolvedCwd, 'AGENTS.md')
176
+ ]
177
+ };
178
+ }
179
+
123
180
  /**
124
181
  * Resolves Claude Code configuration, rules, MCP, and transcript paths for a workspace.
125
182
  */
@@ -218,8 +275,11 @@ export default {
218
275
  getBurnoffRuntimeDir,
219
276
  getBurnoffLedgerDir,
220
277
  getBurnoffRunDir,
278
+ getWorkspaceHash,
279
+ getWorkspaceStateDir,
221
280
  getClaudeProjectsDir,
222
281
  resolveClaudeConfigPaths,
282
+ resolveAntigravityConfigPaths,
223
283
  ensureDirSync,
224
284
  formatNodeUpgradeHint,
225
285
  ensureSupportedNodeVersion