burnoff 1.0.0 → 1.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.
- package/.github/workflows/burnoff-pr-gate.yml +75 -0
- package/README.md +100 -14
- package/bin/burnoff.mjs +71 -16
- package/hooks/hook-io.mjs +8 -11
- package/package.json +3 -2
- package/src/ci/ci-gate.mjs +62 -9
- package/src/ci/pr-cost.mjs +167 -14
- package/src/ci/team-digest.mjs +1 -1
- package/src/cli/audit.mjs +74 -5
- package/src/cli/doctor.mjs +22 -12
- package/src/cli/init.mjs +92 -5
- package/src/cli/startup-audit.mjs +2348 -0
- package/src/config/catalog.json +188 -45
- package/src/config/loader.mjs +85 -9
- package/src/config/paths.mjs +30 -0
- package/src/config/policy.mjs +69 -12
- package/src/config/pricing.mjs +1022 -0
- package/src/config/uncached-attribution.mjs +719 -0
- package/src/guards/loop-breaker.mjs +72 -14
- package/src/guards/post-tool-engine.mjs +33 -12
- package/src/guards/pre-tool-engine.mjs +54 -2
- package/src/guards/read-clamp.mjs +73 -59
- package/src/guards/shell-guard.mjs +45 -19
- package/src/storage/atomic-io.mjs +2 -2
- package/src/storage/file-lock.mjs +53 -9
- package/src/storage/fts5-archive.mjs +27 -12
- package/src/storage/jsonl-parser.mjs +202 -19
- package/src/storage/ledger.mjs +7 -9
- package/src/storage/sqlite-client.mjs +31 -9
|
@@ -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
|
-
|
|
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]
|
|
@@ -399,8 +497,17 @@ export function parseClaudeCodeJsonl(rawContent = '') {
|
|
|
399
497
|
const model = msg?.model || node.model || null;
|
|
400
498
|
if (model) latestModel = model;
|
|
401
499
|
const createdAt = node.timestamp || node.created_at || node.createdAt || null;
|
|
500
|
+
const hasUsage = inputTokens > 0 || cacheReadTokens > 0 || cacheCreationTokens > 0 || outputTokens > 0;
|
|
501
|
+
const hadCompactionBefore = hasUsage ? pendingCompaction : false;
|
|
502
|
+
if (hasUsage) {
|
|
503
|
+
pendingCompaction = false;
|
|
504
|
+
}
|
|
505
|
+
const cacheTtlTier = cacheCreationEphemeral1hInputTokens > 0 ? '1h' : '5m';
|
|
506
|
+
const systemSubtype = node.type === 'system' ? (node.subtype || null) : null;
|
|
507
|
+
const stepToolsUsed = node.type === 'tools-used' && Array.isArray(node.tools) ? [...node.tools] : null;
|
|
508
|
+
const stepEntrypoint = node.entrypoint ? String(node.entrypoint) : latestEntrypoint;
|
|
402
509
|
|
|
403
|
-
if (
|
|
510
|
+
if (hasUsage) {
|
|
404
511
|
usageTurns.push({
|
|
405
512
|
stepIndex: steps.length,
|
|
406
513
|
freshInputTokens: inputTokens,
|
|
@@ -412,7 +519,14 @@ export function parseClaudeCodeJsonl(rawContent = '') {
|
|
|
412
519
|
totalPromptTokens,
|
|
413
520
|
outputTokens,
|
|
414
521
|
model: model || latestModel,
|
|
415
|
-
createdAt
|
|
522
|
+
createdAt,
|
|
523
|
+
hadCompactionBefore,
|
|
524
|
+
isCompactSummary: Boolean(node.isCompactSummary),
|
|
525
|
+
isCompactionBoundary: Boolean(isCompactionMarker),
|
|
526
|
+
isSidechain: Boolean(node.isSidechain),
|
|
527
|
+
shapeHash: latestShapeHash || null,
|
|
528
|
+
entrypoint: stepEntrypoint,
|
|
529
|
+
cacheTtlTier
|
|
416
530
|
});
|
|
417
531
|
}
|
|
418
532
|
|
|
@@ -422,8 +536,11 @@ export function parseClaudeCodeJsonl(rawContent = '') {
|
|
|
422
536
|
messageId: msg?.id || node.message_id || node.messageId || null,
|
|
423
537
|
source: isUser ? 'USER_EXPLICIT' : (isSummary ? 'SYSTEM' : 'MODEL'),
|
|
424
538
|
type: isSummary ? 'CHECKPOINT' : (isUser ? 'USER_INPUT' : 'PLANNER_RESPONSE'),
|
|
539
|
+
rawType: node.type || null,
|
|
540
|
+
systemSubtype,
|
|
425
541
|
status: 'DONE',
|
|
426
542
|
createdAt,
|
|
543
|
+
model: model || latestModel || null,
|
|
427
544
|
toolCalls,
|
|
428
545
|
content,
|
|
429
546
|
freshInputTokens: inputTokens,
|
|
@@ -437,7 +554,16 @@ export function parseClaudeCodeJsonl(rawContent = '') {
|
|
|
437
554
|
totalPromptEnvelopeTokens: totalPromptTokens,
|
|
438
555
|
thinkingTokens,
|
|
439
556
|
untruncatedLength: content.length,
|
|
440
|
-
isTruncated: false
|
|
557
|
+
isTruncated: false,
|
|
558
|
+
isCompactSummary: Boolean(node.isCompactSummary),
|
|
559
|
+
compactMetadata: node.compactMetadata || null,
|
|
560
|
+
isCompactionBoundary: Boolean(isCompactionMarker),
|
|
561
|
+
hadCompactionBefore,
|
|
562
|
+
isSidechain: Boolean(node.isSidechain),
|
|
563
|
+
shapeHash: latestShapeHash || null,
|
|
564
|
+
toolsUsed: stepToolsUsed,
|
|
565
|
+
entrypoint: stepEntrypoint,
|
|
566
|
+
cacheTtlTier
|
|
441
567
|
});
|
|
442
568
|
}
|
|
443
569
|
|
|
@@ -492,7 +618,9 @@ export function parseClaudeCodeJsonl(rawContent = '') {
|
|
|
492
618
|
rewindDetected: dag.rewindBranches.length > 0,
|
|
493
619
|
genMetadata,
|
|
494
620
|
sessionTitle,
|
|
495
|
-
workspacePath
|
|
621
|
+
workspacePath,
|
|
622
|
+
entrypoint: latestEntrypoint || dag.sessionEntrypoint || null,
|
|
623
|
+
toolsUsed: latestToolsUsed
|
|
496
624
|
};
|
|
497
625
|
}
|
|
498
626
|
|
|
@@ -563,6 +691,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
563
691
|
if (!filePath) {
|
|
564
692
|
return {
|
|
565
693
|
schemaRev: SCHEMA_REV,
|
|
694
|
+
attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
|
|
566
695
|
steps: [],
|
|
567
696
|
filePath: null,
|
|
568
697
|
lastByteOffset: 0,
|
|
@@ -571,7 +700,9 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
571
700
|
claudeDag: null,
|
|
572
701
|
genMetadata: null,
|
|
573
702
|
sessionTitle: '',
|
|
574
|
-
workspacePath: ''
|
|
703
|
+
workspacePath: '',
|
|
704
|
+
entrypoint: null,
|
|
705
|
+
toolsUsed: []
|
|
575
706
|
};
|
|
576
707
|
}
|
|
577
708
|
|
|
@@ -583,6 +714,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
583
714
|
|
|
584
715
|
let cached = {
|
|
585
716
|
schemaRev: 0,
|
|
717
|
+
attributionSchemaRev: 0,
|
|
586
718
|
lastByteOffset: 0,
|
|
587
719
|
prefixSha256: '',
|
|
588
720
|
filePath,
|
|
@@ -591,7 +723,9 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
591
723
|
claudeDag: null,
|
|
592
724
|
genMetadata: null,
|
|
593
725
|
sessionTitle: '',
|
|
594
|
-
workspacePath: ''
|
|
726
|
+
workspacePath: '',
|
|
727
|
+
entrypoint: null,
|
|
728
|
+
toolsUsed: []
|
|
595
729
|
};
|
|
596
730
|
let rewindDetected = false;
|
|
597
731
|
let cacheHit = false;
|
|
@@ -600,6 +734,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
600
734
|
if (
|
|
601
735
|
memCached &&
|
|
602
736
|
memCached.schemaRev === SCHEMA_REV &&
|
|
737
|
+
memCached.attributionSchemaRev === ATTRIBUTION_SCHEMA_REV &&
|
|
603
738
|
memCached.filePath === filePath &&
|
|
604
739
|
fs.existsSync(cacheFile)
|
|
605
740
|
) {
|
|
@@ -612,7 +747,11 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
612
747
|
} else if (fs.existsSync(cacheFile)) {
|
|
613
748
|
try {
|
|
614
749
|
const cachedData = JSON.parse(fs.readFileSync(cacheFile, 'utf8'));
|
|
615
|
-
if (
|
|
750
|
+
if (
|
|
751
|
+
cachedData.schemaRev === SCHEMA_REV &&
|
|
752
|
+
cachedData.attributionSchemaRev === ATTRIBUTION_SCHEMA_REV &&
|
|
753
|
+
cachedData.filePath === filePath
|
|
754
|
+
) {
|
|
616
755
|
if (cachedData.lastByteOffset <= stat.size && cachedData.prefixSha256 === currentPrefixSha256) {
|
|
617
756
|
cached = cachedData;
|
|
618
757
|
cacheHit = true;
|
|
@@ -629,6 +768,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
629
768
|
if (cacheHit && cached.lastByteOffset === stat.size) {
|
|
630
769
|
return {
|
|
631
770
|
schemaRev: SCHEMA_REV,
|
|
771
|
+
attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
|
|
632
772
|
steps: cached.steps,
|
|
633
773
|
filePath,
|
|
634
774
|
lastByteOffset: stat.size,
|
|
@@ -637,13 +777,22 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
637
777
|
claudeDag: cached.claudeDag || null,
|
|
638
778
|
genMetadata: cached.genMetadata || null,
|
|
639
779
|
sessionTitle: cached.sessionTitle || '',
|
|
640
|
-
workspacePath: cached.workspacePath || ''
|
|
780
|
+
workspacePath: cached.workspacePath || '',
|
|
781
|
+
entrypoint: cached.entrypoint || null,
|
|
782
|
+
toolsUsed: Array.isArray(cached.toolsUsed) ? cached.toolsUsed : []
|
|
641
783
|
};
|
|
642
784
|
}
|
|
643
785
|
|
|
644
786
|
if (cacheHit && cached.lastByteOffset < stat.size) {
|
|
645
|
-
const
|
|
646
|
-
|
|
787
|
+
const rawNewContent = readSliceUtf8FromFd(filePath, cached.lastByteOffset, stat.size);
|
|
788
|
+
const lastNewlineIdx = rawNewContent.lastIndexOf('\n');
|
|
789
|
+
const newContent = lastNewlineIdx === -1
|
|
790
|
+
? ''
|
|
791
|
+
: rawNewContent.slice(0, lastNewlineIdx + 1);
|
|
792
|
+
const nextByteOffset = newContent.length > 0
|
|
793
|
+
? cached.lastByteOffset + Buffer.byteLength(newContent, 'utf8')
|
|
794
|
+
: cached.lastByteOffset;
|
|
795
|
+
if (newContent && !/"leafUuid"/.test(newContent)) {
|
|
647
796
|
const parsedAppend = parseClaudeCodeJsonl(newContent);
|
|
648
797
|
const baseIdx = Array.isArray(cached.steps) ? cached.steps.length : 0;
|
|
649
798
|
const appendedSteps = parsedAppend.steps.map((s, idx) => ({ ...s, stepIndex: baseIdx + idx }));
|
|
@@ -662,20 +811,27 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
662
811
|
}
|
|
663
812
|
const mergedTitle = cached.sessionTitle || parsedAppend.sessionTitle || '';
|
|
664
813
|
const mergedWorkspace = cached.workspacePath || parsedAppend.workspacePath || '';
|
|
814
|
+
const mergedEntrypoint = cached.entrypoint || parsedAppend.entrypoint || null;
|
|
815
|
+
const mergedToolsUsed = (Array.isArray(parsedAppend.toolsUsed) && parsedAppend.toolsUsed.length > 0)
|
|
816
|
+
? parsedAppend.toolsUsed
|
|
817
|
+
: (Array.isArray(cached.toolsUsed) ? cached.toolsUsed : []);
|
|
665
818
|
const allSteps = [...(cached.steps || []), ...appendedSteps];
|
|
666
819
|
|
|
667
820
|
const updatedCachePayload = {
|
|
668
821
|
schemaRev: SCHEMA_REV,
|
|
822
|
+
attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
|
|
669
823
|
filePath,
|
|
670
824
|
prefixSha256: currentPrefixSha256,
|
|
671
|
-
lastByteOffset:
|
|
825
|
+
lastByteOffset: nextByteOffset,
|
|
672
826
|
mtimeMs: stat.mtimeMs,
|
|
673
827
|
steps: allSteps,
|
|
674
828
|
rewindDetected,
|
|
675
829
|
claudeDag: cached.claudeDag || null,
|
|
676
830
|
genMetadata: mergedGenMetadata,
|
|
677
831
|
sessionTitle: mergedTitle,
|
|
678
|
-
workspacePath: mergedWorkspace
|
|
832
|
+
workspacePath: mergedWorkspace,
|
|
833
|
+
entrypoint: mergedEntrypoint,
|
|
834
|
+
toolsUsed: mergedToolsUsed
|
|
679
835
|
};
|
|
680
836
|
if (incrementalMemCache.size > 24) incrementalMemCache.clear();
|
|
681
837
|
incrementalMemCache.set(cacheFile, updatedCachePayload);
|
|
@@ -686,15 +842,35 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
686
842
|
}
|
|
687
843
|
return {
|
|
688
844
|
schemaRev: SCHEMA_REV,
|
|
845
|
+
attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
|
|
689
846
|
steps: allSteps,
|
|
690
847
|
filePath,
|
|
691
|
-
lastByteOffset:
|
|
848
|
+
lastByteOffset: nextByteOffset,
|
|
692
849
|
prefixSha256: currentPrefixSha256,
|
|
693
850
|
rewindDetected,
|
|
694
851
|
claudeDag: cached.claudeDag || null,
|
|
695
852
|
genMetadata: mergedGenMetadata,
|
|
696
853
|
sessionTitle: mergedTitle,
|
|
697
|
-
workspacePath: mergedWorkspace
|
|
854
|
+
workspacePath: mergedWorkspace,
|
|
855
|
+
entrypoint: mergedEntrypoint,
|
|
856
|
+
toolsUsed: mergedToolsUsed
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
if (!newContent) {
|
|
860
|
+
return {
|
|
861
|
+
schemaRev: SCHEMA_REV,
|
|
862
|
+
attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
|
|
863
|
+
steps: cached.steps,
|
|
864
|
+
filePath,
|
|
865
|
+
lastByteOffset: cached.lastByteOffset,
|
|
866
|
+
prefixSha256: currentPrefixSha256,
|
|
867
|
+
rewindDetected: false,
|
|
868
|
+
claudeDag: cached.claudeDag || null,
|
|
869
|
+
genMetadata: cached.genMetadata || null,
|
|
870
|
+
sessionTitle: cached.sessionTitle || '',
|
|
871
|
+
workspacePath: cached.workspacePath || '',
|
|
872
|
+
entrypoint: cached.entrypoint || null,
|
|
873
|
+
toolsUsed: Array.isArray(cached.toolsUsed) ? cached.toolsUsed : []
|
|
698
874
|
};
|
|
699
875
|
}
|
|
700
876
|
}
|
|
@@ -717,6 +893,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
717
893
|
const finalRewind = rewindDetected || Boolean(parsedClaude.rewindDetected);
|
|
718
894
|
const updatedCachePayload = {
|
|
719
895
|
schemaRev: SCHEMA_REV,
|
|
896
|
+
attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
|
|
720
897
|
filePath,
|
|
721
898
|
prefixSha256: currentPrefixSha256,
|
|
722
899
|
lastByteOffset: stat.size,
|
|
@@ -726,7 +903,9 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
726
903
|
claudeDag: parsedClaude.claudeDag,
|
|
727
904
|
genMetadata: parsedClaude.genMetadata,
|
|
728
905
|
sessionTitle: parsedClaude.sessionTitle,
|
|
729
|
-
workspacePath: parsedClaude.workspacePath
|
|
906
|
+
workspacePath: parsedClaude.workspacePath,
|
|
907
|
+
entrypoint: parsedClaude.entrypoint,
|
|
908
|
+
toolsUsed: parsedClaude.toolsUsed
|
|
730
909
|
};
|
|
731
910
|
if (incrementalMemCache.size > 24) incrementalMemCache.clear();
|
|
732
911
|
incrementalMemCache.set(cacheFile, updatedCachePayload);
|
|
@@ -738,6 +917,7 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
738
917
|
|
|
739
918
|
return {
|
|
740
919
|
schemaRev: SCHEMA_REV,
|
|
920
|
+
attributionSchemaRev: ATTRIBUTION_SCHEMA_REV,
|
|
741
921
|
steps: parsedClaude.steps,
|
|
742
922
|
filePath,
|
|
743
923
|
lastByteOffset: stat.size,
|
|
@@ -746,12 +926,15 @@ export function parseTranscriptIncremental(transcriptPathOrDir, cacheDir = null,
|
|
|
746
926
|
claudeDag: parsedClaude.claudeDag,
|
|
747
927
|
genMetadata: parsedClaude.genMetadata,
|
|
748
928
|
sessionTitle: parsedClaude.sessionTitle,
|
|
749
|
-
workspacePath: parsedClaude.workspacePath
|
|
929
|
+
workspacePath: parsedClaude.workspacePath,
|
|
930
|
+
entrypoint: parsedClaude.entrypoint,
|
|
931
|
+
toolsUsed: parsedClaude.toolsUsed
|
|
750
932
|
};
|
|
751
933
|
}
|
|
752
934
|
|
|
753
935
|
export default {
|
|
754
936
|
SCHEMA_REV,
|
|
937
|
+
ATTRIBUTION_SCHEMA_REV,
|
|
755
938
|
DEFAULT_CLAUDE_TAIL_BYTES,
|
|
756
939
|
stitchClaudeCodeDag,
|
|
757
940
|
discoverClaudeCodeSessions,
|
package/src/storage/ledger.mjs
CHANGED
|
@@ -123,20 +123,14 @@ 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
|
-
|
|
134
|
-
|
|
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 homeDir = options.homeDir || getHomeDir(options);
|
|
133
|
+
return path.join(getBurnoffLedgerDir(homeDir), 'burnoff_ledger.jsonl');
|
|
140
134
|
}
|
|
141
135
|
|
|
142
136
|
export function getLedgerMonthKey(tsMs = Date.now()) {
|
|
@@ -471,6 +465,7 @@ export function recordSavingsReceipt(receipt = {}, options = {}) {
|
|
|
471
465
|
savedTokens,
|
|
472
466
|
savedUSD,
|
|
473
467
|
detail: String(receipt.detail || ''),
|
|
468
|
+
...((receipt.cwd || options.cwd) ? { cwd: String(receipt.cwd || options.cwd) } : {}),
|
|
474
469
|
...(wallClock.seconds > 0
|
|
475
470
|
? {
|
|
476
471
|
savedWallClockSeconds: wallClock.seconds,
|
|
@@ -481,6 +476,8 @@ export function recordSavingsReceipt(receipt = {}, options = {}) {
|
|
|
481
476
|
...(receipt.exPost && typeof receipt.exPost === 'object' ? { exPost: receipt.exPost } : {}),
|
|
482
477
|
...(receipt.rawClampedTokens !== undefined ? { rawClampedTokens: receipt.rawClampedTokens } : {}),
|
|
483
478
|
...(receipt.rereadDiscountApplied !== undefined ? { rereadDiscountApplied: receipt.rereadDiscountApplied } : {}),
|
|
479
|
+
...(receipt.detectorId ? { detectorId: String(receipt.detectorId) } : {}),
|
|
480
|
+
...(receipt.ring0Violation ? { ring0Violation: true } : {}),
|
|
484
481
|
...(receipt.turnId ? { turnId: String(receipt.turnId) } : {})
|
|
485
482
|
};
|
|
486
483
|
|
|
@@ -556,6 +553,7 @@ export function recordInterventionSavings(params = {}, options = {}) {
|
|
|
556
553
|
{
|
|
557
554
|
sessionId,
|
|
558
555
|
turnId: dedupeToken || undefined,
|
|
556
|
+
...(params.cwd || options.cwd ? { cwd: String(params.cwd || options.cwd) } : {}),
|
|
559
557
|
category,
|
|
560
558
|
ledgerBucket: LEDGER_BUCKETS.AVOIDED_WRITE,
|
|
561
559
|
modelId,
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { suppressSqliteExperimentalWarning } from '../config/paths.mjs';
|
|
4
|
+
import { atomicWriteFileSync } from './atomic-io.mjs';
|
|
5
|
+
import { withFileLockSync } from './file-lock.mjs';
|
|
4
6
|
|
|
5
7
|
const BURNOFF_OWNED_DB_DIR_RE = /(?:^|[\\/])(?:\.burnoff|\.claude)(?:[\\/]|$)/i;
|
|
6
8
|
|
|
@@ -300,6 +302,21 @@ export function enforceOwnerOnlyDbPermissions(filePath = '') {
|
|
|
300
302
|
}
|
|
301
303
|
}
|
|
302
304
|
|
|
305
|
+
export function resolveFallbackDbPath(dbPath = '') {
|
|
306
|
+
if (!dbPath || dbPath === ':memory:' || String(dbPath).startsWith('file:')) {
|
|
307
|
+
return dbPath;
|
|
308
|
+
}
|
|
309
|
+
const resolved = path.resolve(dbPath);
|
|
310
|
+
const base = path.basename(resolved);
|
|
311
|
+
if (base.toLowerCase() === 'tool_logs_fts5.db') {
|
|
312
|
+
return path.join(path.dirname(resolved), 'tool_logs_fallback.json');
|
|
313
|
+
}
|
|
314
|
+
if (/\.(?:db|sqlite3?)$/i.test(base)) {
|
|
315
|
+
return path.join(path.dirname(resolved), base.replace(/\.(?:db|sqlite3?)$/i, '_fallback.json'));
|
|
316
|
+
}
|
|
317
|
+
return resolved;
|
|
318
|
+
}
|
|
319
|
+
|
|
303
320
|
/**
|
|
304
321
|
* Pure-JS JSON fallback database adapter for Node 20 LTS runtimes (where built-in `node:sqlite`
|
|
305
322
|
* is absent) or when `BURNOFF_FORCE_NO_SQLITE=1` is set.
|
|
@@ -309,14 +326,19 @@ export class JsonlFallbackDatabaseSync {
|
|
|
309
326
|
this.dbPath = dbPath;
|
|
310
327
|
this.readOnly = Boolean(options.readOnly || options.readonly);
|
|
311
328
|
this.isMemory = !dbPath || dbPath === ':memory:' || String(dbPath).startsWith('file:');
|
|
329
|
+
this.storagePath = this.isMemory ? dbPath : resolveFallbackDbPath(dbPath);
|
|
312
330
|
this.tables = {};
|
|
313
331
|
this._load();
|
|
314
332
|
}
|
|
315
333
|
|
|
316
334
|
_load() {
|
|
317
|
-
if (this.isMemory
|
|
335
|
+
if (this.isMemory) return;
|
|
336
|
+
const candidatePath = fs.existsSync(this.storagePath)
|
|
337
|
+
? this.storagePath
|
|
338
|
+
: (this.dbPath !== this.storagePath && fs.existsSync(this.dbPath) ? this.dbPath : null);
|
|
339
|
+
if (!candidatePath) return;
|
|
318
340
|
try {
|
|
319
|
-
const raw = fs.readFileSync(
|
|
341
|
+
const raw = fs.readFileSync(candidatePath, 'utf8').trim();
|
|
320
342
|
if (raw.startsWith('{')) {
|
|
321
343
|
const parsed = JSON.parse(raw);
|
|
322
344
|
if (parsed && typeof parsed.tables === 'object') {
|
|
@@ -331,13 +353,12 @@ export class JsonlFallbackDatabaseSync {
|
|
|
331
353
|
_flush() {
|
|
332
354
|
if (this.isMemory || this.readOnly) return;
|
|
333
355
|
try {
|
|
334
|
-
fs.mkdirSync(path.dirname(this.
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
);
|
|
340
|
-
enforceOwnerOnlyDbPermissions(this.dbPath);
|
|
356
|
+
fs.mkdirSync(path.dirname(this.storagePath), { recursive: true, mode: 0o700 });
|
|
357
|
+
const payload = JSON.stringify({ fallbackFormat: 'json-v1', tables: this.tables });
|
|
358
|
+
withFileLockSync(this.storagePath, () => {
|
|
359
|
+
atomicWriteFileSync(this.storagePath, payload, { encoding: 'utf8', mode: 0o600 });
|
|
360
|
+
enforceOwnerOnlyDbPermissions(this.storagePath);
|
|
361
|
+
});
|
|
341
362
|
} catch {
|
|
342
363
|
// ignore: best-effort persistence in fallback mode
|
|
343
364
|
}
|
|
@@ -559,6 +580,7 @@ export function openBurnoffDb(dbPath, { readOnly = false, readonly = false, busy
|
|
|
559
580
|
export default {
|
|
560
581
|
probeSqliteBuiltin,
|
|
561
582
|
getDatabaseSyncClass,
|
|
583
|
+
resolveFallbackDbPath,
|
|
562
584
|
JsonlFallbackDatabaseSync,
|
|
563
585
|
resolveDatabaseSync,
|
|
564
586
|
enforceOwnerOnlyDbPermissions,
|