burnoff 1.0.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 (41) hide show
  1. package/.github/workflows/burnoff-pr-gate.yml +75 -0
  2. package/README.md +94 -20
  3. package/bin/burnoff.mjs +129 -30
  4. package/hooks/hook-io.mjs +27 -18
  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 +8 -5
  9. package/src/ci/ci-gate.mjs +84 -9
  10. package/src/ci/pr-cost.mjs +207 -22
  11. package/src/ci/team-digest.mjs +6 -4
  12. package/src/cli/audit.mjs +177 -23
  13. package/src/cli/doctor.mjs +230 -25
  14. package/src/cli/init.mjs +415 -75
  15. package/src/cli/startup-audit.mjs +2824 -0
  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/catalog.json +188 -45
  20. package/src/config/loader.mjs +96 -13
  21. package/src/config/paths.mjs +92 -2
  22. package/src/config/policy.mjs +103 -17
  23. package/src/config/pricing.mjs +1033 -0
  24. package/src/config/uncached-attribution.mjs +719 -0
  25. package/src/guards/loop-breaker.mjs +267 -24
  26. package/src/guards/post-tool-engine.mjs +316 -35
  27. package/src/guards/pre-tool-engine.mjs +389 -130
  28. package/src/guards/read-clamp.mjs +149 -75
  29. package/src/guards/session-hook.mjs +207 -0
  30. package/src/guards/shell-guard.mjs +610 -74
  31. package/src/ipc/daemon.mjs +50 -8
  32. package/src/ipc/fast-client.mjs +62 -5
  33. package/src/ipc/protocol.mjs +1 -1
  34. package/src/storage/antigravity-parser.mjs +258 -0
  35. package/src/storage/atomic-io.mjs +2 -2
  36. package/src/storage/file-lock.mjs +66 -13
  37. package/src/storage/fts5-archive.mjs +31 -16
  38. package/src/storage/jsonl-parser.mjs +209 -20
  39. package/src/storage/ledger.mjs +15 -10
  40. package/src/storage/sqlite-client.mjs +35 -11
  41. package/hooks/hooks.json +0 -12
@@ -9,7 +9,7 @@
9
9
  import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { getHomeDir, getBurnoffCacheDir } from '../config/paths.mjs';
12
- import { openBurnoffDb } from './sqlite-client.mjs';
12
+ import { openBurnoffDb, resolveFallbackDbPath } from './sqlite-client.mjs';
13
13
  import { recordInterventionSavings } from './ledger.mjs';
14
14
 
