burnoff 1.4.1 → 2.1.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 (62) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.github/workflows/burnoff-pr-gate.yml +5 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +2 -2
  4. package/CHANGELOG.md +74 -0
  5. package/README.md +187 -213
  6. package/SECURITY.md +38 -0
  7. package/bin/burnoff.mjs +307 -32
  8. package/commands/burnoff.md +6 -4
  9. package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
  10. package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
  11. package/hooks/hook-io.mjs +216 -11
  12. package/hooks/hooks.json +44 -0
  13. package/hooks/post-tool-use.mjs +3 -1
  14. package/hooks/pre-tool-use.mjs +47 -8
  15. package/hooks/session-lifecycle.mjs +24 -3
  16. package/hooks/user-prompt-submit.mjs +98 -0
  17. package/package.json +6 -4
  18. package/scripts/bench-hooks.mjs +34 -3
  19. package/scripts/bench-savings.mjs +318 -0
  20. package/scripts/burnoff-statusline.mjs +138 -6
  21. package/src/ci/ci-gate.mjs +199 -13
  22. package/src/ci/pr-cost.mjs +417 -45
  23. package/src/ci/pr-summary.mjs +467 -0
  24. package/src/cli/audit.mjs +179 -28
  25. package/src/cli/doctor.mjs +32 -6
  26. package/src/cli/hook-health.mjs +9 -1
  27. package/src/cli/init.mjs +226 -39
  28. package/src/cli/preview.mjs +299 -0
  29. package/src/cli/startup-audit/formatter.mjs +248 -0
  30. package/src/cli/startup-audit/jsonc.mjs +601 -0
  31. package/src/cli/startup-audit/mcp-audit.mjs +735 -0
  32. package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
  33. package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
  34. package/src/cli/startup-audit.mjs +451 -2471
  35. package/src/clients/claude-code.mjs +41 -4
  36. package/src/config/catalog.json +295 -0
  37. package/src/config/effort.mjs +145 -0
  38. package/src/config/harness-quirks.mjs +340 -0
  39. package/src/config/loader.mjs +27 -2
  40. package/src/config/policy.mjs +81 -9
  41. package/src/config/pricing.mjs +247 -19
  42. package/src/config/semver.mjs +25 -0
  43. package/src/config/uncached-attribution.mjs +280 -41
  44. package/src/guards/compaction-baton.mjs +248 -0
  45. package/src/guards/loop-breaker.mjs +328 -47
  46. package/src/guards/model-switch-hook.mjs +126 -0
  47. package/src/guards/phase5-detectors.mjs +275 -21
  48. package/src/guards/post-tool-engine.mjs +333 -11
  49. package/src/guards/pre-tool-engine.mjs +607 -45
  50. package/src/guards/prefix-guard.mjs +609 -0
  51. package/src/guards/prompt-guard.mjs +309 -0
  52. package/src/guards/read-clamp.mjs +192 -8
  53. package/src/guards/session-hook.mjs +149 -7
  54. package/src/guards/shell-guard.mjs +56 -5
  55. package/src/guards/snooze.mjs +169 -5
  56. package/src/ipc/daemon.mjs +76 -0
  57. package/src/ipc/fast-client.mjs +165 -4
  58. package/src/ipc/protocol.mjs +16 -3
  59. package/src/storage/antigravity-parser.mjs +16 -2
  60. package/src/storage/file-lock.mjs +16 -3
  61. package/src/storage/jsonl-parser.mjs +133 -22
  62. package/src/storage/telemetry-metrics.mjs +254 -4
@@ -9,6 +9,12 @@ import path from 'node:path';
9
9
  import os from 'node:os';
10
10
  import net from 'node:net';
11
11
  import crypto from 'node:crypto';
12
+ import { spawn } from 'node:child_process';
13
+ import { fileURLToPath } from 'node:url';
14
+
15
+ const __ipcClientDir = path.dirname(fileURLToPath(import.meta.url));
16
+ const AUTO_DAEMON_COOLDOWN_MS = 30_000;
17
+ const POSIX_MAX_SOCK_BYTES = 100;
12
18
 
