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.
- package/.github/workflows/burnoff-pr-gate.yml +75 -0
- package/README.md +94 -20
- package/bin/burnoff.mjs +129 -30
- package/hooks/hook-io.mjs +27 -18
- package/hooks/post-tool-use.mjs +33 -26
- package/hooks/pre-tool-use.mjs +43 -41
- package/hooks/session-lifecycle.mjs +40 -0
- package/package.json +8 -5
- package/src/ci/ci-gate.mjs +84 -9
- package/src/ci/pr-cost.mjs +207 -22
- package/src/ci/team-digest.mjs +6 -4
- package/src/cli/audit.mjs +177 -23
- package/src/cli/doctor.mjs +230 -25
- package/src/cli/init.mjs +415 -75
- package/src/cli/startup-audit.mjs +2824 -0
- package/src/clients/antigravity.mjs +285 -0
- package/src/clients/claude-code.mjs +180 -0
- package/src/clients/detect.mjs +64 -0
- package/src/config/catalog.json +188 -45
- package/src/config/loader.mjs +96 -13
- package/src/config/paths.mjs +92 -2
- package/src/config/policy.mjs +103 -17
- package/src/config/pricing.mjs +1033 -0
- package/src/config/uncached-attribution.mjs +719 -0
- package/src/guards/loop-breaker.mjs +267 -24
- package/src/guards/post-tool-engine.mjs +316 -35
- package/src/guards/pre-tool-engine.mjs +389 -130
- package/src/guards/read-clamp.mjs +149 -75
- package/src/guards/session-hook.mjs +207 -0
- package/src/guards/shell-guard.mjs +610 -74
- package/src/ipc/daemon.mjs +50 -8
- package/src/ipc/fast-client.mjs +62 -5
- package/src/ipc/protocol.mjs +1 -1
- package/src/storage/antigravity-parser.mjs +258 -0
- package/src/storage/atomic-io.mjs +2 -2
- package/src/storage/file-lock.mjs +66 -13
- package/src/storage/fts5-archive.mjs +31 -16
- package/src/storage/jsonl-parser.mjs +209 -20
- package/src/storage/ledger.mjs +15 -10
- package/src/storage/sqlite-client.mjs +35 -11
- package/hooks/hooks.json +0 -12
|
@@ -7,8 +7,9 @@
|
|
|
7
7
|
import fs from 'node:fs';
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import crypto from 'node:crypto';
|
|
10
|
-
import { resolveEffectiveRates
|
|
10
|
+
import { resolveEffectiveRates } from '../config/loader.mjs';
|
|
11
11
|
import { loadBurnoffPolicy } from '../config/policy.mjs';
|
|
12
|
+
import { getWorkspaceStateDir } from '../config/paths.mjs';
|
|
12
13
|
import { withFileLockSync } from '../storage/file-lock.mjs';
|
|
13
14
|
import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
|
|
14
15
|
import { recordInterventionSavings } from '../storage/ledger.mjs';
|
|
@@ -32,6 +33,7 @@ export const MEASURED_REREAD_P_CODE = 0.73; // 0.27 realization factor (1 - 0.73
|
|
|
32
33
|
export const MEASURED_REREAD_P_DOC = 0.15;
|
|
33
34
|
export const MEASURED_SOLO_TURN_P_GIVEN_REREAD = 0.19;
|
|
34
35
|
export const ASSUMED_MIN_PROMPT_TOKENS = 20_000;
|
|
36
|
+
export const DEFAULT_READ_INTERVAL_TTL_MS = 30 * 60 * 1000;
|
|
35
37
|
|
|
36
38
|
const BURNOFF_CACHE_ARTIFACT_PATH_RE =
|
|
37
39
|
/(?:^|\/)(?:\.claude\/cache\/artifacts|\.burnoff\/cache)(?:\/|$)/i;
|
|
@@ -39,6 +41,7 @@ const GENERATED_OR_MINIFIED_CODE_RE =
|
|
|
39
41
|
/(?:\.min|\.bundle|\.chunk)\.(?:m?js|cjs|css)$|(?:^|\/)(?:node_modules|dist|build|vendor|\.next|coverage)(?:\/|$)/i;
|
|
40
42
|
const ACTIVE_SOURCE_CODE_EXT_RE =
|
|
41
43
|
/\.(?:mjs|cjs|js|jsx|ts|tsx|py|go|rs|java|kt|kts|cs|cpp|cc|cxx|c|h|hpp|rb|php|swift|scala|vue|svelte|sql|sh|bash|zsh|ps1)$/i;
|
|
44
|
+
export const STRUCTURED_DATA_EXT_RE = /\.(?:json|yaml|yml|toml|xml|csv)$/i;
|
|
42
45
|
|
|
43
46
|
export function isBurnoffArtifactPath(filePath = '') {
|
|
44
47
|
const norm = String(filePath || '').replace(/\\/g, '/').trim();
|
|
@@ -56,6 +59,25 @@ export function isActiveSourceCodePath(filePath = '') {
|
|
|
56
59
|
return ACTIVE_SOURCE_CODE_EXT_RE.test(raw);
|
|
57
60
|
}
|
|
58
61
|
|
|
62
|
+
export function isStructuredDataPath(filePath = '') {
|
|
63
|
+
const raw = String(filePath || '').trim();
|
|
64
|
+
if (!raw || isGeneratedOrMinifiedCodePath(raw)) return false;
|
|
65
|
+
return STRUCTURED_DATA_EXT_RE.test(raw);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function matchesNeverClampExt(filePath = '', neverClampExt = []) {
|
|
69
|
+
if (!Array.isArray(neverClampExt) || neverClampExt.length === 0) return false;
|
|
70
|
+
const ext = path.extname(String(filePath || '').trim()).toLowerCase();
|
|
71
|
+
if (!ext) return false;
|
|
72
|
+
for (const item of neverClampExt) {
|
|
73
|
+
const norm = String(item || '').trim().toLowerCase();
|
|
74
|
+
if (!norm) continue;
|
|
75
|
+
const dotted = norm.startsWith('.') ? norm : `.${norm}`;
|
|
76
|
+
if (dotted === ext) return true;
|
|
77
|
+
}
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
|
|
59
81
|
export function computeByteBoundedSliceWindow(
|
|
60
82
|
lines = [],
|
|
61
83
|
targetBytes = CLAMP_TARGET_BYTES,
|
|
@@ -169,12 +191,14 @@ export function evaluateClampExpectedValue({
|
|
|
169
191
|
export function evaluateShieldReadGuard({
|
|
170
192
|
sessionId = 'default',
|
|
171
193
|
cwd = process.cwd(),
|
|
194
|
+
homeDir,
|
|
172
195
|
filePath = '',
|
|
173
196
|
hasSliceBounds = false,
|
|
174
197
|
sliceOffset = null,
|
|
175
198
|
sliceLimit = null,
|
|
176
199
|
currentPromptTokens = 0,
|
|
177
|
-
modelId = 'claude-sonnet-
|
|
200
|
+
modelId = 'claude-sonnet-5-5',
|
|
201
|
+
policy: providedPolicy = null,
|
|
178
202
|
shieldConfig = null,
|
|
179
203
|
forceActive = false,
|
|
180
204
|
recordLedger = true,
|
|
@@ -196,7 +220,7 @@ export function evaluateShieldReadGuard({
|
|
|
196
220
|
return { action: 'allow' };
|
|
197
221
|
}
|
|
198
222
|
|
|
199
|
-
const policy = loadBurnoffPolicy(baseCwd);
|
|
223
|
+
const policy = providedPolicy || loadBurnoffPolicy(baseCwd);
|
|
200
224
|
const rc = policy.readClamp || {};
|
|
201
225
|
const enabled = forceActive || (shieldConfig?.enabled !== undefined ? Boolean(shieldConfig.enabled) : rc.enabled !== false);
|
|
202
226
|
const headProbeMaxBytes = Math.max(
|
|
@@ -207,6 +231,9 @@ export function evaluateShieldReadGuard({
|
|
|
207
231
|
shieldConfig?.neverClampCodeOffCliff !== undefined
|
|
208
232
|
? Boolean(shieldConfig.neverClampCodeOffCliff)
|
|
209
233
|
: rc.neverClampCodeOffCliff !== false;
|
|
234
|
+
const neverClampExt = Array.isArray(shieldConfig?.neverClampExt)
|
|
235
|
+
? shieldConfig.neverClampExt
|
|
236
|
+
: (Array.isArray(rc.neverClampExt) ? rc.neverClampExt : []);
|
|
210
237
|
const codeCeilingBytes = Math.max(
|
|
211
238
|
16_384,
|
|
212
239
|
Number(shieldConfig?.codeNeverClampCeilingBytes ?? NEVER_TRIM_CODE_HARD_CEILING_BYTES)
|
|
@@ -221,9 +248,11 @@ export function evaluateShieldReadGuard({
|
|
|
221
248
|
const cfgSliceLines = Number(shieldConfig?.maxSliceLines ?? DEFAULT_MAX_SLICE_LINES);
|
|
222
249
|
const cfgSliceBytes = Number(shieldConfig?.maxSliceBytes ?? DEFAULT_MAX_SLICE_BYTES);
|
|
223
250
|
|
|
224
|
-
const cliffObj = getModelPricingCliff(modelId, { cwd: baseCwd });
|
|
225
|
-
const cliffTokens = cliffObj ? Number(cliffObj.thresholdTokens || 0) : 0;
|
|
226
251
|
const promptTok = Math.max(0, Number(currentPromptTokens) || 0);
|
|
252
|
+
const baseRates = promptTok > 0
|
|
253
|
+
? resolveEffectiveRates(modelId, promptTok, { cwd: baseCwd, homeDir })
|
|
254
|
+
: null;
|
|
255
|
+
const cliffTokens = baseRates?.cliffThresholdTokens ? Number(baseRates.cliffThresholdTokens) : 0;
|
|
227
256
|
const nearCliff = cliffTokens > 0 && promptTok >= Math.floor(cliffTokens * 0.9);
|
|
228
257
|
|
|
229
258
|
if (!enabled && !nearCliff) {
|
|
@@ -310,7 +339,9 @@ export function evaluateShieldReadGuard({
|
|
|
310
339
|
const isCode = isActiveSourceCodePath(absFile);
|
|
311
340
|
const realizedFactor = isCode ? codeRealizationFactor : 1 - MEASURED_REREAD_P_DOC;
|
|
312
341
|
const realizedClampSavedTokens = Math.max(0, Math.round(clampSavedTokens * realizedFactor));
|
|
313
|
-
const rates =
|
|
342
|
+
const rates = recordLedger
|
|
343
|
+
? (baseRates || resolveEffectiveRates(modelId, promptTok, { cwd: baseCwd, homeDir }))
|
|
344
|
+
: null;
|
|
314
345
|
const clampSavedUSD = rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
|
|
315
346
|
? Number(((realizedClampSavedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
|
|
316
347
|
: 0;
|
|
@@ -328,6 +359,7 @@ export function evaluateShieldReadGuard({
|
|
|
328
359
|
recordInterventionSavings(
|
|
329
360
|
{
|
|
330
361
|
sessionId,
|
|
362
|
+
cwd: baseCwd,
|
|
331
363
|
category: 'BOUNDED_READ_ENFORCED',
|
|
332
364
|
modelId,
|
|
333
365
|
savedTokens: realizedClampSavedTokens,
|
|
@@ -337,7 +369,7 @@ export function evaluateShieldReadGuard({
|
|
|
337
369
|
dedupeId: `huge_clamp:${dedupeHash}`,
|
|
338
370
|
detail: `Fast-clamped huge file ${displayFile} (${(stat.size / (1024 * 1024)).toFixed(1)} MB)`
|
|
339
371
|
},
|
|
340
|
-
{ cwd: baseCwd, ...(ledgerPath ? { ledgerPath } : {}) }
|
|
372
|
+
{ cwd: baseCwd, skipFsync: true, ...(homeDir ? { homeDir } : {}), ...(ledgerPath ? { ledgerPath } : {}) }
|
|
341
373
|
);
|
|
342
374
|
}
|
|
343
375
|
|
|
@@ -388,6 +420,32 @@ export function evaluateShieldReadGuard({
|
|
|
388
420
|
return { action: 'allow' };
|
|
389
421
|
}
|
|
390
422
|
|
|
423
|
+
if (!nearCliff && matchesNeverClampExt(absFile, neverClampExt)) {
|
|
424
|
+
return {
|
|
425
|
+
action: 'allow',
|
|
426
|
+
neverClampExtBypassed: true,
|
|
427
|
+
neverTrimReason: 'policy_never_clamp_ext',
|
|
428
|
+
fileBytes: stat.size,
|
|
429
|
+
sliceBytes: targetBytes
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
if (
|
|
434
|
+
!nearCliff &&
|
|
435
|
+
isStructuredDataPath(absFile) &&
|
|
436
|
+
stat.size < NEVER_TRIM_CODE_HARD_CEILING_BYTES &&
|
|
437
|
+
targetBytes < NEVER_TRIM_CODE_HARD_CEILING_BYTES
|
|
438
|
+
) {
|
|
439
|
+
return {
|
|
440
|
+
action: 'allow',
|
|
441
|
+
structuredDataNeverClampBypassed: true,
|
|
442
|
+
neverTrimReason: 'structured_data_under_128kb',
|
|
443
|
+
fileBytes: stat.size,
|
|
444
|
+
sliceBytes: targetBytes,
|
|
445
|
+
ceilingBytes: NEVER_TRIM_CODE_HARD_CEILING_BYTES
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
391
449
|
if (
|
|
392
450
|
neverClampCodeOffCliff &&
|
|
393
451
|
!nearCliff &&
|
|
@@ -478,6 +536,7 @@ export function evaluateShieldReadGuard({
|
|
|
478
536
|
recordInterventionSavings(
|
|
479
537
|
{
|
|
480
538
|
sessionId,
|
|
539
|
+
cwd: baseCwd,
|
|
481
540
|
category: 'BOUNDED_READ_ENFORCED',
|
|
482
541
|
modelId,
|
|
483
542
|
savedTokens: realizedClampSavedTokens,
|
|
@@ -487,7 +546,7 @@ export function evaluateShieldReadGuard({
|
|
|
487
546
|
dedupeId: `clamp:${clampDedupeHash}`,
|
|
488
547
|
detail: `Clamped read of ${displayFile} (${reqOffset}..${clampEnd} of ${totalLines} lines)`
|
|
489
548
|
},
|
|
490
|
-
{ cwd: baseCwd, ...(ledgerPath ? { ledgerPath } : {}) }
|
|
549
|
+
{ cwd: baseCwd, skipFsync: true, ...(homeDir ? { homeDir } : {}), ...(ledgerPath ? { ledgerPath } : {}) }
|
|
491
550
|
);
|
|
492
551
|
}
|
|
493
552
|
|
|
@@ -512,14 +571,20 @@ export function evaluateShieldReadGuard({
|
|
|
512
571
|
};
|
|
513
572
|
}
|
|
514
573
|
|
|
515
|
-
export function getReadSnapFilePath(baseCwd, sessionId = 'default') {
|
|
574
|
+
export function getReadSnapFilePath(baseCwd, sessionId = 'default', options = {}) {
|
|
516
575
|
if (!baseCwd) return '';
|
|
517
|
-
const safeSid =
|
|
576
|
+
const safeSid =
|
|
577
|
+
typeof sessionId === 'string' && sessionId.trim()
|
|
578
|
+
? sessionId.trim().replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 64) || 'default'
|
|
579
|
+
: 'default';
|
|
580
|
+
if (options?.client === 'antigravity') {
|
|
581
|
+
return path.join(getWorkspaceStateDir(baseCwd, options.homeDir), `read_snapshots_${safeSid}.json`);
|
|
582
|
+
}
|
|
518
583
|
return path.join(path.resolve(String(baseCwd)), '.claude', 'cache', `read_snapshots_${safeSid}.json`);
|
|
519
584
|
}
|
|
520
585
|
|
|
521
|
-
export function loadReadSnapStore(baseCwd, sessionId = 'default') {
|
|
522
|
-
const snapFilePath = getReadSnapFilePath(baseCwd, sessionId);
|
|
586
|
+
export function loadReadSnapStore(baseCwd, sessionId = 'default', options = {}) {
|
|
587
|
+
const snapFilePath = getReadSnapFilePath(baseCwd, sessionId, options);
|
|
523
588
|
let store = {};
|
|
524
589
|
if (snapFilePath && fs.existsSync(snapFilePath)) {
|
|
525
590
|
try {
|
|
@@ -560,7 +625,7 @@ export function mergeLineIntervals(intervals = []) {
|
|
|
560
625
|
|
|
561
626
|
/**
|
|
562
627
|
* Checks whether `[reqStart, reqEnd]` overlaps already-in-context intervals and returns a
|
|
563
|
-
* contiguous unread trim
|
|
628
|
+
* contiguous unread trim when partial overlap is substantial.
|
|
564
629
|
*/
|
|
565
630
|
export function trimRequestedRangeAgainstIntervals(reqStart, reqEnd, rawIntervals = []) {
|
|
566
631
|
const start = Math.max(1, Math.floor(Number(reqStart) || 1));
|
|
@@ -593,14 +658,6 @@ export function trimRequestedRangeAgainstIntervals(reqStart, reqEnd, rawInterval
|
|
|
593
658
|
}
|
|
594
659
|
|
|
595
660
|
if (overlapLines === 0) return { status: 'none' };
|
|
596
|
-
if (overlapLines >= reqLen && reqLen >= 25) {
|
|
597
|
-
return {
|
|
598
|
-
status: 'full_covered',
|
|
599
|
-
anchorOffset: start,
|
|
600
|
-
anchorLimit: 5,
|
|
601
|
-
savedLines: reqLen - 5
|
|
602
|
-
};
|
|
603
|
-
}
|
|
604
661
|
if (
|
|
605
662
|
uncovered.length === 1 &&
|
|
606
663
|
overlapLines >= Math.ceil(reqLen * 0.5) &&
|
|
@@ -617,7 +674,7 @@ export function trimRequestedRangeAgainstIntervals(reqStart, reqEnd, rawInterval
|
|
|
617
674
|
return { status: 'none' };
|
|
618
675
|
}
|
|
619
676
|
|
|
620
|
-
export function recordReadIntervalEntry(store, normKey, statObj, startLine, endLine) {
|
|
677
|
+
export function recordReadIntervalEntry(store, normKey, statObj, startLine, endLine, nowMs = Date.now()) {
|
|
621
678
|
if (!store || !normKey || !statObj || endLine < startLine) return;
|
|
622
679
|
if (!store.__readIntervals || typeof store.__readIntervals !== 'object') {
|
|
623
680
|
store.__readIntervals = {};
|
|
@@ -628,76 +685,89 @@ export function recordReadIntervalEntry(store, normKey, statObj, startLine, endL
|
|
|
628
685
|
Number(prev.mtimeMs) === Number(statObj.mtimeMs) &&
|
|
629
686
|
Number(prev.size) === Number(statObj.size);
|
|
630
687
|
const existing = sameStat && Array.isArray(prev.intervals) ? prev.intervals : [];
|
|
688
|
+
const recordedAt = Number.isFinite(Number(nowMs)) ? Number(nowMs) : Date.now();
|
|
631
689
|
store.__readIntervals[normKey] = {
|
|
632
690
|
mtimeMs: Number(statObj.mtimeMs),
|
|
633
691
|
size: Number(statObj.size),
|
|
692
|
+
recordedAt,
|
|
634
693
|
intervals: mergeLineIntervals([...existing, [startLine, endLine]])
|
|
635
694
|
};
|
|
636
695
|
}
|
|
637
696
|
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
697
|
+
function writeReadSnapStoreUnlocked(
|
|
698
|
+
snapFilePath,
|
|
699
|
+
store,
|
|
700
|
+
{ clearIntervalKeys = [], clearAllIntervals = false } = {}
|
|
701
|
+
) {
|
|
702
|
+
let diskStore = {};
|
|
703
|
+
if (fs.existsSync(snapFilePath)) {
|
|
704
|
+
try {
|
|
705
|
+
const parsed = JSON.parse(fs.readFileSync(snapFilePath, 'utf8'));
|
|
706
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) diskStore = parsed;
|
|
707
|
+
} catch (err) {
|
|
708
|
+
void err; // ignore: corrupt snapshot overwritten cleanly
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
const mergedStore = { ...diskStore, ...store };
|
|
712
|
+
if (clearAllIntervals) {
|
|
713
|
+
mergedStore.__readIntervals = {};
|
|
714
|
+
} else if (diskStore.__readIntervals || store.__readIntervals) {
|
|
715
|
+
const nextIntervals = { ...(diskStore.__readIntervals || {}) };
|
|
716
|
+
for (const [k, v] of Object.entries(store.__readIntervals || {})) {
|
|
717
|
+
const prev = nextIntervals[k];
|
|
718
|
+
if (
|
|
719
|
+
prev &&
|
|
720
|
+
v &&
|
|
721
|
+
Number(prev.mtimeMs) === Number(v.mtimeMs) &&
|
|
722
|
+
Number(prev.size) === Number(v.size)
|
|
723
|
+
) {
|
|
724
|
+
const recordedAt =
|
|
725
|
+
Math.max(Number(prev.recordedAt || 0), Number(v.recordedAt || 0)) || Date.now();
|
|
726
|
+
nextIntervals[k] = {
|
|
727
|
+
mtimeMs: Number(v.mtimeMs),
|
|
728
|
+
size: Number(v.size),
|
|
729
|
+
recordedAt,
|
|
730
|
+
intervals: mergeLineIntervals([...(prev.intervals || []), ...(v.intervals || [])])
|
|
731
|
+
};
|
|
732
|
+
} else {
|
|
733
|
+
nextIntervals[k] = v && typeof v === 'object' && !v.recordedAt
|
|
734
|
+
? { ...v, recordedAt: Date.now() }
|
|
735
|
+
: v;
|
|
677
736
|
}
|
|
737
|
+
}
|
|
738
|
+
for (const delKey of clearIntervalKeys) {
|
|
739
|
+
delete nextIntervals[delKey];
|
|
740
|
+
}
|
|
741
|
+
mergedStore.__readIntervals = nextIntervals;
|
|
742
|
+
}
|
|
678
743
|
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
744
|
+
if (mergedStore.__readIntervals && typeof mergedStore.__readIntervals === 'object') {
|
|
745
|
+
const intervalKeys = Object.keys(mergedStore.__readIntervals);
|
|
746
|
+
while (intervalKeys.length > 24) {
|
|
747
|
+
const oldestInterval = intervalKeys.shift();
|
|
748
|
+
delete mergedStore.__readIntervals[oldestInterval];
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
atomicWriteFileSync(snapFilePath, JSON.stringify(mergedStore), { encoding: 'utf8' });
|
|
752
|
+
return mergedStore;
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
export function saveReadSnapStore(snapFilePath, store, options = {}) {
|
|
756
|
+
if (!snapFilePath) return;
|
|
757
|
+
try {
|
|
758
|
+
withFileLockSync(snapFilePath, () => writeReadSnapStoreUnlocked(snapFilePath, store, options));
|
|
688
759
|
} catch (writeErr) {
|
|
689
760
|
void writeErr; // ignore: non-fatal read snapshot persistence
|
|
690
761
|
}
|
|
691
762
|
}
|
|
692
763
|
|
|
693
|
-
export function updateReadSnapStoreAtomicSync(baseCwd, sessionId, mutatorFn) {
|
|
694
|
-
const snapFilePath = getReadSnapFilePath(baseCwd, sessionId);
|
|
764
|
+
export function updateReadSnapStoreAtomicSync(baseCwd, sessionId, mutatorFn, options = {}) {
|
|
765
|
+
const snapFilePath = getReadSnapFilePath(baseCwd, sessionId, options);
|
|
695
766
|
if (!snapFilePath || typeof mutatorFn !== 'function') return null;
|
|
696
767
|
return withFileLockSync(snapFilePath, () => {
|
|
697
|
-
const { store } = loadReadSnapStore(baseCwd, sessionId);
|
|
768
|
+
const { store } = loadReadSnapStore(baseCwd, sessionId, options);
|
|
698
769
|
const updated = mutatorFn(store) || store;
|
|
699
|
-
|
|
700
|
-
return updated;
|
|
770
|
+
return writeReadSnapStoreUnlocked(snapFilePath, updated);
|
|
701
771
|
});
|
|
702
772
|
}
|
|
703
773
|
|
|
@@ -713,9 +783,13 @@ export default {
|
|
|
713
783
|
HUGE_FILE_HEAD_PROBE_BYTES,
|
|
714
784
|
MEASURED_REREAD_P_CODE,
|
|
715
785
|
MEASURED_REREAD_P_DOC,
|
|
786
|
+
DEFAULT_READ_INTERVAL_TTL_MS,
|
|
787
|
+
STRUCTURED_DATA_EXT_RE,
|
|
716
788
|
isBurnoffArtifactPath,
|
|
717
789
|
isGeneratedOrMinifiedCodePath,
|
|
718
790
|
isActiveSourceCodePath,
|
|
791
|
+
isStructuredDataPath,
|
|
792
|
+
matchesNeverClampExt,
|
|
719
793
|
computeByteBoundedSliceWindow,
|
|
720
794
|
buildCompactClampLandmarks,
|
|
721
795
|
evaluateClampExpectedValue,
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/guards/session-hook.mjs
|
|
3
|
+
* Session lifecycle handler for Claude Code `SessionStart` and `PreCompact` hooks.
|
|
4
|
+
* Invalidates stale per-session read snapshots (`read_snapshots_<sid>.json`) across compaction,
|
|
5
|
+
* resume, clear, and startup, and emits a 1-line last-session savings receipt on `SessionStart`.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { getHomeDir } from '../config/paths.mjs';
|
|
11
|
+
import { classifyLedgerBucket, LEDGER_BUCKETS, readLedgerEntries } from '../storage/ledger.mjs';
|
|
12
|
+
import { getReadSnapFilePath } from './read-clamp.mjs';
|
|
13
|
+
|
|
14
|
+
function normalizeCwdKey(cwdPath = '') {
|
|
15
|
+
const raw = String(cwdPath || '').trim();
|
|
16
|
+
if (!raw) return '';
|
|
17
|
+
return path.resolve(raw).replace(/\\/g, '/').toLowerCase();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function formatTokenCount(tokens) {
|
|
21
|
+
const n = Math.max(0, Math.round(Number(tokens) || 0));
|
|
22
|
+
if (n >= 1000) {
|
|
23
|
+
return `~${(n / 1000).toFixed(1)}k tokens`;
|
|
24
|
+
}
|
|
25
|
+
return `~${n} tokens`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Deletes the cached read-interval snapshot file for `sessionId` so post-compaction,
|
|
30
|
+
* resumed, or cleared sessions start with a fresh view of loaded file intervals.
|
|
31
|
+
*/
|
|
32
|
+
export function invalidateReadSnapshots(cwd, sessionId = 'default', options = {}) {
|
|
33
|
+
if (!cwd) return { removed: false, path: null };
|
|
34
|
+
const sid = String(sessionId || 'default').trim() || 'default';
|
|
35
|
+
const snapPath = getReadSnapFilePath(cwd, sid, options);
|
|
36
|
+
if (!snapPath) return { removed: false, path: null };
|
|
37
|
+
|
|
38
|
+
try {
|
|
39
|
+
if (fs.existsSync(snapPath)) {
|
|
40
|
+
fs.unlinkSync(snapPath);
|
|
41
|
+
return { removed: true, path: snapPath };
|
|
42
|
+
}
|
|
43
|
+
return { removed: false, path: snapPath };
|
|
44
|
+
} catch (err) {
|
|
45
|
+
if (err?.code === 'ENOENT') {
|
|
46
|
+
// ignore: snapshot file already absent
|
|
47
|
+
return { removed: false, path: snapPath };
|
|
48
|
+
}
|
|
49
|
+
void err; // ignore: fail-open snapshot invalidation
|
|
50
|
+
return { removed: false, path: snapPath };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Summarizes the most recent prior session's Burnoff guard activity from the ledger into a single
|
|
56
|
+
* concise status line for the `SessionStart` `systemMessage`, or `null` when nothing occurred.
|
|
57
|
+
*/
|
|
58
|
+
export function buildLastSessionReceipt(cwd, currentSessionId = '', options = {}) {
|
|
59
|
+
const homeDir = options.homeDir || getHomeDir(options);
|
|
60
|
+
const allEntries = readLedgerEntries({
|
|
61
|
+
...options,
|
|
62
|
+
homeDir
|
|
63
|
+
});
|
|
64
|
+
if (!Array.isArray(allEntries) || allEntries.length === 0) {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const curSid = String(currentSessionId || '').trim();
|
|
69
|
+
const normCwd = cwd ? normalizeCwdKey(cwd) : '';
|
|
70
|
+
const sessions = new Map();
|
|
71
|
+
|
|
72
|
+
for (const entry of allEntries) {
|
|
73
|
+
if (!entry || typeof entry !== 'object') continue;
|
|
74
|
+
const sid = String(entry.sessionId || '').trim();
|
|
75
|
+
if (!sid || (curSid && sid === curSid)) continue;
|
|
76
|
+
if (normCwd && entry.cwd && normalizeCwdKey(entry.cwd) !== normCwd) continue;
|
|
77
|
+
|
|
78
|
+
let agg = sessions.get(sid);
|
|
79
|
+
if (!agg) {
|
|
80
|
+
agg = {
|
|
81
|
+
sessionId: sid,
|
|
82
|
+
latestTs: 0,
|
|
83
|
+
readsBounded: 0,
|
|
84
|
+
loopsStopped: 0,
|
|
85
|
+
guardsBlocked: 0,
|
|
86
|
+
tokensNotLoaded: 0
|
|
87
|
+
};
|
|
88
|
+
sessions.set(sid, agg);
|
|
89
|
+
}
|
|
90
|
+
const ts = Number(entry.timestamp || 0);
|
|
91
|
+
if (Number.isFinite(ts) && ts > agg.latestTs) {
|
|
92
|
+
agg.latestTs = ts;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const cat = String(entry.category || '').trim().toUpperCase();
|
|
96
|
+
const detectorId = String(entry.detectorId || '').trim().toUpperCase();
|
|
97
|
+
if (cat === 'BOUNDED_READ_ENFORCED' || cat === 'READ_CLAMPED') {
|
|
98
|
+
agg.readsBounded += 1;
|
|
99
|
+
} else if (
|
|
100
|
+
cat === 'LOOP_TURN_PREVENTED' ||
|
|
101
|
+
cat === 'DET_04_LOOP_BREAKER' ||
|
|
102
|
+
(cat === 'RING0_VIOLATION_BLOCKED' && detectorId === 'DET-04')
|
|
103
|
+
) {
|
|
104
|
+
agg.loopsStopped += 1;
|
|
105
|
+
} else if (
|
|
106
|
+
cat === 'RING0_VIOLATION_BLOCKED' ||
|
|
107
|
+
cat === 'SUBAGENT_FANOUT_BLOCKED' ||
|
|
108
|
+
cat === 'SCOPE_QUOTA_BRAKE'
|
|
109
|
+
) {
|
|
110
|
+
agg.guardsBlocked += 1;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (classifyLedgerBucket(entry) === LEDGER_BUCKETS.AVOIDED_WRITE) {
|
|
114
|
+
agg.tokensNotLoaded += Math.max(0, Math.round(Number(entry.savedTokens || 0)));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const candidates = [...sessions.values()]
|
|
119
|
+
.filter(
|
|
120
|
+
(s) =>
|
|
121
|
+
s.readsBounded > 0 ||
|
|
122
|
+
s.loopsStopped > 0 ||
|
|
123
|
+
s.guardsBlocked > 0 ||
|
|
124
|
+
s.tokensNotLoaded > 0
|
|
125
|
+
)
|
|
126
|
+
.sort((a, b) => b.latestTs - a.latestTs);
|
|
127
|
+
|
|
128
|
+
if (candidates.length === 0) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const latest = candidates[0];
|
|
133
|
+
const parts = [];
|
|
134
|
+
if (latest.readsBounded > 0) {
|
|
135
|
+
parts.push(`${latest.readsBounded} read${latest.readsBounded === 1 ? '' : 's'} bounded`);
|
|
136
|
+
}
|
|
137
|
+
if (latest.loopsStopped > 0) {
|
|
138
|
+
parts.push(`${latest.loopsStopped} loop${latest.loopsStopped === 1 ? '' : 's'} stopped`);
|
|
139
|
+
}
|
|
140
|
+
if (latest.guardsBlocked > 0) {
|
|
141
|
+
parts.push(`${latest.guardsBlocked} guard${latest.guardsBlocked === 1 ? '' : 's'} blocked`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const tokPart =
|
|
145
|
+
latest.tokensNotLoaded > 0
|
|
146
|
+
? `${formatTokenCount(latest.tokensNotLoaded)} kept out of context`
|
|
147
|
+
: '';
|
|
148
|
+
|
|
149
|
+
if (parts.length > 0 && tokPart) {
|
|
150
|
+
return `Burnoff: Last session — ${parts.join(', ')} (${tokPart})`;
|
|
151
|
+
}
|
|
152
|
+
if (parts.length > 0) {
|
|
153
|
+
return `Burnoff: Last session — ${parts.join(', ')}`;
|
|
154
|
+
}
|
|
155
|
+
if (tokPart) {
|
|
156
|
+
return `Burnoff: Last session — ${tokPart}`;
|
|
157
|
+
}
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Evaluates a `SessionStart` or `PreCompact` lifecycle hook payload.
|
|
163
|
+
*/
|
|
164
|
+
export function runSessionLifecycleHook(event = {}, options = {}) {
|
|
165
|
+
const hookEventName = String(
|
|
166
|
+
event.hook_event_name || event.hookEventName || options.hookEventName || ''
|
|
167
|
+
).trim();
|
|
168
|
+
const source = String(event.source || options.source || '').trim().toLowerCase();
|
|
169
|
+
const sessionId = String(event.session_id || event.sessionId || options.sessionId || 'default');
|
|
170
|
+
const cwd = path.resolve(String(event.cwd || options.cwd || process.cwd()));
|
|
171
|
+
|
|
172
|
+
const invalidated = invalidateReadSnapshots(cwd, sessionId, options);
|
|
173
|
+
const isCompactEvent = /^PreCompact$/i.test(hookEventName) || source === 'compact';
|
|
174
|
+
|
|
175
|
+
if (isCompactEvent) {
|
|
176
|
+
return {
|
|
177
|
+
exitCode: 0,
|
|
178
|
+
stdout: '',
|
|
179
|
+
stderr: '',
|
|
180
|
+
invalidated
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const receipt = buildLastSessionReceipt(cwd, sessionId, options);
|
|
185
|
+
if (!receipt) {
|
|
186
|
+
return {
|
|
187
|
+
exitCode: 0,
|
|
188
|
+
stdout: '',
|
|
189
|
+
stderr: '',
|
|
190
|
+
invalidated
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
exitCode: 0,
|
|
196
|
+
stdout: JSON.stringify({ systemMessage: receipt }),
|
|
197
|
+
stderr: '',
|
|
198
|
+
systemMessage: receipt,
|
|
199
|
+
invalidated
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export default {
|
|
204
|
+
invalidateReadSnapshots,
|
|
205
|
+
buildLastSessionReceipt,
|
|
206
|
+
runSessionLifecycleHook
|
|
207
|
+
};
|