15
15
  export const FTS5_COMPRESSOR_CONSTANTS = Object.freeze({
@@ -20,7 +20,7 @@ export const FTS5_COMPRESSOR_CONSTANTS = Object.freeze({
20
20
  /(?:(?:^|[\s;|&])@['"]|\b(?:pytest|jest|vitest|cargo\s+(?:test|clippy|check|build)|tsc|go\s+test|eslint|biome|ruff|next\s+build|vite\s+build|(?:mvn|mvnw(?:\.cmd)?|gradle|gradlew(?:\.bat)?|kotlinc)\b|dotnet\s+(?:test|build)\b|make\b|ctest\b|bazel\s+(?:test|build)\b|(?:(?:npx|pnpm(?:\s+exec)?)\s+)?playwright\s+test\b|(?:bundle\s+exec\s+)?rspec\b|phpunit\b|deno\s+test\b|docker\s+(?:build|logs)|kubectl\s+(?:logs|get|describe)|gh\s+(?:pr|run|api|issue|release|workflow)|git\s+(?:diff|log|show|status|grep|ls-files|blame|branch|tag|stash|reflog|cherry-pick)|(?:npm|pnpm|yarn|bun)\s+(?:test|run\s+(?:test|lint|build|typecheck)|install|ci|add|update|audit|outdated|pack|publish)|(?:pip3?|uv|poetry)\s+(?:install|sync|audit|list|show)|node(?:\.exe)?|python3?(?:\.exe)?|select-string|get-childitem|gci|get-content|write-output|powershell|pwsh|rg|ripgrep|grep|find|fd|tree|curl|wget|aws|gcloud|terraform)\b)/i
21
21
  });
22
22
 
23
- export function getDefaultToolLogsDbPath(homeDir = getHomeDir()) {
23
+ export function getDefaultToolLogsDbPath(homeDir = null) {
24
24
  return path.join(getBurnoffCacheDir(homeDir), 'tool_logs_fts5.db');
25
25
  }
26
26
 
@@ -380,7 +380,8 @@ export function compressCliOutputFts5Sync({
380
380
  recordLedger = true,
381
381
  ledgerPath = null,
382
382
  minBytes = 0,
383
- minTokensSaved = 0
383
+ minTokensSaved = 0,
384
+ retentionDays = 30
384
385
  } = {}) {
385
386
  const rawStr = String(rawOutput || '');
386
387
  const rawLines = rawStr.split(/\r?\n/);
@@ -441,7 +442,7 @@ export function compressCliOutputFts5Sync({
441
442
  );
442
443
 
443
444
  try {
444
- pruneExpiredFts5LogsSync(db);
445
+ pruneExpiredFts5LogsSync(db, Date.now(), Number(retentionDays ?? 30));
445
446
  } catch (pruneErr) {
446
447
  void pruneErr; // ignore: non-fatal background retention prune
447
448
  }
@@ -597,11 +598,11 @@ export async function searchToolLogsFts5(dbPath, {
597
598
  turnId = '',
598
599
  keyword = '',
599
600
  limit = 10,
600
- homeDir = getHomeDir(),
601
+ homeDir = null,
601
602
  DatabaseSync = null
602
603
  } = {}) {
603
604
  const resolvedDbPath = dbPath || getDefaultToolLogsDbPath(homeDir);
604
- if (!fs.existsSync(resolvedDbPath)) {
605
+ if (!fs.existsSync(resolvedDbPath) && !fs.existsSync(resolveFallbackDbPath(resolvedDbPath))) {
605
606
  return { hits: [], matchedLines: [] };
606
607
  }
607
608
 
@@ -609,26 +610,40 @@ export async function searchToolLogsFts5(dbPath, {
609
610
  try {
610
611
  db = openBurnoffDb(resolvedDbPath, { readOnly: true, DatabaseSync });
611
612
  const cleanKeyword = String(keyword || '').replace(/[^A-Za-z0-9_./:-]/g, ' ').trim();
613
+ const maxLimit = Math.max(1, Number(limit) || 10);
614
+ const cleanTurnId = turnId ? String(turnId) : '';
612
615
 
613
616
  let rows = [];
614
617
  if (cleanKeyword) {
615
618
  const ftsToken = cleanKeyword.split(/\s+/).filter(Boolean).map((t) => `"${t}"`).join(' AND ');
619
+ if (cleanTurnId) {
620
+ rows = db.prepare(`
621
+ SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
622
+ FROM tool_logs
623
+ WHERE turn_id = ? AND tool_logs MATCH ?
624
+ LIMIT ?
625
+ `).all(cleanTurnId, ftsToken, maxLimit);
626
+ } else {
627
+ rows = db.prepare(`
628
+ SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
629
+ FROM tool_logs
630
+ WHERE tool_logs MATCH ?
631
+ LIMIT ?
632
+ `).all(ftsToken, maxLimit);
633
+ }
634
+ } else if (cleanTurnId) {
616
635
  rows = db.prepare(`
617
636
  SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
618
637
  FROM tool_logs
619
- WHERE tool_logs MATCH ?
638
+ WHERE turn_id = ?
620
639
  LIMIT ?
621
- `).all(ftsToken, Math.max(1, limit));
640
+ `).all(cleanTurnId, maxLimit);
622
641
  } else {
623
642
  rows = db.prepare(`
624
643
  SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
625
644
  FROM tool_logs
626
645
  LIMIT ?
627
- `).all(Math.max(1, limit));
628
- }
629
-
630
- if (turnId) {
631
- rows = rows.filter((r) => String(r.turnId) === String(turnId));
646
+ `).all(maxLimit);
632
647
  }
633
648
 
634
649
  const matchedLines = [];
@@ -663,13 +678,13 @@ export async function searchToolLogsFts5(dbPath, {
663
678
  }
664
679
 
665
680
  export async function searchFts5Logs(options = {}) {
666
- const { turnId = '', keyword = '', limit = 10, dbPath = null, homeDir = getHomeDir(), DatabaseSync = null } = options;
681
+ const { turnId = '', keyword = '', limit = 10, dbPath = null, homeDir = null, DatabaseSync = null } = options;
667
682
  return searchToolLogsFts5(dbPath, { turnId, keyword, limit, homeDir, DatabaseSync });
668
683
  }
669
684
 
670
- export function getFts5CompressionStats(dbPath = null, { DatabaseSync = null, homeDir = getHomeDir() } = {}) {
685
+ export function getFts5CompressionStats(dbPath = null, { DatabaseSync = null, homeDir = null } = {}) {
671
686
  const resolvedDbPath = dbPath || getDefaultToolLogsDbPath(homeDir);
672
- if (!fs.existsSync(resolvedDbPath)) {
687
+ if (!fs.existsSync(resolvedDbPath) && !fs.existsSync(resolveFallbackDbPath(resolvedDbPath))) {
673
688
  return { active: true, logCount: 0, savedTokens: 0, formattedSavedK: '0.0k' };
674
689
  }
675
690
 
@@ -10,9 +10,10 @@ import path from 'node:path';
10
10
  import crypto from 'node:crypto';
11
11
  import { StringDecoder } from 'node:string_decoder';
12
12
  import { atomicWriteFileSync } from './atomic-io.mjs';
13
- import { getHomeDir, getBurnoffCacheDir, getClaudeProjectsDir } from '../config/paths.mjs';
13
+ import { getHomeDir, getBurnoffCacheDir, getClaudeProjectsDir, canonicalizePath } from '../config/paths.mjs';
14
14
 
15
15
  export const SCHEMA_REV = 4;
16
+ export const ATTRIBUTION_SCHEMA_REV = 1;
16
17
  export const DEFAULT_CLAUDE_TAIL_BYTES = 8 * 1024 * 1024;
17
18
  const PREFIX_HASH_BYTES = 4096;
18
19
 
@@ -42,11 +43,26 @@ export function stitchClaudeCodeDag(jsonlLinesOrContent = []) {
42
43
  let explicitLeafUuid = null;
43
44
  let lastEntryUuid = null;
44
45
  let inferredSystemPromptTokens = 0;
46
+ let sessionEntrypoint = null;
47
+ let toolsUsed = [];
48
+ const compactRawIndices = [];
45
49
 
46
50
  for (let i = 0; i < entries.length; i++) {
47
51
  const e = entries[i];
48
52
  if (!e || typeof e !== 'object') continue;
49
53
 
54
+ if (e.entrypoint && !sessionEntrypoint) sessionEntrypoint = String(e.entrypoint);
55
+ if (e.type === 'tools-used' && Array.isArray(e.tools)) {
56
+ toolsUsed = [...e.tools];
57
+ }
58
+ if (
59
+ e.type === 'summary' ||
60
+ Boolean(e.isCompactSummary) ||
61
+ (e.type === 'system' && e.subtype === 'compact_boundary')
62
+ ) {
63
+ compactRawIndices.push(i);
64
+ }
65
+
50
66
  if (e.leafUuid) explicitLeafUuid = e.leafUuid;
51
67
  if (e.type === 'file-history-snapshot' || e.snapshot) {
52
68
  restorePoints.push({
@@ -100,16 +116,21 @@ export function stitchClaudeCodeDag(jsonlLinesOrContent = []) {
100
116
  let count = 0;
101
117
  let tokens = 0;
102
118
  let tip = startUuid;
119
+ const subVisited = new Set();
103
120
  const stack = [startUuid];
104
121
  while (stack.length > 0) {
105
122
  const u = stack.pop();
123
+ if (!u || subVisited.has(u)) continue;
124
+ subVisited.add(u);
106
125
  const n = nodeMap.get(u);
107
126
  if (!n) continue;
108
127
  count++;
109
128
  tip = u;
110
129
  tokens += Number(n.output_tokens ?? n.message?.usage?.output_tokens ?? Math.ceil(String(n.content || '').length / 4));
111
130
  for (const ch of (childrenMap.get(u) || [])) {
112
- stack.push(ch);
131
+ if (!subVisited.has(ch)) {
132
+ stack.push(ch);
133
+ }
113
134
  }
114
135
  }
115
136
  return { count, tokens, tip };
@@ -229,16 +250,72 @@ export function stitchClaudeCodeDag(jsonlLinesOrContent = []) {
229
250
  activeBranchSteps: consolidatedActiveChain.map((n, idx) => ({ ...n, stepIndex: idx })),
230
251
  rewindBranches,
231
252
  restorePoints,
232
- inferredSystemPromptTokens
253
+ inferredSystemPromptTokens,
254
+ sessionEntrypoint,
255
+ toolsUsed,
256
+ compactRawIndices
233
257
  };
234
258
  }
235
259
 
260
+ function peekSessionWorkspacePath(fullPath) {
261
+ let fd = null;
262
+ try {
263
+ fd = fs.openSync(fullPath, 'r');
264
+ const buf = Buffer.allocUnsafe(4096);
265
+ const bytesRead = fs.readSync(fd, buf, 0, buf.length, 0);
266
+ if (bytesRead <= 0) return '';
267
+ const head = buf.toString('utf8', 0, bytesRead);
268
+ for (const line of head.split(/\r?\n/)) {
269
+ if (!line.trim()) continue;
270
+ if (!line.includes('"cwd"') && !line.includes('"workspacePath"')) continue;
271
+ try {
272
+ const parsed = JSON.parse(line);
273
+ const ws = parsed?.cwd || parsed?.workspacePath || '';
274
+ if (typeof ws === 'string' && ws.trim()) return ws.trim();
275
+ } catch {
276
+ // ignore: partial trailing line in 4 KB head peek
277
+ }
278
+ }
279
+ } catch {
280
+ // ignore: unreadable session file head returns empty string
281
+ } finally {
282
+ if (fd !== null) {
283
+ try {
284
+ fs.closeSync(fd);
285
+ } catch {
286
+ // ignore: close cleanup failure
287
+ }
288
+ }
289
+ }
290
+ return '';
291
+ }
292
+
293
+ function normalizeProjectSlugForMatch(slug = '') {
294
+ return String(slug || '')
295
+ .toLowerCase()
296
+ .replace(/[^a-z0-9]+/g, '-')
297
+ .replace(/^-+|-+$/g, '');
298
+ }
299
+
300
+ function doesSessionMatchCwd(fullPath, projectSlug, targetCanon, expectedSlug) {
301
+ const headerCwd = peekSessionWorkspacePath(fullPath);
302
+ if (headerCwd) {
303
+ const canonHeader = canonicalizePath(path.resolve(headerCwd));
304
+ return canonHeader === targetCanon || canonHeader.startsWith(`${targetCanon}/`);
305
+ }
306
+ if (!projectSlug) return false;
307
+ return normalizeProjectSlugForMatch(projectSlug) === expectedSlug;
308
+ }
309
+
236
310
  /**
237
311
  * Discovers Claude Code `.jsonl` session transcripts under `~/.claude/projects/<project>/<sid>.jsonl`.
238
312
  */
239
313
  export function discoverClaudeCodeSessions(homeDir = getHomeDir(), options = {}) {
240
314
  const projectsDir = getClaudeProjectsDir(homeDir, options);
241
315
  if (!projectsDir || !fs.existsSync(projectsDir)) return [];
316
+ const hasCwdFilter = Boolean(options?.cwd && typeof options.cwd === 'string' && options.cwd.trim());
317
+ const targetCanon = hasCwdFilter ? canonicalizePath(path.resolve(options.cwd.trim())) : '';
318
+ const expectedSlug = hasCwdFilter ? normalizeProjectSlugForMatch(targetCanon) : '';
242
319
  const sessions = [];
243
320
 
244
321
  const inspectJsonlFile = (fullPath, projectSlug = '') => {
@@ -247,6 +324,9 @@ export function discoverClaudeCodeSessions(homeDir = getHomeDir(), options = {})
247
324
  if (!stat.isFile() || stat.size === 0) return;
248
325
  const base = path.basename(fullPath);
249
326
  if (!base.endsWith('.jsonl') || base.startsWith('.')) return;
327
+ if (hasCwdFilter && !doesSessionMatchCwd(fullPath, projectSlug, targetCanon, expectedSlug)) {
328
+ return;
329
+ }
250
330
  const sessionId = base.replace(/\.jsonl$/i, '');
251
331
  sessions.push({
252
332
  storeName: 'claude-code',
@@ -299,10 +379,21 @@ export function parseClaudeCodeJsonl(rawContent = '') {
299
379
  let sessionTitle = '';
300
380
  let workspacePath = '';
301
381
  let latestModel = null;
382
+ let pendingCompaction = false;
383
+ let latestShapeHash = null;
384
+ let latestEntrypoint = dag.sessionEntrypoint || null;
385
+ let latestToolsUsed = Array.isArray(dag.toolsUsed) ? [...dag.toolsUsed] : [];
302
386
 
303
387
  for (let i = 0; i < dag.activeBranchSteps.length; i++) {
304
388
  const node = dag.activeBranchSteps[i];
305
389
  if (!node || typeof node !== 'object') continue;
390
+ if (node.entrypoint) latestEntrypoint = String(node.entrypoint);
391
+ if (node.type === 'api-request-shape' && node.shapeHash) {
392
+ latestShapeHash = String(node.shapeHash);
393
+ }
394
+ if (node.type === 'tools-used' && Array.isArray(node.tools)) {
395
+ latestToolsUsed = [...node.tools];
396
+ }
306
397
  if (node.type === 'file-history-snapshot' && !node.message && !node.content) {
307
398
  continue;
308
399
  }
@@ -314,6 +405,13 @@ export function parseClaudeCodeJsonl(rawContent = '') {
314
405
  const role = String(msg?.role || node.role || node.type || '').toLowerCase();
315
406
  const isUser = role === 'user' || node.type === 'USER_INPUT' || node.source === 'USER_EXPLICIT';
316
407
  const isSummary = role === 'summary' || node.type === 'summary' || node.type === 'CHECKPOINT';
408
+ const isCompactionMarker =
409
+ isSummary ||
410
+ Boolean(node.isCompactSummary) ||
411
+ (node.type === 'system' && node.subtype === 'compact_boundary');
412
+ if (isCompactionMarker) {
413
+ pendingCompaction = true;
414
+ }
317
415
 
318
416
  const toolCalls = Array.isArray(node.tool_calls)
319
417
  ? [...node.tool_calls]
@@ -390,6 +488,10 @@ export function parseClaudeCodeJsonl(rawContent = '') {
390
488
  ? flatCacheCreationTokens
391
489
  : (cacheCreationEphemeral5mInputTokens + cacheCreationEphemeral1hInputTokens);
392
490
  const totalPromptTokens = inputTokens + cacheReadTokens + cacheCreationTokens;
491
+ const hasExplicitThinkingTokens =
492
+ node.thinking_tokens != null ||
493
+ node.thinkingTokens != null ||
494
+ usage.thinking_tokens != null;
393
495
  const thinkingTokens = Math.max(0, Number(
394
496
  node.thinking_tokens ??
395
497
  node.thinkingTokens ??
@@ -399,8 +501,17 @@ export function parseClaudeCodeJsonl(rawContent = '') {
399
501
  const model = msg?.model || node.model || null;
400
502
  if (model) latestModel = model;
401
503
  const createdAt = node.timestamp || node.created_at || node.createdAt || null;
504
+ const hasUsage = inputTokens > 0 || cacheReadTokens > 0 || cacheCreationTokens > 0 || outputTokens > 0;
505
+ const hadCompactionBefore = hasUsage ? pendingCompaction : false;
506
+ if (hasUsage) {
507
+ pendingCompaction = false;
508
+ }
509
+ const cacheTtlTier = cacheCreationEphemeral1hInputTokens > 0 ? '1h' : '5m';
510
+ const systemSubtype = node.type === 'system' ? (node.subtype || null) : null;
511
+ const stepToolsUsed = node.type === 'tools-used' && Array.isArray(node.tools) ? [...node.tools] : null;
512
+ const stepEntrypoint = node.entrypoint ? String(node.entrypoint) : latestEntrypoint;
402
513
 
403
- if (inputTokens > 0 || cacheReadTokens > 0 || cacheCreationTokens > 0 || outputTokens > 0) {
514
+ if (hasUsage) {
404
515
  usageTurns.push({
405
516
  stepIndex: steps.length,
406
517
  freshInputTokens: inputTokens,
@@ -412,7 +523,14 @@ export function parseClaudeCodeJsonl(rawContent = '') {
412
523
  totalPromptTokens,
413
524
  outputTokens,
414
525
  model: model || latestModel,
415
- createdAt
526
+ createdAt,
527
+ hadCompactionBefore,
528
+ isCompactSummary: Boolean(node.isCompactSummary),
529
+ isCompactionBoundary: Boolean(isCompactionMarker),
530
+ isSidechain: Boolean(node.isSidechain),
531
+ shapeHash: latestShapeHash || null,
532
+ entrypoint: stepEntrypoint,
533
+ cacheTtlTier
416
534
  });
417
535
  }
418
536
 
@@ -422,8 +540,11 @@ export function parseClaudeCodeJsonl(rawContent = '') {
422
540
  messageId: msg?.id || node.message_id || node.messageId || null,
423
541
  source: isUser ? 'USER_EXPLICIT' : (isSummary ? 'SYSTEM' : 'MODEL'),
424
542
  type: isSummary ? 'CHECKPOINT' : (isUser ? 'USER_INPUT' : 'PLANNER_RESPONSE'),
543
+ rawType: node.type || null,
544
+ systemSubtype,
425
545
  status: 'DONE',
426
546
  createdAt,
547
+ model: model || latestModel || null,
427
548
  toolCalls,
428
549
  content,
429
550
  freshInputTokens: inputTokens,
@@ -436,8 +557,19 @@ export function parseClaudeCodeJsonl(rawContent = '') {
436
557
  totalPromptTokens,
437
558
  totalPromptEnvelopeTokens: totalPromptTokens,
438
559
  thinkingTokens,
560
+ thinkingTokensEstimated: !hasExplicitThinkingTokens && thinkingTokens > 0,
561
+ outputIncludesThinking: true,
439
562
  untruncatedLength: content.length,
440
- isTruncated: false
563
+ isTruncated: false,
564
+ isCompactSummary: Boolean(node.isCompactSummary),
565
+ compactMetadata: node.compactMetadata || null,
566
+ isCompactionBoundary: Boolean(isCompactionMarker),
567
+ hadCompactionBefore,
568
+ isSidechain: Boolean(node.isSidechain),
569
+ shapeHash: latestShapeHash || null,
570
+ toolsUsed: stepToolsUsed,
571
+ entrypoint: stepEntrypoint,
572
+ cacheTtlTier
441
573
  });
442
574
  }
443
575
 
@@ -492,7 +624,9 @@ export function parseClaudeCodeJsonl(rawContent = '') {
492
624
  rewindDetected: dag.rewindBranches.length > 0,
493
625
  genMetadata,
494
626
  sessionTitle,
495
- workspacePath
627
+ workspacePath,
628
+ entrypoint: latestEntrypoint || dag.sessionEntrypoint || null,
629
+ toolsUsed: latestToolsUsed
496
630
  };
497
631
  }
498
632
 
@@ -563,6 +697,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
563
697
  if (!filePath) {
564
698
  return {
565
699
  schemaRev: SCHEMA_REV,
700
+ attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
566
701
  steps: [],
567
702
  filePath: null,
568
703
  lastByteOffset: 0,
@@ -571,11 +706,13 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
571
706
  claudeDag: null,
572
707
  genMetadata: null,
573
708
  sessionTitle: '',
574
- workspacePath: ''
709
+ workspacePath: '',
710
+ entrypoint: null,
711
+ toolsUsed: []
575
712
  };
576
713
  }
577
714
 
578
- const actualCacheDir = actualCacheDirArg || getBurnoffCacheDir(actualOpts.homeDir || getHomeDir(actualOpts));
715
+ const actualCacheDir = actualCacheDirArg || getBurnoffCacheDir(actualOpts.homeDir || null);
579
716
  const stat = fs.statSync(filePath);
580
717
  const currentPrefixSha256 = computeFilePrefixSha256(filePath, stat.size);
581
718
  const pathHash = crypto.createHash('sha1').update(path.resolve(filePath)).digest('hex').slice(0, 10);
@@ -583,6 +720,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
583
720
 
584
721
  let cached = {
585
722
  schemaRev: 0,
723
+ attributionSchemaRev: 0,
586
724
  lastByteOffset: 0,
587
725
  prefixSha256: '',
588
726
  filePath,
@@ -591,7 +729,9 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
591
729
  claudeDag: null,
592
730
  genMetadata: null,
593
731
  sessionTitle: '',
594
- workspacePath: ''
732
+ workspacePath: '',
733
+ entrypoint: null,
734
+ toolsUsed: []
595
735
  };
596
736
  let rewindDetected = false;
597
737
  let cacheHit = false;
@@ -600,6 +740,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
600
740
  if (
601
741
  memCached &&
602
742
  memCached.schemaRev === SCHEMA_REV &&
743
+ memCached.attributionSchemaRev === ATTRIBUTION_SCHEMA_REV &&
603
744
  memCached.filePath === filePath &&
604
745
  fs.existsSync(cacheFile)
605
746
  ) {
@@ -612,7 +753,11 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
612
753
  } else if (fs.existsSync(cacheFile)) {
613
754
  try {
614
755
  const cachedData = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
615
- if (cachedData.schemaRev === SCHEMA_REV && cachedData.filePath === filePath) {
756
+ if (
757
+ cachedData.schemaRev === SCHEMA_REV &&
758
+ cachedData.attributionSchemaRev === ATTRIBUTION_SCHEMA_REV &&
759
+ cachedData.filePath === filePath
760
+ ) {
616
761
  if (cachedData.lastByteOffset <= stat.size && cachedData.prefixSha256 === currentPrefixSha256) {
617
762
  cached = cachedData;
618
763
  cacheHit = true;
@@ -629,6 +774,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
629
774
  if (cacheHit && cached.lastByteOffset === stat.size) {
630
775
  return {
631
776
  schemaRev: SCHEMA_REV,
777
+ attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
632
778
  steps: cached.steps,
633
779
  filePath,
634
780
  lastByteOffset: stat.size,
@@ -637,13 +783,22 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
637
783
  claudeDag: cached.claudeDag || null,
638
784
  genMetadata: cached.genMetadata || null,
639
785
  sessionTitle: cached.sessionTitle || '',
640
- workspacePath: cached.workspacePath || ''
786
+ workspacePath: cached.workspacePath || '',
787
+ entrypoint: cached.entrypoint || null,
788
+ toolsUsed: Array.isArray(cached.toolsUsed) ? cached.toolsUsed : []
641
789
  };
642
790
  }
643
791
 
644
792
  if (cacheHit && cached.lastByteOffset < stat.size) {
645
- const newContent = readSliceUtf8FromFd(filePath, cached.lastByteOffset, stat.size);
646
- if (!/"leafUuid"/.test(newContent)) {
793
+ const rawNewContent = readSliceUtf8FromFd(filePath, cached.lastByteOffset, stat.size);
794
+ const lastNewlineIdx = rawNewContent.lastIndexOf('\n');
795
+ const newContent = lastNewlineIdx === -1
796
+ ? ''
797
+ : rawNewContent.slice(0, lastNewlineIdx + 1);
798
+ const nextByteOffset = newContent.length > 0
799
+ ? cached.lastByteOffset + Buffer.byteLength(newContent, 'utf8')
800
+ : cached.lastByteOffset;
801
+ if (newContent && !/"leafUuid"/.test(newContent)) {
647
802
  const parsedAppend = parseClaudeCodeJsonl(newContent);
648
803
  const baseIdx = Array.isArray(cached.steps) ? cached.steps.length : 0;
649
804
  const appendedSteps = parsedAppend.steps.map((s, idx) => ({ ...s, stepIndex: baseIdx + idx }));
@@ -662,20 +817,27 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
662
817
  }
663
818
  const mergedTitle = cached.sessionTitle || parsedAppend.sessionTitle || '';
664
819
  const mergedWorkspace = cached.workspacePath || parsedAppend.workspacePath || '';
820
+ const mergedEntrypoint = cached.entrypoint || parsedAppend.entrypoint || null;
821
+ const mergedToolsUsed = (Array.isArray(parsedAppend.toolsUsed) && parsedAppend.toolsUsed.length > 0)
822
+ ? parsedAppend.toolsUsed
823
+ : (Array.isArray(cached.toolsUsed) ? cached.toolsUsed : []);
665
824
  const allSteps = [...(cached.steps || []), ...appendedSteps];
666
825
 
667
826
  const updatedCachePayload = {
668
827
  schemaRev: SCHEMA_REV,
828
+ attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
669
829
  filePath,
670
830
  prefixSha256: currentPrefixSha256,
671
- lastByteOffset: stat.size,
831
+ lastByteOffset: nextByteOffset,
672
832
  mtimeMs: stat.mtimeMs,
673
833
  steps: allSteps,
674
834
  rewindDetected,
675
835
  claudeDag: cached.claudeDag || null,
676
836
  genMetadata: mergedGenMetadata,
677
837
  sessionTitle: mergedTitle,
678
- workspacePath: mergedWorkspace
838
+ workspacePath: mergedWorkspace,
839
+ entrypoint: mergedEntrypoint,
840
+ toolsUsed: mergedToolsUsed
679
841
  };
680
842
  if (incrementalMemCache.size > 24) incrementalMemCache.clear();
681
843
  incrementalMemCache.set(cacheFile, updatedCachePayload);
@@ -686,15 +848,35 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
686
848
  }
687
849
  return {
688
850
  schemaRev: SCHEMA_REV,
851
+ attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
689
852
  steps: allSteps,
690
853
  filePath,
691
- lastByteOffset: stat.size,
854
+ lastByteOffset: nextByteOffset,
692
855
  prefixSha256: currentPrefixSha256,
693
856
  rewindDetected,
694
857
  claudeDag: cached.claudeDag || null,
695
858
  genMetadata: mergedGenMetadata,
696
859
  sessionTitle: mergedTitle,
697
- workspacePath: mergedWorkspace
860
+ workspacePath: mergedWorkspace,
861
+ entrypoint: mergedEntrypoint,
862
+ toolsUsed: mergedToolsUsed
863
+ };
864
+ }
865
+ if (!newContent) {
866
+ return {
867
+ schemaRev: SCHEMA_REV,
868
+ attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
869
+ steps: cached.steps,
870
+ filePath,
871
+ lastByteOffset: cached.lastByteOffset,
872
+ prefixSha256: currentPrefixSha256,
873
+ rewindDetected: false,
874
+ claudeDag: cached.claudeDag || null,
875
+ genMetadata: cached.genMetadata || null,
876
+ sessionTitle: cached.sessionTitle || '',
877
+ workspacePath: cached.workspacePath || '',
878
+ entrypoint: cached.entrypoint || null,
879
+ toolsUsed: Array.isArray(cached.toolsUsed) ? cached.toolsUsed : []
698
880
  };
699
881
  }
700
882
  }
@@ -717,6 +899,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
717
899
  const finalRewind = rewindDetected || Boolean(parsedClaude.rewindDetected);
718
900
  const updatedCachePayload = {
719
901
  schemaRev: SCHEMA_REV,
902
+ attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
720
903
  filePath,
721
904
  prefixSha256: currentPrefixSha256,
722
905
  lastByteOffset: stat.size,
@@ -726,7 +909,9 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
726
909
  claudeDag: parsedClaude.claudeDag,
727
910
  genMetadata: parsedClaude.genMetadata,
728
911
  sessionTitle: parsedClaude.sessionTitle,
729
- workspacePath: parsedClaude.workspacePath
912
+ workspacePath: parsedClaude.workspacePath,
913
+ entrypoint: parsedClaude.entrypoint,
914
+ toolsUsed: parsedClaude.toolsUsed
730
915
  };
731
916
  if (incrementalMemCache.size > 24) incrementalMemCache.clear();
732
917
  incrementalMemCache.set(cacheFile, updatedCachePayload);
@@ -738,6 +923,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
738
923
 
739
924
  return {
740
925
  schemaRev: SCHEMA_REV,
926
+ attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
741
927
  steps: parsedClaude.steps,
742
928
  filePath,
743
929
  lastByteOffset: stat.size,
@@ -746,12 +932,15 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
746
932
  claudeDag: parsedClaude.claudeDag,
747
933
  genMetadata: parsedClaude.genMetadata,
748
934
  sessionTitle: parsedClaude.sessionTitle,
749
- workspacePath: parsedClaude.workspacePath
935
+ workspacePath: parsedClaude.workspacePath,
936
+ entrypoint: parsedClaude.entrypoint,
937
+ toolsUsed: parsedClaude.toolsUsed
750
938
  };
751
939
  }
752
940
 
753
941
  export default {
754
942
  SCHEMA_REV,
943
+ ATTRIBUTION_SCHEMA_REV,
755
944
  DEFAULT_CLAUDE_TAIL_BYTES,
756
945
  stitchClaudeCodeDag,
757
946
  discoverClaudeCodeSessions,
@@ -123,20 +123,16 @@ function safeAppendJsonl(filePath, entry) {
123
123
  }
124
124
 
125
125
  /**
126
- * Resolves the Burnoff ledger file path (`options.ledgerPath`, or
127
- * `<cwd>/.burnoff/ledger/burnoff_ledger.jsonl`, or `~/.burnoff/ledger/burnoff_ledger.jsonl`).
126
+ * Resolves the Burnoff ledger file path (`options.ledgerPath`, or `~/.burnoff/ledger/burnoff_ledger.jsonl`).
128
127
  */
129
128
  export function getLedgerFilePath(options = {}) {
130
129
  if (typeof options.ledgerPath === 'string' && options.ledgerPath.trim()) {
131
130
  return options.ledgerPath.trim();
132
131
  }
133
- if (options.homeDir) {
134
- return path.join(getBurnoffLedgerDir(options.homeDir), 'burnoff_ledger.jsonl');
135
- }
136
- if (options.cwd) {
137
- return path.join(options.cwd, '.burnoff', 'ledger', 'burnoff_ledger.jsonl');
138
- }
139
- return path.join(getBurnoffLedgerDir(getHomeDir(options)), 'burnoff_ledger.jsonl');
132
+ const explicitHomeDir = typeof options.homeDir === 'string' && options.homeDir.trim()
133
+ ? options.homeDir.trim()
134
+ : null;
135
+ return path.join(getBurnoffLedgerDir(explicitHomeDir), 'burnoff_ledger.jsonl');
140
136
  }
141
137
 
142
138
  export function getLedgerMonthKey(tsMs = Date.now()) {
@@ -471,6 +467,7 @@ export function recordSavingsReceipt(receipt = {}, options = {}) {
471
467
  savedTokens,
472
468
  savedUSD,
473
469
  detail: String(receipt.detail || ''),
470
+ ...((receipt.cwd || options.cwd) ? { cwd: String(receipt.cwd || options.cwd) } : {}),
474
471
  ...(wallClock.seconds > 0
475
472
  ? {
476
473
  savedWallClockSeconds: wallClock.seconds,
@@ -481,6 +478,8 @@ export function recordSavingsReceipt(receipt = {}, options = {}) {
481
478
  ...(receipt.exPost && typeof receipt.exPost === 'object' ? { exPost: receipt.exPost } : {}),
482
479
  ...(receipt.rawClampedTokens !== undefined ? { rawClampedTokens: receipt.rawClampedTokens } : {}),
483
480
  ...(receipt.rereadDiscountApplied !== undefined ? { rereadDiscountApplied: receipt.rereadDiscountApplied } : {}),
481
+ ...(receipt.detectorId ? { detectorId: String(receipt.detectorId) } : {}),
482
+ ...(receipt.ring0Violation ? { ring0Violation: true } : {}),
484
483
  ...(receipt.turnId ? { turnId: String(receipt.turnId) } : {})
485
484
  };
486
485
 
@@ -556,6 +555,7 @@ export function recordInterventionSavings(params = {}, options = {}) {
556
555
  {
557
556
  sessionId,
558
557
  turnId: dedupeToken || undefined,
558
+ ...(params.cwd || options.cwd ? { cwd: String(params.cwd || options.cwd) } : {}),
559
559
  category,
560
560
  ledgerBucket: LEDGER_BUCKETS.AVOIDED_WRITE,
561
561
  modelId,
@@ -582,7 +582,12 @@ export function recordInterventionSavings(params = {}, options = {}) {
582
582
  return { recorded: res.ok, deduplicated: false, receipt: res.entry };
583
583
  };
584
584
 
585
- return dedupeShortKey ? withFileLockSync(dedupeIndexPath, writeUnderLock, options) : writeUnderLock();
585
+ return dedupeShortKey
586
+ ? withFileLockSync(dedupeIndexPath, writeUnderLock, {
587
+ ...options,
588
+ fallbackValue: { recorded: false, deduplicated: false, skippedByLockTimeout: true, receipt: null }
589
+ })
590
+ : writeUnderLock();
586
591
  }
587
592
 
588
593
  export function computeExPostRealizedSavings(params = {}) {