13
19
  function normalizeHomePath(raw = '') {
14
20
  return String(raw || '').trim().replace(/\\/g, '/').replace(/\/+$/, '');
@@ -46,10 +52,11 @@ export function resolveFastIpcPipePath(options = {}) {
46
52
  return String(options.ipcPath || process.env.BURNOFF_IPC_PATH);
47
53
  }
48
54
 
55
+ const platform = options.platform || process.platform;
49
56
  const wsTarget = path.resolve(options.cwd || process.cwd());
50
57
  const wsHash = crypto.createHash('sha1').update(wsTarget.toLowerCase()).digest('hex').slice(0, 10);
51
58
 
52
- if (process.platform === 'win32') {
59
+ if (platform === 'win32') {
53
60
  let rawUser = process.env.USERNAME || process.env.USER;
54
61
  if (!rawUser) {
55
62
  try {
@@ -68,7 +75,17 @@ export function resolveFastIpcPipePath(options = {}) {
68
75
  : process.env.BURNOFF_HOME
69
76
  ? path.resolve(process.env.BURNOFF_HOME)
70
77
  : path.join(process.env.HOME || os.homedir() || '/tmp', '.burnoff');
71
- return path.join(burnoffHome, 'run', `daemon-${wsHash}.sock`);
78
+ const runDir = path.join(burnoffHome, 'run');
79
+ const candidate = path.join(runDir, `daemon-${wsHash}.sock`);
80
+ if (Buffer.byteLength(candidate, 'utf8') <= POSIX_MAX_SOCK_BYTES) {
81
+ return candidate;
82
+ }
83
+ const sockHash = crypto
84
+ .createHash('sha1')
85
+ .update(`${runDir}\0${wsHash}`)
86
+ .digest('hex')
87
+ .slice(0, 16);
88
+ return path.posix.join('/tmp', `bo-${sockHash}.sock`);
72
89
  }
73
90
 
74
91
  function isPidAliveFast(pid) {
@@ -102,7 +119,13 @@ function sendRawDaemonRpc(method, params = {}, options = {}) {
102
119
  if (!options.ipcPath && !options.homeDir && !process.env.BURNOFF_IPC_PATH && !isRealHostHomeEnv()) {
103
120
  return Promise.resolve(null);
104
121
  }
105
- const derivedCwd = options.cwd || params?.event?.cwd || params?.input?.cwd || params?.cwd;
122
+ // Antigravity payloads carry the workspace in workspacePaths[0] / workspacePath rather than cwd.
123
+ const eventWs =
124
+ Array.isArray(params?.event?.workspacePaths) && params.event.workspacePaths[0]
125
+ ? String(params.event.workspacePaths[0])
126
+ : params?.event?.workspacePath;
127
+ const derivedCwd =
128
+ options.cwd || params?.event?.cwd || eventWs || params?.input?.cwd || params?.cwd;
106
129
  const effectiveOptions = derivedCwd ? { ...options, cwd: derivedCwd } : options;
107
130
  const pipePath = resolveFastIpcPipePath(effectiveOptions);
108
131
  if (!pipePath) {
@@ -246,10 +269,148 @@ export async function tryFastDaemonRpc(method, params = {}, options = {}) {
246
269
  return result && result.fullVerdict === true ? result : null;
247
270
  }
248
271
 
272
+ function resolveAutoDaemonSpawnGuardPath(options = {}) {
273
+ const wsTarget = path.resolve(options.cwd || process.cwd());
274
+ const wsHash = crypto.createHash('sha1').update(wsTarget.toLowerCase()).digest('hex').slice(0, 10);
275
+ const burnoffHome = options.homeDir
276
+ ? path.join(path.resolve(options.homeDir), '.burnoff')
277
+ : process.env.BURNOFF_HOME
278
+ ? path.resolve(process.env.BURNOFF_HOME)
279
+ : path.join(process.env.USERPROFILE || process.env.HOME || os.homedir() || '/tmp', '.burnoff');
280
+ return path.join(burnoffHome, 'run', `daemon-spawn-${wsHash}.lock`);
281
+ }
282
+
283
+ function isAutoDaemonDisabledInPolicy(cwd) {
284
+ if (!cwd) return false;
285
+ for (const name of ['.burnoff.yaml', '.burnoff.yml']) {
286
+ const p = path.join(cwd, name);
287
+ try {
288
+ if (!fs.existsSync(p)) continue;
289
+ const text = fs.readFileSync(p, 'utf8');
290
+ if (/^\s*autoStart\s*:\s*false\b/m.test(text)) return true;
291
+ return false;
292
+ } catch {
293
+ return false; // ignore: unreadable policy does not disable auto-daemon
294
+ }
295
+ }
296
+ return false;
297
+ }
298
+
299
+ /**
300
+ * Fires off a detached background Burnoff IPC daemon when none is running for the workspace.
301
+ * Throttled via a 30-second guard file so parallel hooks never spawn duplicate daemons.
302
+ */
303
+ export function maybeSpawnAutoDaemon(options = {}) {
304
+ try {
305
+ if (options.autoStart === false) return { spawned: false, reason: 'option_disabled' };
306
+ if (process.env.BURNOFF_NO_AUTO_DAEMON === '1') return { spawned: false, reason: 'env_disabled' };
307
+ if (process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true') {
308
+ return { spawned: false, reason: 'ci_disabled' };
309
+ }
310
+ if (!options.ipcPath && !options.homeDir && !process.env.BURNOFF_IPC_PATH && !isRealHostHomeEnv()) {
311
+ return { spawned: false, reason: 'sandboxed_home' };
312
+ }
313
+ if ((options.ipcPath || process.env.BURNOFF_IPC_PATH) && !options.allowExplicitIpc) {
314
+ return { spawned: false, reason: 'explicit_ipc_override' };
315
+ }
316
+
317
+ const cwd = path.resolve(options.cwd || process.cwd());
318
+ if (isAutoDaemonDisabledInPolicy(cwd)) {
319
+ return { spawned: false, reason: 'policy_disabled' };
320
+ }
321
+
322
+ const pipePath = resolveFastIpcPipePath({ ...options, cwd });
323
+ if (process.platform === 'win32') {
324
+ if (!options.ipcPath && !process.env.BURNOFF_IPC_PATH) {
325
+ const markerPath = resolveFastDaemonMarkerPath({ ...options, cwd });
326
+ if (markerPath && fs.existsSync(markerPath)) {
327
+ try {
328
+ const parsed = JSON.parse(fs.readFileSync(markerPath, 'utf8'));
329
+ if (isPidAliveFast(parsed?.pid)) {
330
+ return { spawned: false, reason: 'already_running' };
331
+ }
332
+ } catch {
333
+ // ignore: stale marker falls through to spawn
334
+ }
335
+ }
336
+ }
337
+ } else if (pipePath && fs.existsSync(pipePath)) {
338
+ return { spawned: false, reason: 'already_running' };
339
+ }
340
+
341
+ const guardPath = options.spawnGuardPath || resolveAutoDaemonSpawnGuardPath({ ...options, cwd });
342
+ fs.mkdirSync(path.dirname(guardPath), { recursive: true });
343
+ const nowMs = Number(options.nowMs ?? Date.now());
344
+ const cooldownMs = Math.max(1000, Number(options.cooldownMs ?? AUTO_DAEMON_COOLDOWN_MS));
345
+
346
+ let acquiredGuard = false;
347
+ try {
348
+ const fd = fs.openSync(guardPath, 'wx', 0o600);
349
+ try {
350
+ fs.writeSync(fd, JSON.stringify({ pid: process.pid, ts: nowMs }));
351
+ } finally {
352
+ fs.closeSync(fd);
353
+ }
354
+ acquiredGuard = true;
355
+ } catch (err) {
356
+ if (err?.code === 'EEXIST') {
357
+ try {
358
+ const st = fs.statSync(guardPath);
359
+ if (nowMs - st.mtimeMs < cooldownMs) {
360
+ return { spawned: false, reason: 'cooldown_active' };
361
+ }
362
+ fs.unlinkSync(guardPath);
363
+ const fd2 = fs.openSync(guardPath, 'wx', 0o600);
364
+ try {
365
+ fs.writeSync(fd2, JSON.stringify({ pid: process.pid, ts: nowMs }));
366
+ } finally {
367
+ fs.closeSync(fd2);
368
+ }
369
+ acquiredGuard = true;
370
+ } catch {
371
+ return { spawned: false, reason: 'cooldown_race' };
372
+ }
373
+ }
374
+ }
375
+
376
+ if (!acquiredGuard) {
377
+ return { spawned: false, reason: 'guard_not_acquired' };
378
+ }
379
+
380
+ const cliEntry = options.cliEntry || path.resolve(__ipcClientDir, '../../bin/burnoff.mjs');
381
+ const spawnArgs = [cliEntry, 'daemon', 'start', '--foreground', '--cwd', cwd];
382
+ if (options.ipcPath || process.env.BURNOFF_IPC_PATH) {
383
+ spawnArgs.push('--ipc', String(options.ipcPath || process.env.BURNOFF_IPC_PATH));
384
+ }
385
+ if (options.homeDir) {
386
+ spawnArgs.push('--home', String(options.homeDir));
387
+ }
388
+ if (options.idleTimeoutMs !== undefined) {
389
+ spawnArgs.push('--idle-ms', String(options.idleTimeoutMs));
390
+ }
391
+
392
+ const spawnFn = options.spawnFn || spawn;
393
+ const child = spawnFn(process.execPath, spawnArgs, {
394
+ cwd: path.dirname(cliEntry),
395
+ env: options.env || process.env,
396
+ detached: true,
397
+ stdio: 'ignore',
398
+ windowsHide: true
399
+ });
400
+ if (child && typeof child.unref === 'function') {
401
+ child.unref();
402
+ }
403
+ return { spawned: true, pid: child?.pid || null, guardPath };
404
+ } catch {
405
+ return { spawned: false, reason: 'spawn_error' }; // ignore: auto-daemon warmup is best-effort
406
+ }
407
+ }
408
+
249
409
  export default {
250
410
  isRealHostHomeEnv,
251
411
  resolveFastIpcPipePath,
252
412
  resolveFastDaemonMarkerPath,
253
413
  sendDaemonRpc,
254
- tryFastDaemonRpc
414
+ tryFastDaemonRpc,
415
+ maybeSpawnAutoDaemon
255
416
  };
@@ -26,21 +26,25 @@ export const IPC_LIMITS = Object.freeze({
26
26
  DEFAULT_REQUEST_TIMEOUT_MS: 500
27
27
  });
28
28
 
29
+ export const POSIX_MAX_SOCK_BYTES = 100;
30
+
29
31
  /**
30
32
  * Resolves the workspace-scoped OS-specific local IPC transport address.
31
33
  * - Honors explicit `options.ipcPath` or `BURNOFF_IPC_PATH`.
32
34
  * - Win32: `\\.\pipe\burnoff-<cleanUser>-<wsHash>`
33
- * - POSIX: `<BURNOFF_HOME>/run/daemon-<wsHash>.sock`
35
+ * - POSIX: `<BURNOFF_HOME>/run/daemon-<wsHash>.sock` (falls back to `/tmp/bo-<hash>.sock`
36
+ * when the path exceeds 100 UTF-8 bytes to respect macOS's 104-byte `sun_path` cap)
34
37
  */
35
38
  export function resolveIpcPath(options = {}) {
36
39
  if (options.ipcPath || process.env.BURNOFF_IPC_PATH) {
37
40
  return String(options.ipcPath || process.env.BURNOFF_IPC_PATH);
38
41
  }
39
42
 
43
+ const platform = options.platform || process.platform;
40
44
  const wsTarget = path.resolve(options.cwd || process.cwd());
41
45
  const wsHash = crypto.createHash('sha1').update(wsTarget.toLowerCase()).digest('hex').slice(0, 10);
42
46
 
43
- if (process.platform === 'win32') {
47
+ if (platform === 'win32') {
44
48
  let rawUser = process.env.USERNAME || process.env.USER;
45
49
  if (!rawUser) {
46
50
  try {
@@ -54,7 +58,16 @@ export function resolveIpcPath(options = {}) {
54
58
  }
55
59
 
56
60
  const runDir = getBurnoffRunDir(options.homeDir || null);
57
- return path.join(runDir, `daemon-${wsHash}.sock`);
61
+ const candidate = path.join(runDir, `daemon-${wsHash}.sock`);
62
+ if (Buffer.byteLength(candidate, 'utf8') <= POSIX_MAX_SOCK_BYTES) {
63
+ return candidate;
64
+ }
65
+ const sockHash = crypto
66
+ .createHash('sha1')
67
+ .update(`${runDir}\0${wsHash}`)
68
+ .digest('hex')
69
+ .slice(0, 16);
70
+ return path.posix.join('/tmp', `bo-${sockHash}.sock`);
58
71
  }
59
72
 
60
73
  export function formatJsonRpcRequest(method, params = {}, id = null) {
@@ -7,6 +7,7 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { getHomeDir, resolveAntigravityConfigPaths } from '../config/paths.mjs';
10
+ import { readBoundedTailUtf8 } from './jsonl-parser.mjs';
10
11
 
11
12
  function unwrapQuotedArgString(val) {
12
13
  if (typeof val !== 'string') return val;
@@ -118,7 +119,7 @@ export function parseAntigravityTranscript(filePathOrContent = '', options = {})
118
119
  fs.existsSync(filePathOrContent)
119
120
  ) {
120
121
  resolvedPath = path.resolve(filePathOrContent);
121
- rawContent = fs.readFileSync(resolvedPath, 'utf8');
122
+ rawContent = readBoundedTailUtf8(resolvedPath, options.tailBytes);
122
123
  } else {
123
124
  rawContent = String(filePathOrContent || '');
124
125
  }
@@ -147,7 +148,20 @@ export function parseAntigravityTranscript(filePathOrContent = '', options = {})
147
148
  const freshInputTokens = Math.max(0, Number(entry.input_tokens ?? entry.inputTokens ?? 0));
148
149
  const cacheReadTokens = Math.max(0, Number(entry.cache_read_tokens ?? entry.cacheReadTokens ?? 0));
149
150
  const outputTokens = Math.max(0, Number(entry.output_tokens ?? entry.outputTokens ?? 0));
150
- const thinkingTokens = Math.max(0, Number(entry.thinking_tokens ?? entry.thinkingTokens ?? 0));
151
+ const thinkingTokens = Math.max(
152
+ 0,
153
+ Number(
154
+ entry.thinking_tokens ??
155
+ entry.thinkingTokens ??
156
+ entry.thoughtsTokenCount ??
157
+ entry.thoughts_token_count ??
158
+ entry.usageMetadata?.thoughtsTokenCount ??
159
+ entry.usageMetadata?.thoughts_token_count ??
160
+ entry.usage?.thoughtsTokenCount ??
161
+ entry.usage?.thoughts_token_count ??
162
+ 0
163
+ ) || 0
164
+ );
151
165
  const totalPromptTokens = freshInputTokens + cacheReadTokens;
152
166
  const model = entry.model ? String(entry.model) : lastModel;
153
167
  if (model) lastModel = model;
@@ -21,6 +21,10 @@ export const LOCK_ORDER_DOC = Object.freeze([
21
21
  const DEFAULT_MAX_WAIT_MS = 2500;
22
22
  const DEFAULT_STALE_MS = 5000;
23
23
  const MIN_STALE_MS = 5000;
24
+ // A holder whose PID is gone is only reaped once the lock is older than this grace window. Without it a
25
+ // waiter can read a live holder's lock, lose the race to the holder's release+exit, see a dead PID, and
26
+ // then reap the NEXT holder's fresh lock (two writers in the critical section => lost updates).
27
+ const PID_DEAD_GRACE_MS = 1000;
24
28
 
25
29
  function isPidAlive(pid) {
26
30
  const num = Number(pid);
@@ -42,7 +46,8 @@ function inspectLockFile(lockPath, staleMs, fsMod) {
42
46
  const pid = Number(parsed?.pid || 0);
43
47
  const ageMs = createdAtMs > 0 ? Date.now() - createdAtMs : Infinity;
44
48
  const staleByAge = ageMs > staleMs;
45
- const staleByPid = Number.isInteger(pid) && pid > 0 && !isPidAlive(pid);
49
+ const staleByPid =
50
+ Number.isInteger(pid) && pid > 0 && ageMs > PID_DEAD_GRACE_MS && !isPidAlive(pid);
46
51
  return {
47
52
  stale: staleByAge || staleByPid,
48
53
  pid,
@@ -61,7 +66,15 @@ function inspectLockFile(lockPath, staleMs, fsMod) {
61
66
  }
62
67
  }
63
68
 
64
- function tryReapStaleLock(lockPath, fsMod) {
69
+ function tryReapStaleLock(lockPath, fsMod, expectedNonce = null) {
70
+ if (expectedNonce) {
71
+ try {
72
+ const current = JSON.parse(fsMod.readFileSync(lockPath, 'utf8'));
73
+ if (current?.nonce !== expectedNonce) return false; // lock changed hands since inspection
74
+ } catch {
75
+ // ignore: unreadable lock falls through to the rename-based reap
76
+ }
77
+ }
65
78
  const reapPath = `${lockPath}.reap.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 6)}`;
66
79
  try {
67
80
  fsMod.renameSync(lockPath, reapPath);
@@ -138,7 +151,7 @@ export function withFileLockSync(targetPath, fn, options = {}) {
138
151
 
139
152
  const info = inspectLockFile(lockPath, staleMs, fsMod);
140
153
  if (info.stale) {
141
- if (tryReapStaleLock(lockPath, fsMod)) {
154
+ if (tryReapStaleLock(lockPath, fsMod, info.nonce)) {
142
155
  continue;
143
156
  }
144
157
  }
@@ -387,6 +387,33 @@ export function parseClaudeCodeJsonl(rawContent = '') {
387
387
  let latestShapeHash = null;
388
388
  let latestEntrypoint = dag.sessionEntrypoint || null;
389
389
  let latestToolsUsed = Array.isArray(dag.toolsUsed) ? [...dag.toolsUsed] : [];
390
+ let seenFirstMainThreadCall = false;
391
+ let pendingAppendedPositions = 0;
392
+ let lastAppendedBlockType = null;
393
+
394
+ const accumulateContentPositions = (rawMsgContent) => {
395
+ if (typeof rawMsgContent === 'string') {
396
+ if (rawMsgContent.trim()) {
397
+ pendingAppendedPositions += 1;
398
+ lastAppendedBlockType = 'text';
399
+ }
400
+ return;
401
+ }
402
+ if (!Array.isArray(rawMsgContent)) return;
403
+ for (const block of rawMsgContent) {
404
+ if (!block || typeof block !== 'object') continue;
405
+ const bType = String(block.type || 'text').toLowerCase();
406
+ if (bType === 'tool_use' || bType === 'tool_result') {
407
+ if (lastAppendedBlockType !== bType) {
408
+ pendingAppendedPositions += 1;
409
+ lastAppendedBlockType = bType;
410
+ }
411
+ } else {
412
+ pendingAppendedPositions += 1;
413
+ lastAppendedBlockType = bType;
414
+ }
415
+ }
416
+ };
390
417
 
391
418
  for (let i = 0; i < dag.activeBranchSteps.length; i++) {
392
419
  const node = dag.activeBranchSteps[i];
@@ -415,6 +442,8 @@ export function parseClaudeCodeJsonl(rawContent = '') {
415
442
  (node.type === 'system' && node.subtype === 'compact_boundary');
416
443
  if (isCompactionMarker) {
417
444
  pendingCompaction = true;
445
+ pendingAppendedPositions = 0;
446
+ lastAppendedBlockType = null;
418
447
  }
419
448
 
420
449
  const toolCalls = Array.isArray(node.tool_calls)
@@ -422,20 +451,38 @@ export function parseClaudeCodeJsonl(rawContent = '') {
422
451
  : (Array.isArray(node.toolCalls) ? [...node.toolCalls] : []);
423
452
  const textParts = [];
424
453
  let thinkingText = String(node.thinking || '');
454
+ let hasThinkingBlock = Boolean(node.thinking);
455
+ let visibleOutputChars = 0;
425
456
 
426
457
  const rawMsgContent = msg?.content ?? node.content;
427
458
  if (typeof rawMsgContent === 'string') {
428
459
  textParts.push(rawMsgContent);
460
+ visibleOutputChars += rawMsgContent.length;
429
461
  } else if (Array.isArray(rawMsgContent)) {
430
462
  for (const block of rawMsgContent) {
431
463
  if (!block || typeof block !== 'object') continue;
432
464
  if (block.type === 'text' && block.text) {
433
- textParts.push(String(block.text));
434
- } else if (block.type === 'thinking' && block.thinking) {
435
- thinkingText += (thinkingText ? '\n' : '') + String(block.thinking);
465
+ const textStr = String(block.text);
466
+ textParts.push(textStr);
467
+ visibleOutputChars += textStr.length;
468
+ } else if (block.type === 'thinking') {
469
+ hasThinkingBlock = true;
470
+ if (block.thinking) {
471
+ thinkingText += (thinkingText ? '\n' : '') + String(block.thinking);
472
+ }
473
+ } else if (block.type === 'redacted_thinking') {
474
+ hasThinkingBlock = true;
436
475
  } else if (block.type === 'tool_use') {
476
+ const toolName = block.name || 'tool_use';
477
+ let serializedInputLen = 2;
478
+ try {
479
+ serializedInputLen = JSON.stringify(block.input || block.args || {}).length;
480
+ } catch {
481
+ // ignore: circular tool input
482
+ }
483
+ visibleOutputChars += String(block.name || '').length + serializedInputLen;
437
484
  toolCalls.push({
438
- name: block.name || 'tool_use',
485
+ name: toolName,
439
486
  args: block.input || block.args || {}
440
487
  });
441
488
  } else if (block.type === 'tool_result') {
@@ -492,16 +539,39 @@ export function parseClaudeCodeJsonl(rawContent = '') {
492
539
  ? flatCacheCreationTokens
493
540
  : (cacheCreationEphemeral5mInputTokens + cacheCreationEphemeral1hInputTokens);
494
541
  const totalPromptTokens = inputTokens + cacheReadTokens + cacheCreationTokens;
495
- const hasExplicitThinkingTokens =
496
- node.thinking_tokens != null ||
497
- node.thinkingTokens != null ||
498
- usage.thinking_tokens != null;
499
- const thinkingTokens = Math.max(0, Number(
542
+ const explicitThinkingTokensRaw =
500
543
  node.thinking_tokens ??
501
544
  node.thinkingTokens ??
545
+ node.thoughtsTokenCount ??
546
+ node.thoughts_token_count ??
502
547
  usage.thinking_tokens ??
503
- (thinkingText ? Math.ceil(thinkingText.length / 4) : 0)
504
- ) || 0);
548
+ usage.thinkingTokens ??
549
+ usage.thoughtsTokenCount ??
550
+ usage.thoughts_token_count ??
551
+ node.usageMetadata?.thoughtsTokenCount ??
552
+ node.usageMetadata?.thoughts_token_count ??
553
+ usage.usageMetadata?.thoughtsTokenCount ??
554
+ usage.usageMetadata?.thoughts_token_count ??
555
+ usage.output_tokens_details?.thinking_tokens ??
556
+ usage.output_tokens_details?.reasoning_tokens ??
557
+ usage.completion_tokens_details?.reasoning_tokens ??
558
+ usage.reasoning_tokens ??
559
+ usage.reasoningTokens ??
560
+ null;
561
+ const hasExplicitThinkingTokens = explicitThinkingTokensRaw != null;
562
+ const isAssistantTurn = role === 'assistant' || node.type === 'assistant';
563
+ let thinkingTokens = 0;
564
+ let thinkingTokensEstimated = false;
565
+ let thinkingTokensSource = 'none';
566
+ if (hasExplicitThinkingTokens) {
567
+ thinkingTokens = Math.max(0, Number(explicitThinkingTokensRaw) || 0);
568
+ thinkingTokensSource = 'reported';
569
+ } else if (hasThinkingBlock && isAssistantTurn && outputTokens > 0) {
570
+ const visibleOutputTokensEst = Math.ceil(visibleOutputChars / 4);
571
+ thinkingTokens = Math.max(0, outputTokens - visibleOutputTokensEst);
572
+ thinkingTokensEstimated = thinkingTokens > 0;
573
+ thinkingTokensSource = thinkingTokens > 0 ? 'output_minus_visible_upper_bound' : 'none';
574
+ }
505
575
  const model = msg?.model || node.model || null;
506
576
  if (model) latestModel = model;
507
577
  const createdAt = node.firstChunkAt || node.timestamp || node.created_at || node.createdAt || null;
@@ -534,6 +604,18 @@ export function parseClaudeCodeJsonl(rawContent = '') {
534
604
  const systemSubtype = node.type === 'system' ? (node.subtype || null) : null;
535
605
  const stepToolsUsed = node.type === 'tools-used' && Array.isArray(node.tools) ? [...node.tools] : null;
536
606
  const stepEntrypoint = node.entrypoint ? String(node.entrypoint) : latestEntrypoint;
607
+ const isMainThread = !node.isSidechain;
608
+ let appendedPositionsSincePrevCall = 0;
609
+
610
+ if (hasUsage && isMainThread) {
611
+ appendedPositionsSincePrevCall = seenFirstMainThreadCall ? pendingAppendedPositions : 0;
612
+ pendingAppendedPositions = 0;
613
+ lastAppendedBlockType = null;
614
+ seenFirstMainThreadCall = true;
615
+ accumulateContentPositions(rawMsgContent);
616
+ } else if (!hasUsage && isMainThread && seenFirstMainThreadCall) {
617
+ accumulateContentPositions(rawMsgContent);
618
+ }
537
619
 
538
620
  if (hasUsage) {
539
621
  usageTurns.push({
@@ -554,7 +636,8 @@ export function parseClaudeCodeJsonl(rawContent = '') {
554
636
  isSidechain: Boolean(node.isSidechain),
555
637
  shapeHash: latestShapeHash || null,
556
638
  entrypoint: stepEntrypoint,
557
- cacheTtlTier
639
+ cacheTtlTier,
640
+ appendedPositionsSincePrevCall
558
641
  });
559
642
  }
560
643
 
@@ -585,7 +668,8 @@ export function parseClaudeCodeJsonl(rawContent = '') {
585
668
  totalPromptTokens,
586
669
  totalPromptEnvelopeTokens: totalPromptTokens,
587
670
  thinkingTokens,
588
- thinkingTokensEstimated: !hasExplicitThinkingTokens && thinkingTokens > 0,
671
+ thinkingTokensEstimated,
672
+ thinkingTokensSource,
589
673
  outputIncludesThinking: true,
590
674
  untruncatedLength: content.length,
591
675
  isTruncated: false,
@@ -597,7 +681,8 @@ export function parseClaudeCodeJsonl(rawContent = '') {
597
681
  shapeHash: latestShapeHash || null,
598
682
  toolsUsed: stepToolsUsed,
599
683
  entrypoint: stepEntrypoint,
600
- cacheTtlTier
684
+ cacheTtlTier,
685
+ appendedPositionsSincePrevCall
601
686
  });
602
687
  }
603
688
 
@@ -701,6 +786,27 @@ function readSliceUtf8FromFd(filePath, startOffset, endOffset) {
701
786
  return content;
702
787
  }
703
788
 
789
+ /**
790
+ * Reads at most the last `tailBytes` of a text file (default 8 MiB), aligned past the first partial line
791
+ * when the file is larger than the window. `tailBytes` of 0 / null / Infinity reads the whole file.
792
+ */
793
+ export function readBoundedTailUtf8(filePath, tailBytes = DEFAULT_CLAUDE_TAIL_BYTES) {
794
+ const stat = fs.statSync(filePath);
795
+ const limit =
796
+ tailBytes === 0 || tailBytes === null || tailBytes === Infinity
797
+ ? 0
798
+ : Number.isFinite(Number(tailBytes)) && Number(tailBytes) > 0
799
+ ? Number(tailBytes)
800
+ : DEFAULT_CLAUDE_TAIL_BYTES;
801
+ const tailStart = limit > 0 && stat.size > limit ? Math.max(0, stat.size - limit) : 0;
802
+ let content = readSliceUtf8FromFd(filePath, tailStart, stat.size);
803
+ if (tailStart > 0) {
804
+ const nlIdx = content.indexOf('\n');
805
+ if (nlIdx !== -1) content = content.slice(nlIdx + 1);
806
+ }
807
+ return content;
808
+ }
809
+
704
810
  const incrementalMemCache = new Map();
705
811
 
706
812
  function resolveJsonlTranscriptFile(targetPath) {
@@ -741,6 +847,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
741
847
  }
742
848
 
743
849
  const actualCacheDir = actualCacheDirArg || getBurnoffCacheDir(actualOpts.homeDir || null);
850
+ const isReadOnly = actualOpts?.readOnly === true || actualOpts?.persistCache === false;
744
851
  const stat = fs.statSync(filePath);
745
852
  const currentPrefixSha256 = computeFilePrefixSha256(filePath, stat.size);
746
853
  const pathHash = crypto.createHash('sha1').update(path.resolve(filePath)).digest('hex').slice(0, 10);
@@ -869,10 +976,12 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
869
976
  };
870
977
  if (incrementalMemCache.size > 24) incrementalMemCache.clear();
871
978
  incrementalMemCache.set(cacheFile, updatedCachePayload);
872
- try {
873
- atomicWriteFileSync(cacheFile, JSON.stringify(updatedCachePayload), { encoding: 'utf8' });
874
- } catch (err) {
875
- void err; // ignore: non-fatal cache write failure
979
+ if (!isReadOnly) {
980
+ try {
981
+ atomicWriteFileSync(cacheFile, JSON.stringify(updatedCachePayload), { encoding: 'utf8' });
982
+ } catch (err) {
983
+ void err; // ignore: non-fatal cache write failure
984
+ }
876
985
  }
877
986
  return {
878
987
  schemaRev: SCHEMA_REV,
@@ -943,10 +1052,12 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
943
1052
  };
944
1053
  if (incrementalMemCache.size > 24) incrementalMemCache.clear();
945
1054
  incrementalMemCache.set(cacheFile, updatedCachePayload);
946
- try {
947
- atomicWriteFileSync(cacheFile, JSON.stringify(updatedCachePayload), { encoding: 'utf8' });
948
- } catch (err) {
949
- void err; // ignore: non-fatal cache write failure
1055
+ if (!isReadOnly) {
1056
+ try {
1057
+ atomicWriteFileSync(cacheFile, JSON.stringify(updatedCachePayload), { encoding: 'utf8' });
1058
+ } catch (err) {
1059
+ void err; // ignore: non-fatal cache write failure
1060
+ }
950
1061
  }
951
1062
 
952
1063
  return {