burnoff 1.4.0 → 1.4.1

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.
@@ -1,804 +1,826 @@
1
- /**
2
- * @file src/guards/read-clamp.mjs
3
- * Bounded `Read` Firewall (`updatedInput` clamping), 8 MB OOM Head-Probe Guard,
4
- * and Atomic Per-File Read-Interval Cache (`DET-11`/`DET-12`).
5
- */
6
-
7
- import fs from 'node:fs';
8
- import path from 'node:path';
9
- import crypto from 'node:crypto';
10
- import { resolveEffectiveRates } from '../config/loader.mjs';
11
- import { loadBurnoffPolicy } from '../config/policy.mjs';
12
- import { getWorkspaceStateDir } from '../config/paths.mjs';
13
- import { withFileLockSync } from '../storage/file-lock.mjs';
14
- import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
15
- import { recordInterventionSavings } from '../storage/ledger.mjs';
16
-
17
- export const DEFAULT_MAX_UNSLICED_LINES = 250;
18
- export const DEFAULT_MAX_UNSLICED_BYTES = 16_384;
19
- export const DEFAULT_MAX_SLICE_LINES = 400;
20
- export const DEFAULT_MAX_SLICE_BYTES = 24_576;
21
- export const CLIFF_SHIELD_MAX_UNSLICED_LINES = 150;
22
- export const CLIFF_SHIELD_MAX_UNSLICED_BYTES = 6_144;
23
- export const CLIFF_SHIELD_MAX_SLICE_LINES = 150;
24
- export const CLIFF_SHIELD_MAX_SLICE_BYTES = 8_192;
25
- export const CLAMP_TARGET_BYTES = 16_384;
26
- export const CLAMP_TARGET_LINES = 250;
27
- export const NEVER_TRIM_CODE_HARD_CEILING_BYTES = 131_072; // 128 KB
28
- export const OOM_HEAD_PROBE_BYTES = 8 * 1024 * 1024; // 8 MB OOM guard threshold
29
- export const HUGE_FILE_HEAD_PROBE_BYTES = 32_768; // 32 KB bounded head probe
30
- export const ASSUMED_INDUCED_OUTPUT_TOKENS = 600;
31
- export const ASSUMED_REMAINING_CACHE_READS = 4;
32
- export const MEASURED_REREAD_P_CODE = 0.73; // 0.27 realization factor (1 - 0.73)
33
- export const MEASURED_REREAD_P_DOC = 0.15;
34
- export const MEASURED_SOLO_TURN_P_GIVEN_REREAD = 0.19;
35
- export const ASSUMED_MIN_PROMPT_TOKENS = 20_000;
36
- export const DEFAULT_READ_INTERVAL_TTL_MS = 30 * 60 * 1000;
37
-
38
- const BURNOFF_CACHE_ARTIFACT_PATH_RE =
39
- /(?:^|\/)(?:\.claude\/cache\/artifacts|\.burnoff\/cache)(?:\/|$)/i;
40
- const GENERATED_OR_MINIFIED_CODE_RE =
41
- /(?:\.min|\.bundle|\.chunk)\.(?:m?js|cjs|css)$|(?:^|\/)(?:node_modules|dist|build|vendor|\.next|coverage)(?:\/|$)/i;
42
- const ACTIVE_SOURCE_CODE_EXT_RE =
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;
45
-
46
- export function isBurnoffArtifactPath(filePath = '') {
47
- const norm = String(filePath || '').replace(/\\/g, '/').trim();
48
- return BURNOFF_CACHE_ARTIFACT_PATH_RE.test(norm);
49
- }
50
-
51
- export function isGeneratedOrMinifiedCodePath(filePath = '') {
52
- const norm = String(filePath || '').replace(/\\/g, '/').trim();
53
- return GENERATED_OR_MINIFIED_CODE_RE.test(norm);
54
- }
55
-
56
- export function isActiveSourceCodePath(filePath = '') {
57
- const raw = String(filePath || '').trim();
58
- if (!raw || isGeneratedOrMinifiedCodePath(raw)) return false;
59
- return ACTIVE_SOURCE_CODE_EXT_RE.test(raw);
60
- }
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
-
81
- export function computeByteBoundedSliceWindow(
82
- lines = [],
83
- targetBytes = CLAMP_TARGET_BYTES,
84
- maxClampLines = CLAMP_TARGET_LINES
85
- ) {
86
- let accBytes = 0;
87
- let accLines = 0;
88
- const ceiling = Math.max(15, Math.min(maxClampLines, lines.length));
89
- for (let i = 0; i < lines.length && accLines < ceiling; i += 1) {
90
- const lineBytes = Buffer.byteLength(lines[i], 'utf8') + 1;
91
- if (accLines > 0 && accBytes + lineBytes > targetBytes) break;
92
- accBytes += lineBytes;
93
- accLines += 1;
94
- }
95
- const clampLimit = Math.max(15, Math.min(ceiling, accLines));
96
- const clampedBytes = Buffer.byteLength(lines.slice(0, clampLimit).join('\n'), 'utf8');
97
- return { clampLimit, clampedBytes };
98
- }
99
-
100
- /**
101
- * Builds lightweight structural landmarks (markdown headings and top-level symbols)
102
- * for unread ranges without requiring an external index generator.
103
- */
104
- export function buildCompactClampLandmarks(
105
- rawLines = [],
106
- clampStart = 1,
107
- clampEnd = 1,
108
- maxChars = 900
109
- ) {
110
- const landmarks = [];
111
- const headingOrSymbolRe =
112
- /^(?:#{1,4}\s+\S|(?:export\s+(?:async\s+)?(?:function|class|const|interface|type)|async\s+function|function\s+\w+|class\s+\w+|def\s+\w+|func\s+\w+|(?:pub\s+)?(?:fn|struct|enum|impl)\s+\w+))/;
113
-
114
- for (let idx = 0; idx < rawLines.length; idx += 1) {
115
- const lineNum = idx + 1;
116
- if (lineNum >= clampStart && lineNum <= clampEnd) continue;
117
- const trimmed = String(rawLines[idx] || '').trim();
118
- if (!trimmed) continue;
119
- if (headingOrSymbolRe.test(trimmed)) {
120
- landmarks.push(` L${lineNum}: ${trimmed.slice(0, 100)}`);
121
- if (landmarks.length >= 12) break;
122
- }
123
- }
124
-
125
- if (landmarks.length === 0) return '';
126
- const block = `Landmarks outside L${clampStart}..L${clampEnd}:\n${landmarks.join('\n')}`;
127
- return block.length <= maxChars ? block : `${block.slice(0, Math.max(0, maxChars - 4))}\n...`;
128
- }
129
-
130
- /**
131
- * Evaluates whether a `clamp` is expected-value net positive once induced-turn cost is weighed
132
- * against avoided cache write + future cache reads.
133
- */
134
- export function evaluateClampExpectedValue({
135
- clampSavedTokens = 0,
136
- filePath = '',
137
- nearCliff = false,
138
- promptTokens = 0,
139
- rates = {}
140
- } = {}) {
141
- const savedTok = Math.max(0, Number(clampSavedTokens) || 0);
142
- const isCode = isActiveSourceCodePath(filePath);
143
- if (nearCliff) {
144
- return {
145
- netPositive: savedTok > 200,
146
- minBreakEvenTokens: 201,
147
- evUSD: 0,
148
- pReread: 0,
149
- realizationFactor: 1,
150
- expectedSavedTokens: savedTok,
151
- isCode
152
- };
153
- }
154
- const writeRate = Number(rates.write5mPer1M || rates.inputPer1M || 3.75);
155
- const readRate = Number(rates.readPer1M ?? rates.cachedReadPer1M ?? 0.3);
156
- const outRate = Number(rates.outputPer1M || 15.0);
157
- const effPromptTok = Math.max(ASSUMED_MIN_PROMPT_TOKENS, Number(promptTokens) || 0);
158
- const effectivePer1M = writeRate + ASSUMED_REMAINING_CACHE_READS * readRate;
159
- const avoidedValueUSD = (savedTok / 1_000_000) * effectivePer1M;
160
- const inducedTurnUSD =
161
- (ASSUMED_INDUCED_OUTPUT_TOKENS / 1_000_000) * outRate +
162
- (effPromptTok / 1_000_000) * readRate;
163
- const pReread = isCode ? MEASURED_REREAD_P_CODE : MEASURED_REREAD_P_DOC;
164
- const realizationFactor = Number((1 - pReread).toFixed(2));
165
- const expectedSavedTokens = Math.round(savedTok * realizationFactor);
166
- const pInducedTurn = pReread * MEASURED_SOLO_TURN_P_GIVEN_REREAD;
167
- const evUSD = (1 - pReread) * avoidedValueUSD - pInducedTurn * inducedTurnUSD;
168
- const minBreakEvenTokens = Math.max(
169
- 200,
170
- effectivePer1M > 0
171
- ? Math.ceil(((pInducedTurn / Math.max(0.05, 1 - pReread)) * inducedTurnUSD * 1_000_000) / effectivePer1M)
172
- : 2000
173
- );
174
- return {
175
- netPositive: savedTok > minBreakEvenTokens && evUSD > 0,
176
- minBreakEvenTokens,
177
- evUSD: Number(evUSD.toFixed(6)),
178
- avoidedValueUSD: Number(avoidedValueUSD.toFixed(6)),
179
- inducedTurnUSD: Number(inducedTurnUSD.toFixed(6)),
180
- pReread,
181
- pInducedTurn: Number(pInducedTurn.toFixed(4)),
182
- realizationFactor,
183
- expectedSavedTokens,
184
- isCode
185
- };
186
- }
187
-
188
- /**
189
- * Evaluates an incoming `Read` call for bounded-read clamping (`updatedInput`) and OOM protection.
190
- */
191
- export function evaluateShieldReadGuard({
192
- sessionId = 'default',
193
- cwd = process.cwd(),
194
- homeDir,
195
- filePath = '',
196
- hasSliceBounds = false,
197
- sliceOffset = null,
198
- sliceLimit = null,
199
- currentPromptTokens = 0,
200
- modelId = 'claude-sonnet-5-5',
201
- policy: providedPolicy = null,
202
- shieldConfig = null,
203
- forceActive = false,
204
- recordLedger = true,
205
- ledgerPath
206
- } = {}) {
207
- const rawTarget = String(filePath || '').trim();
208
- const hasExplicitDimensions = sliceOffset !== null || sliceLimit !== null;
209
- if (!rawTarget || (hasSliceBounds && !hasExplicitDimensions)) {
210
- return { action: 'allow' };
211
- }
212
- if (rawTarget.endsWith('.index.md') || isBurnoffArtifactPath(rawTarget)) {
213
- return { action: 'allow' };
214
- }
215
-
216
- const baseCwd = path.resolve(cwd || process.cwd());
217
- const absFile = path.isAbsolute(rawTarget) ? path.resolve(rawTarget) : path.resolve(baseCwd, rawTarget);
218
- const relFile = path.relative(baseCwd, absFile).replace(/\\/g, '/');
219
- if (isBurnoffArtifactPath(absFile) || isBurnoffArtifactPath(relFile)) {
220
- return { action: 'allow' };
221
- }
222
-
223
- const policy = providedPolicy || loadBurnoffPolicy(baseCwd);
224
- const rc = policy.readClamp || {};
225
- const enabled = forceActive || (shieldConfig?.enabled !== undefined ? Boolean(shieldConfig.enabled) : rc.enabled !== false);
226
- const headProbeMaxBytes = Math.max(
227
- 65_536,
228
- Number(shieldConfig?.headProbeMaxBytes ?? rc.headProbeMaxBytes ?? OOM_HEAD_PROBE_BYTES)
229
- );
230
- const neverClampCodeOffCliff =
231
- shieldConfig?.neverClampCodeOffCliff !== undefined
232
- ? Boolean(shieldConfig.neverClampCodeOffCliff)
233
- : rc.neverClampCodeOffCliff !== false;
234
- const neverClampExt = Array.isArray(shieldConfig?.neverClampExt)
235
- ? shieldConfig.neverClampExt
236
- : (Array.isArray(rc.neverClampExt) ? rc.neverClampExt : []);
237
- const codeCeilingBytes = Math.max(
238
- 16_384,
239
- Number(shieldConfig?.codeNeverClampCeilingBytes ?? NEVER_TRIM_CODE_HARD_CEILING_BYTES)
240
- );
241
- const codeRealizationFactor = Math.min(
242
- 1,
243
- Math.max(0.05, Number(shieldConfig?.codeRealizationDiscount ?? rc.codeRealizationDiscount ?? (1 - MEASURED_REREAD_P_CODE)))
244
- );
245
-
246
- const cfgMaxLines = Number(shieldConfig?.maxUnslicedLines ?? shieldConfig?.maxLines ?? rc.maxLines ?? DEFAULT_MAX_UNSLICED_LINES);
247
- const cfgMaxBytes = Number(shieldConfig?.maxUnslicedBytes ?? shieldConfig?.maxBytes ?? rc.maxBytes ?? DEFAULT_MAX_UNSLICED_BYTES);
248
- const cfgSliceLines = Number(shieldConfig?.maxSliceLines ?? DEFAULT_MAX_SLICE_LINES);
249
- const cfgSliceBytes = Number(shieldConfig?.maxSliceBytes ?? DEFAULT_MAX_SLICE_BYTES);
250
-
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;
256
- const nearCliff = cliffTokens > 0 && promptTok >= Math.floor(cliffTokens * 0.9);
257
-
258
- if (!enabled && !nearCliff) {
259
- return { action: 'allow' };
260
- }
261
-
262
- if (!fs.existsSync(absFile)) {
263
- return { action: 'allow' };
264
- }
265
- let stat;
266
- try {
267
- stat = fs.statSync(absFile);
268
- } catch (err) {
269
- void err; // ignore: unreadable file stat falls back to allow
270
- return { action: 'allow' };
271
- }
272
- if (!stat.isFile() || stat.size < 1024) {
273
- return { action: 'allow' };
274
- }
275
-
276
- const isSlicedCheck = Boolean(hasSliceBounds && hasExplicitDimensions);
277
- const reqOffset = isSlicedCheck ? Math.max(1, Math.floor(Number(sliceOffset) || 1)) : 1;
278
- const reqLimitNum = Number(sliceLimit);
279
- const reqLimit =
280
- isSlicedCheck && Number.isFinite(reqLimitNum) && reqLimitNum > 0
281
- ? Math.floor(reqLimitNum)
282
- : null;
283
-
284
- const maxLines = isSlicedCheck
285
- ? nearCliff
286
- ? Number(shieldConfig?.cliffMaxSliceLines || CLIFF_SHIELD_MAX_SLICE_LINES)
287
- : cfgSliceLines
288
- : nearCliff
289
- ? Number(shieldConfig?.cliffMaxUnslicedLines || CLIFF_SHIELD_MAX_UNSLICED_LINES)
290
- : cfgMaxLines;
291
- const maxBytes = isSlicedCheck
292
- ? nearCliff
293
- ? Number(shieldConfig?.cliffMaxSliceBytes || CLIFF_SHIELD_MAX_SLICE_BYTES)
294
- : cfgSliceBytes
295
- : nearCliff
296
- ? Number(shieldConfig?.cliffMaxUnslicedBytes || CLIFF_SHIELD_MAX_UNSLICED_BYTES)
297
- : cfgMaxBytes;
298
-
299
- // 8 MB OOM head-probe fast-clamp: never calls fs.readFileSync on full file
300
- if (stat.size > headProbeMaxBytes) {
301
- const probeBuf = Buffer.allocUnsafe(HUGE_FILE_HEAD_PROBE_BYTES);
302
- let bytesRead = 0;
303
- const fd = fs.openSync(absFile, 'r');
304
- try {
305
- bytesRead = fs.readSync(fd, probeBuf, 0, HUGE_FILE_HEAD_PROBE_BYTES, 0);
306
- } finally {
307
- fs.closeSync(fd);
308
- }
309
- const usedProbe = probeBuf.subarray(0, bytesRead);
310
- if (usedProbe.includes(0x00)) {
311
- return { action: 'allow' };
312
- }
313
- const probeText = usedProbe.toString('utf8');
314
- const headLines = probeText.length === 0 ? [] : probeText.replace(/\r\n/g, '\n').split('\n');
315
- const avgBytesPerLine = Math.max(1, bytesRead / Math.max(1, headLines.length));
316
- const totalLinesEstimate = Math.max(headLines.length, Math.round(stat.size / avgBytesPerLine));
317
-
318
- if (isSlicedCheck && reqLimit !== null && reqLimit <= maxLines && reqOffset > 1) {
319
- if (reqLimit * avgBytesPerLine <= maxBytes) {
320
- return { action: 'allow' };
321
- }
322
- }
323
-
324
- const targetClampBytes = nearCliff
325
- ? (isSlicedCheck ? CLIFF_SHIELD_MAX_SLICE_BYTES : CLIFF_SHIELD_MAX_UNSLICED_BYTES)
326
- : Math.min(CLAMP_TARGET_BYTES, cfgMaxBytes);
327
- const targetClampLines = nearCliff
328
- ? (isSlicedCheck ? CLIFF_SHIELD_MAX_SLICE_LINES : CLIFF_SHIELD_MAX_UNSLICED_LINES)
329
- : Math.min(CLAMP_TARGET_LINES, cfgMaxLines);
330
- const { clampLimit, clampedBytes } = computeByteBoundedSliceWindow(
331
- headLines,
332
- targetClampBytes,
333
- targetClampLines
334
- );
335
-
336
- const displayFile =
337
- !relFile.startsWith('..') && !path.isAbsolute(relFile) ? relFile : path.basename(absFile);
338
- const clampSavedTokens = Math.max(0, Math.ceil((stat.size - clampedBytes) / 4));
339
- const isCode = isActiveSourceCodePath(absFile);
340
- const realizedFactor = isCode ? codeRealizationFactor : 1 - MEASURED_REREAD_P_DOC;
341
- const realizedClampSavedTokens = Math.max(0, Math.round(clampSavedTokens * realizedFactor));
342
- const rates = recordLedger
343
- ? (baseRates || resolveEffectiveRates(modelId, promptTok, { cwd: baseCwd, homeDir }))
344
- : null;
345
- const clampSavedUSD = rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
346
- ? Number(((realizedClampSavedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
347
- : 0;
348
- const clampEnd = reqOffset + clampLimit - 1;
349
- const hugeReason =
350
- `[Burnoff Read Clamp] Fast-clamped huge file ${displayFile} (${(stat.size / (1024 * 1024)).toFixed(1)} MB; ~${totalLinesEstimate.toLocaleString('en-US')} est. lines) ` +
351
- `to L${reqOffset}..L${clampEnd} (~${(clampedBytes / 1024).toFixed(1)} KB). Pass bounded offset & limit to inspect other ranges.`;
352
-
353
- if (recordLedger) {
354
- const dedupeHash = crypto
355
- .createHash('sha256')
356
- .update(`${absFile}:${reqOffset}:${clampLimit}:${stat.mtimeMs}`)
357
- .digest('hex')
358
- .slice(0, 16);
359
- recordInterventionSavings(
360
- {
361
- sessionId,
362
- cwd: baseCwd,
363
- category: 'BOUNDED_READ_ENFORCED',
364
- modelId,
365
- savedTokens: realizedClampSavedTokens,
366
- rawClampedTokens: clampSavedTokens,
367
- rereadDiscountApplied: Number((1 - realizedFactor).toFixed(2)),
368
- savedUSD: clampSavedUSD,
369
- dedupeId: `huge_clamp:${dedupeHash}`,
370
- detail: `Fast-clamped huge file ${displayFile} (${(stat.size / (1024 * 1024)).toFixed(1)} MB)`
371
- },
372
- { cwd: baseCwd, skipFsync: true, ...(homeDir ? { homeDir } : {}), ...(ledgerPath ? { ledgerPath } : {}) }
373
- );
374
- }
375
-
376
- return {
377
- action: 'clamp',
378
- detectorId: nearCliff ? 'DET-12' : 'DET-11',
379
- triggerReason: 'huge_file_oom_head_probe',
380
- reason: hugeReason,
381
- clampOffset: reqOffset,
382
- clampLimit,
383
- hugeFileFastClamp: true,
384
- totalLines: totalLinesEstimate,
385
- maxLines,
386
- fileBytes: stat.size,
387
- maxBytes,
388
- clampedBytes,
389
- nearCliff,
390
- savedTokens: realizedClampSavedTokens,
391
- rawClampedTokens: clampSavedTokens,
392
- savedUSD: clampSavedUSD
393
- };
394
- }
395
-
396
- let rawText;
397
- try {
398
- rawText = fs.readFileSync(absFile, 'utf8');
399
- } catch (readErr) {
400
- void readErr; // ignore: unreadable file falls back to allow
401
- return { action: 'allow' };
402
- }
403
- if (rawText.includes('\0')) {
404
- return { action: 'allow' };
405
- }
406
-
407
- const rawLines = rawText.length === 0 ? [] : rawText.replace(/\r\n/g, '\n').split('\n');
408
- const totalLines = rawLines.length;
409
- const targetSliceLines = isSlicedCheck
410
- ? rawLines.slice(reqOffset - 1, reqLimit ? reqOffset - 1 + reqLimit : rawLines.length)
411
- : rawLines;
412
- const targetLineCount = targetSliceLines.length;
413
- const targetBytes = isSlicedCheck
414
- ? Buffer.byteLength(targetSliceLines.join('\n'), 'utf8')
415
- : stat.size;
416
-
417
- const exceedsLineCap = targetLineCount > maxLines;
418
- const exceedsByteCap = targetBytes > maxBytes;
419
- if (!exceedsLineCap && !exceedsByteCap) {
420
- return { action: 'allow' };
421
- }
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
-
449
- if (
450
- neverClampCodeOffCliff &&
451
- !nearCliff &&
452
- isActiveSourceCodePath(absFile) &&
453
- targetBytes <= codeCeilingBytes
454
- ) {
455
- return {
456
- action: 'allow',
457
- codeNeverClampBypassed: true,
458
- neverTrimReason: 'active_source_code_off_cliff',
459
- fileBytes: stat.size,
460
- sliceBytes: targetBytes,
461
- ceilingBytes: codeCeilingBytes
462
- };
463
- }
464
-
465
- if (targetLineCount < 20) {
466
- return { action: 'allow', tooShortToClamp: true };
467
- }
468
-
469
- const targetClampBytes = nearCliff
470
- ? (isSlicedCheck ? CLIFF_SHIELD_MAX_SLICE_BYTES : CLIFF_SHIELD_MAX_UNSLICED_BYTES)
471
- : Math.min(CLAMP_TARGET_BYTES, cfgMaxBytes);
472
- const targetClampLines = nearCliff
473
- ? (isSlicedCheck ? CLIFF_SHIELD_MAX_SLICE_LINES : CLIFF_SHIELD_MAX_UNSLICED_LINES)
474
- : Math.min(CLAMP_TARGET_LINES, cfgMaxLines);
475
- const { clampLimit, clampedBytes } = computeByteBoundedSliceWindow(
476
- targetSliceLines,
477
- targetClampBytes,
478
- targetClampLines
479
- );
480
- if (clampLimit >= Math.floor(targetLineCount * 0.8)) {
481
- return { action: 'allow', evBypassed: true };
482
- }
483
-
484
- const clampEnd = reqOffset + clampLimit - 1;
485
- const compactLandmarks = buildCompactClampLandmarks(rawLines, reqOffset, clampEnd, 900);
486
- const clampSavedTokens = Math.max(
487
- 0,
488
- Math.ceil((targetBytes - clampedBytes - compactLandmarks.length) / 4)
489
- );
490
- const rates = resolveEffectiveRates(modelId, promptTok + clampSavedTokens, { cwd: baseCwd });
491
- const clampEv = evaluateClampExpectedValue({
492
- clampSavedTokens,
493
- filePath: absFile,
494
- nearCliff,
495
- promptTokens: promptTok,
496
- rates: rates && !rates.unknownModel ? rates : {}
497
- });
498
- if (!clampEv.netPositive) {
499
- return { action: 'allow', evBypassed: true, ev: clampEv };
500
- }
501
-
502
- const isCode = isActiveSourceCodePath(absFile);
503
- const realizedFactor = isCode ? codeRealizationFactor : 1 - MEASURED_REREAD_P_DOC;
504
- const realizedClampSavedTokens = Math.max(0, Math.round(clampSavedTokens * realizedFactor));
505
- const clampSavedUSD = rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
506
- ? Number(((realizedClampSavedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
507
- : 0;
508
-
509
- const displayFile =
510
- !relFile.startsWith('..') && !path.isAbsolute(relFile) ? relFile : path.basename(absFile);
511
- const cliffTag = nearCliff
512
- ? ` (90% of ${(cliffTokens / 1000).toFixed(0)}k pricing cliff)`
513
- : '';
514
- const triggerReason = isSlicedCheck
515
- ? (exceedsLineCap ? 'explicit_slice_line_cap' : 'explicit_slice_byte_cap')
516
- : (exceedsLineCap ? 'line_cap' : 'byte_width_cap');
517
- const capClause = exceedsLineCap
518
- ? `${targetLineCount} lines > ${maxLines}-line cap`
519
- : `${targetLineCount} lines / ${(targetBytes / 1024).toFixed(1)} KB > ${(maxBytes / 1024).toFixed(0)} KB byte-width cap`;
520
- const unreadParts = [];
521
- if (reqOffset > 1) unreadParts.push(`L1..L${reqOffset - 1}`);
522
- if (clampEnd < totalLines) unreadParts.push(`L${clampEnd + 1}..L${totalLines}`);
523
- const unreadSummary = unreadParts.length > 0 ? unreadParts.join(', ') : 'none';
524
- const landBlock = compactLandmarks ? `\n${compactLandmarks}` : '';
525
- const clampReason =
526
- `[Burnoff Read Clamp] Clamped ${isSlicedCheck ? 'wide slice' : 'unsliced Read'} of ${displayFile} (${capClause}${cliffTag}) ` +
527
- `to L${reqOffset}..L${clampEnd} of ${totalLines} lines (~${(clampedBytes / 1024).toFixed(1)} KB; unread: ${unreadSummary}). ` +
528
- `Pass offset & limit to inspect remaining sections.${landBlock}`;
529
-
530
- if (recordLedger) {
531
- const clampDedupeHash = crypto
532
- .createHash('sha256')
533
- .update(`${absFile}:${reqOffset}:${clampLimit}:${stat.mtimeMs}`)
534
- .digest('hex')
535
- .slice(0, 16);
536
- recordInterventionSavings(
537
- {
538
- sessionId,
539
- cwd: baseCwd,
540
- category: 'BOUNDED_READ_ENFORCED',
541
- modelId,
542
- savedTokens: realizedClampSavedTokens,
543
- rawClampedTokens: clampSavedTokens,
544
- rereadDiscountApplied: Number((1 - realizedFactor).toFixed(2)),
545
- savedUSD: clampSavedUSD,
546
- dedupeId: `clamp:${clampDedupeHash}`,
547
- detail: `Clamped read of ${displayFile} (${reqOffset}..${clampEnd} of ${totalLines} lines)`
548
- },
549
- { cwd: baseCwd, skipFsync: true, ...(homeDir ? { homeDir } : {}), ...(ledgerPath ? { ledgerPath } : {}) }
550
- );
551
- }
552
-
553
- return {
554
- action: 'clamp',
555
- detectorId: nearCliff ? 'DET-12' : 'DET-11',
556
- triggerReason,
557
- reason: clampReason,
558
- clampOffset: reqOffset,
559
- clampLimit,
560
- totalLines,
561
- maxLines,
562
- fileBytes: stat.size,
563
- sliceBytes: targetBytes,
564
- maxBytes,
565
- clampedBytes,
566
- nearCliff,
567
- savedTokens: realizedClampSavedTokens,
568
- rawClampedTokens: clampSavedTokens,
569
- savedUSD: clampSavedUSD,
570
- ev: clampEv
571
- };
572
- }
573
-
574
- export function getReadSnapFilePath(baseCwd, sessionId = 'default', options = {}) {
575
- if (!baseCwd) return '';
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
- }
583
- return path.join(path.resolve(String(baseCwd)), '.claude', 'cache', `read_snapshots_${safeSid}.json`);
584
- }
585
-
586
- export function loadReadSnapStore(baseCwd, sessionId = 'default', options = {}) {
587
- const snapFilePath = getReadSnapFilePath(baseCwd, sessionId, options);
588
- let store = {};
589
- if (snapFilePath && fs.existsSync(snapFilePath)) {
590
- try {
591
- const parsed = JSON.parse(fs.readFileSync(snapFilePath, 'utf8'));
592
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) store = parsed;
593
- } catch (readErr) {
594
- void readErr; // ignore: corrupt read snapshot file resets cleanly
595
- store = {};
596
- }
597
- }
598
- return { snapFilePath, store };
599
- }
600
-
601
- export function mergeLineIntervals(intervals = []) {
602
- const normalized = [];
603
- for (const pair of Array.isArray(intervals) ? intervals : []) {
604
- if (!Array.isArray(pair) || pair.length < 2) continue;
605
- const s = Math.max(1, Math.floor(Number(pair[0])));
606
- const e = Math.floor(Number(pair[1]));
607
- if (Number.isFinite(s) && Number.isFinite(e) && e >= s) {
608
- normalized.push([s, e]);
609
- }
610
- }
611
- if (normalized.length === 0) return [];
612
- normalized.sort((a, b) => (a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]));
613
- const merged = [normalized[0]];
614
- for (let i = 1; i < normalized.length; i += 1) {
615
- const cur = normalized[i];
616
- const last = merged[merged.length - 1];
617
- if (cur[0] <= last[1] + 1) {
618
- last[1] = Math.max(last[1], cur[1]);
619
- } else {
620
- merged.push([cur[0], cur[1]]);
621
- }
622
- }
623
- return merged;
624
- }
625
-
626
- /**
627
- * Checks whether `[reqStart, reqEnd]` overlaps already-in-context intervals and returns a
628
- * contiguous unread trim when partial overlap is substantial.
629
- */
630
- export function trimRequestedRangeAgainstIntervals(reqStart, reqEnd, rawIntervals = []) {
631
- const start = Math.max(1, Math.floor(Number(reqStart) || 1));
632
- const end = Math.floor(Number(reqEnd) || 0);
633
- if (end < start) return { status: 'none' };
634
- const merged = mergeLineIntervals(rawIntervals);
635
- if (merged.length === 0) return { status: 'none' };
636
-
637
- const reqLen = end - start + 1;
638
- let overlapLines = 0;
639
- const uncovered = [];
640
- let cursor = start;
641
-
642
- for (const [is, ie] of merged) {
643
- if (ie < start) continue;
644
- if (is > end) break;
645
- const ovStart = Math.max(start, is);
646
- const ovEnd = Math.min(end, ie);
647
- if (ovEnd >= ovStart) {
648
- overlapLines += ovEnd - ovStart + 1;
649
- }
650
- if (cursor < is) {
651
- uncovered.push([cursor, Math.min(end, is - 1)]);
652
- }
653
- cursor = Math.max(cursor, ie + 1);
654
- if (cursor > end) break;
655
- }
656
- if (cursor <= end) {
657
- uncovered.push([cursor, end]);
658
- }
659
-
660
- if (overlapLines === 0) return { status: 'none' };
661
- if (
662
- uncovered.length === 1 &&
663
- overlapLines >= Math.ceil(reqLen * 0.5) &&
664
- overlapLines >= 10
665
- ) {
666
- const [uStart, uEnd] = uncovered[0];
667
- return {
668
- status: 'trimmed',
669
- offset: uStart,
670
- limit: uEnd - uStart + 1,
671
- savedLines: overlapLines
672
- };
673
- }
674
- return { status: 'none' };
675
- }
676
-
677
- export function recordReadIntervalEntry(store, normKey, statObj, startLine, endLine, nowMs = Date.now()) {
678
- if (!store || !normKey || !statObj || endLine < startLine) return;
679
- if (!store.__readIntervals || typeof store.__readIntervals !== 'object') {
680
- store.__readIntervals = {};
681
- }
682
- const prev = store.__readIntervals[normKey];
683
- const sameStat =
684
- prev &&
685
- Number(prev.mtimeMs) === Number(statObj.mtimeMs) &&
686
- Number(prev.size) === Number(statObj.size);
687
- const existing = sameStat && Array.isArray(prev.intervals) ? prev.intervals : [];
688
- const recordedAt = Number.isFinite(Number(nowMs)) ? Number(nowMs) : Date.now();
689
- store.__readIntervals[normKey] = {
690
- mtimeMs: Number(statObj.mtimeMs),
691
- size: Number(statObj.size),
692
- recordedAt,
693
- intervals: mergeLineIntervals([...existing, [startLine, endLine]])
694
- };
695
- }
696
-
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;
736
- }
737
- }
738
- for (const delKey of clearIntervalKeys) {
739
- delete nextIntervals[delKey];
740
- }
741
- mergedStore.__readIntervals = nextIntervals;
742
- }
743
-
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));
759
- } catch (writeErr) {
760
- void writeErr; // ignore: non-fatal read snapshot persistence
761
- }
762
- }
763
-
764
- export function updateReadSnapStoreAtomicSync(baseCwd, sessionId, mutatorFn, options = {}) {
765
- const snapFilePath = getReadSnapFilePath(baseCwd, sessionId, options);
766
- if (!snapFilePath || typeof mutatorFn !== 'function') return null;
767
- return withFileLockSync(snapFilePath, () => {
768
- const { store } = loadReadSnapStore(baseCwd, sessionId, options);
769
- const updated = mutatorFn(store) || store;
770
- return writeReadSnapStoreUnlocked(snapFilePath, updated);
771
- });
772
- }
773
-
774
- export default {
775
- DEFAULT_MAX_UNSLICED_LINES,
776
- DEFAULT_MAX_UNSLICED_BYTES,
777
- DEFAULT_MAX_SLICE_LINES,
778
- DEFAULT_MAX_SLICE_BYTES,
779
- CLAMP_TARGET_BYTES,
780
- CLAMP_TARGET_LINES,
781
- NEVER_TRIM_CODE_HARD_CEILING_BYTES,
782
- OOM_HEAD_PROBE_BYTES,
783
- HUGE_FILE_HEAD_PROBE_BYTES,
784
- MEASURED_REREAD_P_CODE,
785
- MEASURED_REREAD_P_DOC,
786
- DEFAULT_READ_INTERVAL_TTL_MS,
787
- STRUCTURED_DATA_EXT_RE,
788
- isBurnoffArtifactPath,
789
- isGeneratedOrMinifiedCodePath,
790
- isActiveSourceCodePath,
791
- isStructuredDataPath,
792
- matchesNeverClampExt,
793
- computeByteBoundedSliceWindow,
794
- buildCompactClampLandmarks,
795
- evaluateClampExpectedValue,
796
- evaluateShieldReadGuard,
797
- getReadSnapFilePath,
798
- loadReadSnapStore,
799
- mergeLineIntervals,
800
- trimRequestedRangeAgainstIntervals,
801
- recordReadIntervalEntry,
802
- saveReadSnapStore,
803
- updateReadSnapStoreAtomicSync
804
- };
1
+ /**
2
+ * @file src/guards/read-clamp.mjs
3
+ * Bounded `Read` Firewall (`updatedInput` clamping), 8 MB OOM Head-Probe Guard,
4
+ * and Atomic Per-File Read-Interval Cache (`DET-11`/`DET-12`).
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import crypto from 'node:crypto';
10
+ import { resolveEffectiveRates } from '../config/loader.mjs';
11
+ import { loadBurnoffPolicy } from '../config/policy.mjs';
12
+ import { getWorkspaceStateDir } from '../config/paths.mjs';
13
+ import { withFileLockSync } from '../storage/file-lock.mjs';
14
+ import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
15
+ import { recordInterventionSavings } from '../storage/ledger.mjs';
16
+ import { chooseStructuralClampEndLine } from './structural-boundaries.mjs';
17
+
18
+ export const DEFAULT_MAX_UNSLICED_LINES = 250;
19
+ export const DEFAULT_MAX_UNSLICED_BYTES = 16_384;
20
+ export const DEFAULT_MAX_SLICE_LINES = 400;
21
+ export const DEFAULT_MAX_SLICE_BYTES = 24_576;
22
+ export const CLIFF_SHIELD_MAX_UNSLICED_LINES = 150;
23
+ export const CLIFF_SHIELD_MAX_UNSLICED_BYTES = 6_144;
24
+ export const CLIFF_SHIELD_MAX_SLICE_LINES = 150;
25
+ export const CLIFF_SHIELD_MAX_SLICE_BYTES = 8_192;
26
+ export const CLAMP_TARGET_BYTES = 16_384;
27
+ export const CLAMP_TARGET_LINES = 250;
28
+ export const NEVER_TRIM_CODE_HARD_CEILING_BYTES = 131_072; // 128 KB
29
+ export const OOM_HEAD_PROBE_BYTES = 8 * 1024 * 1024; // 8 MB OOM guard threshold
30
+ export const HUGE_FILE_HEAD_PROBE_BYTES = 32_768; // 32 KB bounded head probe
31
+ export const ASSUMED_INDUCED_OUTPUT_TOKENS = 600;
32
+ export const ASSUMED_REMAINING_CACHE_READS = 4;
33
+ export const MEASURED_REREAD_P_CODE = 0.73; // 0.27 realization factor (1 - 0.73)
34
+ export const MEASURED_REREAD_P_DOC = 0.15;
35
+ export const MEASURED_SOLO_TURN_P_GIVEN_REREAD = 0.19;
36
+ export const ASSUMED_MIN_PROMPT_TOKENS = 20_000;
37
+ export const DEFAULT_READ_INTERVAL_TTL_MS = 30 * 60 * 1000;
38
+
39
+ const BURNOFF_CACHE_ARTIFACT_PATH_RE =
40
+ /(?:^|\/)(?:\.claude\/cache\/artifacts|\.burnoff\/cache)(?:\/|$)/i;
41
+ const GENERATED_OR_MINIFIED_CODE_RE =
42
+ /(?:\.min|\.bundle|\.chunk)\.(?:m?js|cjs|css)$|(?:^|\/)(?:node_modules|dist|build|vendor|\.next|coverage)(?:\/|$)/i;
43
+ const ACTIVE_SOURCE_CODE_EXT_RE =
44
+ /\.(?: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;
45
+ export const STRUCTURED_DATA_EXT_RE = /\.(?:json|yaml|yml|toml|xml|csv)$/i;
46
+
47
+ export function isBurnoffArtifactPath(filePath = '') {
48
+ const norm = String(filePath || '').replace(/\\/g, '/').trim();
49
+ return BURNOFF_CACHE_ARTIFACT_PATH_RE.test(norm);
50
+ }
51
+
52
+ export function isGeneratedOrMinifiedCodePath(filePath = '') {
53
+ const norm = String(filePath || '').replace(/\\/g, '/').trim();
54
+ return GENERATED_OR_MINIFIED_CODE_RE.test(norm);
55
+ }
56
+
57
+ export function isActiveSourceCodePath(filePath = '') {
58
+ const raw = String(filePath || '').trim();
59
+ if (!raw || isGeneratedOrMinifiedCodePath(raw)) return false;
60
+ return ACTIVE_SOURCE_CODE_EXT_RE.test(raw);
61
+ }
62
+
63
+ export function isStructuredDataPath(filePath = '') {
64
+ const raw = String(filePath || '').trim();
65
+ if (!raw || isGeneratedOrMinifiedCodePath(raw)) return false;
66
+ return STRUCTURED_DATA_EXT_RE.test(raw);
67
+ }
68
+
69
+ export function matchesNeverClampExt(filePath = '', neverClampExt = []) {
70
+ if (!Array.isArray(neverClampExt) || neverClampExt.length === 0) return false;
71
+ const ext = path.extname(String(filePath || '').trim()).toLowerCase();
72
+ if (!ext) return false;
73
+ for (const item of neverClampExt) {
74
+ const norm = String(item || '').trim().toLowerCase();
75
+ if (!norm) continue;
76
+ const dotted = norm.startsWith('.') ? norm : `.${norm}`;
77
+ if (dotted === ext) return true;
78
+ }
79
+ return false;
80
+ }
81
+
82
+ export function computeByteBoundedSliceWindow(
83
+ lines = [],
84
+ targetBytes = CLAMP_TARGET_BYTES,
85
+ maxClampLines = CLAMP_TARGET_LINES
86
+ ) {
87
+ let accBytes = 0;
88
+ let accLines = 0;
89
+ const ceiling = Math.max(15, Math.min(maxClampLines, lines.length));
90
+ for (let i = 0; i < lines.length && accLines < ceiling; i += 1) {
91
+ const lineBytes = Buffer.byteLength(lines[i], 'utf8') + 1;
92
+ if (accLines > 0 && accBytes + lineBytes > targetBytes) break;
93
+ accBytes += lineBytes;
94
+ accLines += 1;
95
+ }
96
+ const clampLimit = Math.max(15, Math.min(ceiling, accLines));
97
+ const clampedBytes = Buffer.byteLength(lines.slice(0, clampLimit).join('\n'), 'utf8');
98
+ return { clampLimit, clampedBytes };
99
+ }
100
+
101
+ /**
102
+ * Builds lightweight structural landmarks (markdown headings and top-level symbols)
103
+ * for unread ranges without requiring an external index generator.
104
+ */
105
+ export function buildCompactClampLandmarks(
106
+ rawLines = [],
107
+ clampStart = 1,
108
+ clampEnd = 1,
109
+ maxChars = 900
110
+ ) {
111
+ const landmarks = [];
112
+ const headingOrSymbolRe =
113
+ /^(?:#{1,4}\s+\S|(?:export\s+(?:async\s+)?(?:function|class|const|interface|type)|async\s+function|function\s+\w+|class\s+\w+|def\s+\w+|func\s+\w+|(?:pub\s+)?(?:fn|struct|enum|impl)\s+\w+))/;
114
+
115
+ for (let idx = 0; idx < rawLines.length; idx += 1) {
116
+ const lineNum = idx + 1;
117
+ if (lineNum >= clampStart && lineNum <= clampEnd) continue;
118
+ const trimmed = String(rawLines[idx] || '').trim();
119
+ if (!trimmed) continue;
120
+ if (headingOrSymbolRe.test(trimmed)) {
121
+ landmarks.push(` L${lineNum}: ${trimmed.slice(0, 100)}`);
122
+ if (landmarks.length >= 12) break;
123
+ }
124
+ }
125
+
126
+ if (landmarks.length === 0) return '';
127
+ const block = `Landmarks outside L${clampStart}..L${clampEnd}:\n${landmarks.join('\n')}`;
128
+ return block.length <= maxChars ? block : `${block.slice(0, Math.max(0, maxChars - 4))}\n...`;
129
+ }
130
+
131
+ /**
132
+ * Evaluates whether a `clamp` is expected-value net positive once induced-turn cost is weighed
133
+ * against avoided cache write + future cache reads.
134
+ */
135
+ export function evaluateClampExpectedValue({
136
+ clampSavedTokens = 0,
137
+ filePath = '',
138
+ nearCliff = false,
139
+ promptTokens = 0,
140
+ rates = {}
141
+ } = {}) {
142
+ const savedTok = Math.max(0, Number(clampSavedTokens) || 0);
143
+ const isCode = isActiveSourceCodePath(filePath);
144
+ if (nearCliff) {
145
+ return {
146
+ netPositive: savedTok > 200,
147
+ minBreakEvenTokens: 201,
148
+ evUSD: 0,
149
+ pReread: 0,
150
+ realizationFactor: 1,
151
+ expectedSavedTokens: savedTok,
152
+ isCode
153
+ };
154
+ }
155
+ const writeRate = Number(rates.write5mPer1M || rates.inputPer1M || 3.75);
156
+ const readRate = Number(rates.readPer1M ?? rates.cachedReadPer1M ?? 0.3);
157
+ const outRate = Number(rates.outputPer1M || 15.0);
158
+ const effPromptTok = Math.max(ASSUMED_MIN_PROMPT_TOKENS, Number(promptTokens) || 0);
159
+ const effectivePer1M = writeRate + ASSUMED_REMAINING_CACHE_READS * readRate;
160
+ const avoidedValueUSD = (savedTok / 1_000_000) * effectivePer1M;
161
+ const inducedTurnUSD =
162
+ (ASSUMED_INDUCED_OUTPUT_TOKENS / 1_000_000) * outRate +
163
+ (effPromptTok / 1_000_000) * readRate;
164
+ const pReread = isCode ? MEASURED_REREAD_P_CODE : MEASURED_REREAD_P_DOC;
165
+ const realizationFactor = Number((1 - pReread).toFixed(2));
166
+ const expectedSavedTokens = Math.round(savedTok * realizationFactor);
167
+ const pInducedTurn = pReread * MEASURED_SOLO_TURN_P_GIVEN_REREAD;
168
+ const evUSD = (1 - pReread) * avoidedValueUSD - pInducedTurn * inducedTurnUSD;
169
+ const minBreakEvenTokens = Math.max(
170
+ 200,
171
+ effectivePer1M > 0
172
+ ? Math.ceil(((pInducedTurn / Math.max(0.05, 1 - pReread)) * inducedTurnUSD * 1_000_000) / effectivePer1M)
173
+ : 2000
174
+ );
175
+ return {
176
+ netPositive: savedTok > minBreakEvenTokens && evUSD > 0,
177
+ minBreakEvenTokens,
178
+ evUSD: Number(evUSD.toFixed(6)),
179
+ avoidedValueUSD: Number(avoidedValueUSD.toFixed(6)),
180
+ inducedTurnUSD: Number(inducedTurnUSD.toFixed(6)),
181
+ pReread,
182
+ pInducedTurn: Number(pInducedTurn.toFixed(4)),
183
+ realizationFactor,
184
+ expectedSavedTokens,
185
+ isCode
186
+ };
187
+ }
188
+
189
+ /**
190
+ * Evaluates an incoming `Read` call for bounded-read clamping (`updatedInput`) and OOM protection.
191
+ */
192
+ export function evaluateShieldReadGuard({
193
+ sessionId = 'default',
194
+ cwd = process.cwd(),
195
+ homeDir,
196
+ filePath = '',
197
+ hasSliceBounds = false,
198
+ sliceOffset = null,
199
+ sliceLimit = null,
200
+ currentPromptTokens = 0,
201
+ modelId = 'claude-sonnet-5-5',
202
+ policy: providedPolicy = null,
203
+ shieldConfig = null,
204
+ forceActive = false,
205
+ recordLedger = true,
206
+ ledgerPath
207
+ } = {}) {
208
+ const rawTarget = String(filePath || '').trim();
209
+ const hasExplicitDimensions = sliceOffset !== null || sliceLimit !== null;
210
+ if (!rawTarget || (hasSliceBounds && !hasExplicitDimensions)) {
211
+ return { action: 'allow' };
212
+ }
213
+ if (rawTarget.endsWith('.index.md') || isBurnoffArtifactPath(rawTarget)) {
214
+ return { action: 'allow' };
215
+ }
216
+
217
+ const baseCwd = path.resolve(cwd || process.cwd());
218
+ const absFile = path.isAbsolute(rawTarget) ? path.resolve(rawTarget) : path.resolve(baseCwd, rawTarget);
219
+ const relFile = path.relative(baseCwd, absFile).replace(/\\/g, '/');
220
+ if (isBurnoffArtifactPath(absFile) || isBurnoffArtifactPath(relFile)) {
221
+ return { action: 'allow' };
222
+ }
223
+
224
+ const policy = providedPolicy || loadBurnoffPolicy(baseCwd);
225
+ const rc = policy.readClamp || {};
226
+ const enabled = forceActive || (shieldConfig?.enabled !== undefined ? Boolean(shieldConfig.enabled) : rc.enabled !== false);
227
+ const headProbeMaxBytes = Math.max(
228
+ 65_536,
229
+ Number(shieldConfig?.headProbeMaxBytes ?? rc.headProbeMaxBytes ?? OOM_HEAD_PROBE_BYTES)
230
+ );
231
+ const neverClampCodeOffCliff =
232
+ shieldConfig?.neverClampCodeOffCliff !== undefined
233
+ ? Boolean(shieldConfig.neverClampCodeOffCliff)
234
+ : rc.neverClampCodeOffCliff !== false;
235
+ const neverClampExt = Array.isArray(shieldConfig?.neverClampExt)
236
+ ? shieldConfig.neverClampExt
237
+ : (Array.isArray(rc.neverClampExt) ? rc.neverClampExt : []);
238
+ const codeCeilingBytes = Math.max(
239
+ 16_384,
240
+ Number(shieldConfig?.codeNeverClampCeilingBytes ?? NEVER_TRIM_CODE_HARD_CEILING_BYTES)
241
+ );
242
+ const codeRealizationFactor = Math.min(
243
+ 1,
244
+ Math.max(0.05, Number(shieldConfig?.codeRealizationDiscount ?? rc.codeRealizationDiscount ?? (1 - MEASURED_REREAD_P_CODE)))
245
+ );
246
+
247
+ const cfgMaxLines = Number(shieldConfig?.maxUnslicedLines ?? shieldConfig?.maxLines ?? rc.maxLines ?? DEFAULT_MAX_UNSLICED_LINES);
248
+ const cfgMaxBytes = Number(shieldConfig?.maxUnslicedBytes ?? shieldConfig?.maxBytes ?? rc.maxBytes ?? DEFAULT_MAX_UNSLICED_BYTES);
249
+ const cfgSliceLines = Number(shieldConfig?.maxSliceLines ?? DEFAULT_MAX_SLICE_LINES);
250
+ const cfgSliceBytes = Number(shieldConfig?.maxSliceBytes ?? DEFAULT_MAX_SLICE_BYTES);
251
+
252
+ const promptTok = Math.max(0, Number(currentPromptTokens) || 0);
253
+ const baseRates = promptTok > 0
254
+ ? resolveEffectiveRates(modelId, promptTok, { cwd: baseCwd, homeDir })
255
+ : null;
256
+ const cliffTokens = baseRates?.cliffThresholdTokens ? Number(baseRates.cliffThresholdTokens) : 0;
257
+ const nearCliff = cliffTokens > 0 && promptTok >= Math.floor(cliffTokens * 0.9);
258
+
259
+ if (!enabled && !nearCliff) {
260
+ return { action: 'allow' };
261
+ }
262
+
263
+ if (!fs.existsSync(absFile)) {
264
+ return { action: 'allow' };
265
+ }
266
+ let stat;
267
+ try {
268
+ stat = fs.statSync(absFile);
269
+ } catch (err) {
270
+ void err; // ignore: unreadable file stat falls back to allow
271
+ return { action: 'allow' };
272
+ }
273
+ if (!stat.isFile() || stat.size < 1024) {
274
+ return { action: 'allow' };
275
+ }
276
+
277
+ const isSlicedCheck = Boolean(hasSliceBounds && hasExplicitDimensions);
278
+ const reqOffset = isSlicedCheck ? Math.max(1, Math.floor(Number(sliceOffset) || 1)) : 1;
279
+ const reqLimitNum = Number(sliceLimit);
280
+ const reqLimit =
281
+ isSlicedCheck && Number.isFinite(reqLimitNum) && reqLimitNum > 0
282
+ ? Math.floor(reqLimitNum)
283
+ : null;
284
+
285
+ const maxLines = isSlicedCheck
286
+ ? nearCliff
287
+ ? Number(shieldConfig?.cliffMaxSliceLines || CLIFF_SHIELD_MAX_SLICE_LINES)
288
+ : cfgSliceLines
289
+ : nearCliff
290
+ ? Number(shieldConfig?.cliffMaxUnslicedLines || CLIFF_SHIELD_MAX_UNSLICED_LINES)
291
+ : cfgMaxLines;
292
+ const maxBytes = isSlicedCheck
293
+ ? nearCliff
294
+ ? Number(shieldConfig?.cliffMaxSliceBytes || CLIFF_SHIELD_MAX_SLICE_BYTES)
295
+ : cfgSliceBytes
296
+ : nearCliff
297
+ ? Number(shieldConfig?.cliffMaxUnslicedBytes || CLIFF_SHIELD_MAX_UNSLICED_BYTES)
298
+ : cfgMaxBytes;
299
+
300
+ // 8 MB OOM head-probe fast-clamp: never calls fs.readFileSync on full file
301
+ if (stat.size > headProbeMaxBytes) {
302
+ const probeBuf = Buffer.allocUnsafe(HUGE_FILE_HEAD_PROBE_BYTES);
303
+ let bytesRead = 0;
304
+ const fd = fs.openSync(absFile, 'r');
305
+ try {
306
+ bytesRead = fs.readSync(fd, probeBuf, 0, HUGE_FILE_HEAD_PROBE_BYTES, 0);
307
+ } finally {
308
+ fs.closeSync(fd);
309
+ }
310
+ const usedProbe = probeBuf.subarray(0, bytesRead);
311
+ if (usedProbe.includes(0x00)) {
312
+ return { action: 'allow' };
313
+ }
314
+ const probeText = usedProbe.toString('utf8');
315
+ const headLines = probeText.length === 0 ? [] : probeText.replace(/\r\n/g, '\n').split('\n');
316
+ const avgBytesPerLine = Math.max(1, bytesRead / Math.max(1, headLines.length));
317
+ const totalLinesEstimate = Math.max(headLines.length, Math.round(stat.size / avgBytesPerLine));
318
+
319
+ if (isSlicedCheck && reqLimit !== null && reqLimit <= maxLines && reqOffset > 1) {
320
+ if (reqLimit * avgBytesPerLine <= maxBytes) {
321
+ return { action: 'allow' };
322
+ }
323
+ }
324
+
325
+ const targetClampBytes = nearCliff
326
+ ? (isSlicedCheck ? CLIFF_SHIELD_MAX_SLICE_BYTES : CLIFF_SHIELD_MAX_UNSLICED_BYTES)
327
+ : Math.min(CLAMP_TARGET_BYTES, cfgMaxBytes);
328
+ const targetClampLines = nearCliff
329
+ ? (isSlicedCheck ? CLIFF_SHIELD_MAX_SLICE_LINES : CLIFF_SHIELD_MAX_UNSLICED_LINES)
330
+ : Math.min(CLAMP_TARGET_LINES, cfgMaxLines);
331
+ const { clampLimit, clampedBytes } = computeByteBoundedSliceWindow(
332
+ headLines,
333
+ targetClampBytes,
334
+ targetClampLines
335
+ );
336
+
337
+ const displayFile =
338
+ !relFile.startsWith('..') && !path.isAbsolute(relFile) ? relFile : path.basename(absFile);
339
+ const clampSavedTokens = Math.max(0, Math.ceil((stat.size - clampedBytes) / 4));
340
+ const isCode = isActiveSourceCodePath(absFile);
341
+ const realizedFactor = isCode ? codeRealizationFactor : 1 - MEASURED_REREAD_P_DOC;
342
+ const realizedClampSavedTokens = Math.max(0, Math.round(clampSavedTokens * realizedFactor));
343
+ const rates = recordLedger
344
+ ? (baseRates || resolveEffectiveRates(modelId, promptTok, { cwd: baseCwd, homeDir }))
345
+ : null;
346
+ const clampSavedUSD = rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
347
+ ? Number(((realizedClampSavedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
348
+ : 0;
349
+ const clampEnd = reqOffset + clampLimit - 1;
350
+ const hugeReason =
351
+ `[Burnoff Read Clamp] Fast-clamped huge file ${displayFile} (${(stat.size / (1024 * 1024)).toFixed(1)} MB; ~${totalLinesEstimate.toLocaleString('en-US')} est. lines) ` +
352
+ `to L${reqOffset}..L${clampEnd} (~${(clampedBytes / 1024).toFixed(1)} KB). Pass bounded offset & limit to inspect other ranges.`;
353
+
354
+ if (recordLedger) {
355
+ const dedupeHash = crypto
356
+ .createHash('sha256')
357
+ .update(`${absFile}:${reqOffset}:${clampLimit}:${stat.mtimeMs}`)
358
+ .digest('hex')
359
+ .slice(0, 16);
360
+ recordInterventionSavings(
361
+ {
362
+ sessionId,
363
+ cwd: baseCwd,
364
+ category: 'BOUNDED_READ_ENFORCED',
365
+ modelId,
366
+ savedTokens: realizedClampSavedTokens,
367
+ rawClampedTokens: clampSavedTokens,
368
+ rereadDiscountApplied: Number((1 - realizedFactor).toFixed(2)),
369
+ savedUSD: clampSavedUSD,
370
+ dedupeId: `huge_clamp:${dedupeHash}`,
371
+ detail: `Fast-clamped huge file ${displayFile} (${(stat.size / (1024 * 1024)).toFixed(1)} MB)`
372
+ },
373
+ { cwd: baseCwd, skipFsync: true, ...(homeDir ? { homeDir } : {}), ...(ledgerPath ? { ledgerPath } : {}) }
374
+ );
375
+ }
376
+
377
+ return {
378
+ action: 'clamp',
379
+ detectorId: nearCliff ? 'DET-12' : 'DET-11',
380
+ triggerReason: 'huge_file_oom_head_probe',
381
+ reason: hugeReason,
382
+ clampOffset: reqOffset,
383
+ clampLimit,
384
+ hugeFileFastClamp: true,
385
+ totalLines: totalLinesEstimate,
386
+ maxLines,
387
+ fileBytes: stat.size,
388
+ maxBytes,
389
+ clampedBytes,
390
+ nearCliff,
391
+ savedTokens: realizedClampSavedTokens,
392
+ rawClampedTokens: clampSavedTokens,
393
+ savedUSD: clampSavedUSD
394
+ };
395
+ }
396
+
397
+ let rawText;
398
+ try {
399
+ rawText = fs.readFileSync(absFile, 'utf8');
400
+ } catch (readErr) {
401
+ void readErr; // ignore: unreadable file falls back to allow
402
+ return { action: 'allow' };
403
+ }
404
+ if (rawText.includes('\0')) {
405
+ return { action: 'allow' };
406
+ }
407
+
408
+ const rawLines = rawText.length === 0 ? [] : rawText.replace(/\r\n/g, '\n').split('\n');
409
+ const totalLines = rawLines.length;
410
+ const targetSliceLines = isSlicedCheck
411
+ ? rawLines.slice(reqOffset - 1, reqLimit ? reqOffset - 1 + reqLimit : rawLines.length)
412
+ : rawLines;
413
+ const targetLineCount = targetSliceLines.length;
414
+ const targetBytes = isSlicedCheck
415
+ ? Buffer.byteLength(targetSliceLines.join('\n'), 'utf8')
416
+ : stat.size;
417
+
418
+ const exceedsLineCap = targetLineCount > maxLines;
419
+ const exceedsByteCap = targetBytes > maxBytes;
420
+ if (!exceedsLineCap && !exceedsByteCap) {
421
+ return { action: 'allow' };
422
+ }
423
+
424
+ if (!nearCliff && matchesNeverClampExt(absFile, neverClampExt)) {
425
+ return {
426
+ action: 'allow',
427
+ neverClampExtBypassed: true,
428
+ neverTrimReason: 'policy_never_clamp_ext',
429
+ fileBytes: stat.size,
430
+ sliceBytes: targetBytes
431
+ };
432
+ }
433
+
434
+ if (
435
+ !nearCliff &&
436
+ isStructuredDataPath(absFile) &&
437
+ stat.size < NEVER_TRIM_CODE_HARD_CEILING_BYTES &&
438
+ targetBytes < NEVER_TRIM_CODE_HARD_CEILING_BYTES
439
+ ) {
440
+ return {
441
+ action: 'allow',
442
+ structuredDataNeverClampBypassed: true,
443
+ neverTrimReason: 'structured_data_under_128kb',
444
+ fileBytes: stat.size,
445
+ sliceBytes: targetBytes,
446
+ ceilingBytes: NEVER_TRIM_CODE_HARD_CEILING_BYTES
447
+ };
448
+ }
449
+
450
+ if (
451
+ neverClampCodeOffCliff &&
452
+ !nearCliff &&
453
+ isActiveSourceCodePath(absFile) &&
454
+ targetBytes <= codeCeilingBytes
455
+ ) {
456
+ return {
457
+ action: 'allow',
458
+ codeNeverClampBypassed: true,
459
+ neverTrimReason: 'active_source_code_off_cliff',
460
+ fileBytes: stat.size,
461
+ sliceBytes: targetBytes,
462
+ ceilingBytes: codeCeilingBytes
463
+ };
464
+ }
465
+
466
+ if (targetLineCount < 20) {
467
+ return { action: 'allow', tooShortToClamp: true };
468
+ }
469
+
470
+ const targetClampBytes = nearCliff
471
+ ? (isSlicedCheck ? CLIFF_SHIELD_MAX_SLICE_BYTES : CLIFF_SHIELD_MAX_UNSLICED_BYTES)
472
+ : Math.min(CLAMP_TARGET_BYTES, cfgMaxBytes);
473
+ const targetClampLines = nearCliff
474
+ ? (isSlicedCheck ? CLIFF_SHIELD_MAX_SLICE_LINES : CLIFF_SHIELD_MAX_UNSLICED_LINES)
475
+ : Math.min(CLAMP_TARGET_LINES, cfgMaxLines);
476
+ let { clampLimit, clampedBytes } = computeByteBoundedSliceWindow(
477
+ targetSliceLines,
478
+ targetClampBytes,
479
+ targetClampLines
480
+ );
481
+ let structuralBoundarySnapped = false;
482
+ let structuralFallback = false;
483
+ if (
484
+ stat.size >= NEVER_TRIM_CODE_HARD_CEILING_BYTES ||
485
+ isStructuredDataPath(absFile) ||
486
+ /\.(?:md|mdx|markdown|txt|log)$/i.test(absFile)
487
+ ) {
488
+ const structChoice = chooseStructuralClampEndLine(targetSliceLines, {
489
+ filePath: absFile,
490
+ maxLimit: clampLimit,
491
+ minLimit: 15
492
+ });
493
+ structuralBoundarySnapped = Boolean(structChoice.snapped);
494
+ structuralFallback = Boolean(structChoice.usedFallback);
495
+ if (structChoice.endLine >= 15 && structChoice.endLine < clampLimit) {
496
+ clampLimit = structChoice.endLine;
497
+ clampedBytes = Buffer.byteLength(targetSliceLines.slice(0, clampLimit).join('\n'), 'utf8');
498
+ }
499
+ }
500
+ if (clampLimit >= Math.floor(targetLineCount * 0.8)) {
501
+ return { action: 'allow', evBypassed: true };
502
+ }
503
+
504
+ const clampEnd = reqOffset + clampLimit - 1;
505
+ const compactLandmarks = buildCompactClampLandmarks(rawLines, reqOffset, clampEnd, 900);
506
+ const clampSavedTokens = Math.max(
507
+ 0,
508
+ Math.ceil((targetBytes - clampedBytes - compactLandmarks.length) / 4)
509
+ );
510
+ const rates = resolveEffectiveRates(modelId, promptTok + clampSavedTokens, { cwd: baseCwd });
511
+ const clampEv = evaluateClampExpectedValue({
512
+ clampSavedTokens,
513
+ filePath: absFile,
514
+ nearCliff,
515
+ promptTokens: promptTok,
516
+ rates: rates && !rates.unknownModel ? rates : {}
517
+ });
518
+ if (!clampEv.netPositive) {
519
+ return { action: 'allow', evBypassed: true, ev: clampEv };
520
+ }
521
+
522
+ const isCode = isActiveSourceCodePath(absFile);
523
+ const realizedFactor = isCode ? codeRealizationFactor : 1 - MEASURED_REREAD_P_DOC;
524
+ const realizedClampSavedTokens = Math.max(0, Math.round(clampSavedTokens * realizedFactor));
525
+ const clampSavedUSD = rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
526
+ ? Number(((realizedClampSavedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
527
+ : 0;
528
+
529
+ const displayFile =
530
+ !relFile.startsWith('..') && !path.isAbsolute(relFile) ? relFile : path.basename(absFile);
531
+ const cliffTag = nearCliff
532
+ ? ` (90% of ${(cliffTokens / 1000).toFixed(0)}k pricing cliff)`
533
+ : '';
534
+ const triggerReason = isSlicedCheck
535
+ ? (exceedsLineCap ? 'explicit_slice_line_cap' : 'explicit_slice_byte_cap')
536
+ : (exceedsLineCap ? 'line_cap' : 'byte_width_cap');
537
+ const capClause = exceedsLineCap
538
+ ? `${targetLineCount} lines > ${maxLines}-line cap`
539
+ : `${targetLineCount} lines / ${(targetBytes / 1024).toFixed(1)} KB > ${(maxBytes / 1024).toFixed(0)} KB byte-width cap`;
540
+ const unreadParts = [];
541
+ if (reqOffset > 1) unreadParts.push(`L1..L${reqOffset - 1}`);
542
+ if (clampEnd < totalLines) unreadParts.push(`L${clampEnd + 1}..L${totalLines}`);
543
+ const unreadSummary = unreadParts.length > 0 ? unreadParts.join(', ') : 'none';
544
+ const landBlock = compactLandmarks ? `\n${compactLandmarks}` : '';
545
+ const clampReason =
546
+ `[Burnoff Read Clamp] Clamped ${isSlicedCheck ? 'wide slice' : 'unsliced Read'} of ${displayFile} (${capClause}${cliffTag}) ` +
547
+ `to L${reqOffset}..L${clampEnd} of ${totalLines} lines (~${(clampedBytes / 1024).toFixed(1)} KB; unread: ${unreadSummary}). ` +
548
+ `Pass offset & limit to inspect remaining sections.${landBlock}`;
549
+
550
+ if (recordLedger) {
551
+ const clampDedupeHash = crypto
552
+ .createHash('sha256')
553
+ .update(`${absFile}:${reqOffset}:${clampLimit}:${stat.mtimeMs}`)
554
+ .digest('hex')
555
+ .slice(0, 16);
556
+ recordInterventionSavings(
557
+ {
558
+ sessionId,
559
+ cwd: baseCwd,
560
+ category: 'BOUNDED_READ_ENFORCED',
561
+ modelId,
562
+ savedTokens: realizedClampSavedTokens,
563
+ rawClampedTokens: clampSavedTokens,
564
+ rereadDiscountApplied: Number((1 - realizedFactor).toFixed(2)),
565
+ savedUSD: clampSavedUSD,
566
+ dedupeId: `clamp:${clampDedupeHash}`,
567
+ detail: `Clamped read of ${displayFile} (${reqOffset}..${clampEnd} of ${totalLines} lines)`
568
+ },
569
+ { cwd: baseCwd, skipFsync: true, ...(homeDir ? { homeDir } : {}), ...(ledgerPath ? { ledgerPath } : {}) }
570
+ );
571
+ }
572
+
573
+ return {
574
+ action: 'clamp',
575
+ detectorId: nearCliff ? 'DET-12' : 'DET-11',
576
+ triggerReason,
577
+ reason: clampReason,
578
+ clampOffset: reqOffset,
579
+ clampLimit,
580
+ totalLines,
581
+ maxLines,
582
+ fileBytes: stat.size,
583
+ sliceBytes: targetBytes,
584
+ maxBytes,
585
+ clampedBytes,
586
+ nearCliff,
587
+ structuralBoundarySnapped,
588
+ structuralFallback,
589
+ savedTokens: realizedClampSavedTokens,
590
+ rawClampedTokens: clampSavedTokens,
591
+ savedUSD: clampSavedUSD,
592
+ ev: clampEv
593
+ };
594
+ }
595
+
596
+ export function getReadSnapFilePath(baseCwd, sessionId = 'default', options = {}) {
597
+ if (!baseCwd) return '';
598
+ const safeSid =
599
+ typeof sessionId === 'string' && sessionId.trim()
600
+ ? sessionId.trim().replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 64) || 'default'
601
+ : 'default';
602
+ if (options?.client === 'antigravity') {
603
+ return path.join(getWorkspaceStateDir(baseCwd, options.homeDir), `read_snapshots_${safeSid}.json`);
604
+ }
605
+ return path.join(path.resolve(String(baseCwd)), '.claude', 'cache', `read_snapshots_${safeSid}.json`);
606
+ }
607
+
608
+ export function loadReadSnapStore(baseCwd, sessionId = 'default', options = {}) {
609
+ const snapFilePath = getReadSnapFilePath(baseCwd, sessionId, options);
610
+ let store = {};
611
+ if (snapFilePath && fs.existsSync(snapFilePath)) {
612
+ try {
613
+ const parsed = JSON.parse(fs.readFileSync(snapFilePath, 'utf8'));
614
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) store = parsed;
615
+ } catch (readErr) {
616
+ void readErr; // ignore: corrupt read snapshot file resets cleanly
617
+ store = {};
618
+ }
619
+ }
620
+ return { snapFilePath, store };
621
+ }
622
+
623
+ export function mergeLineIntervals(intervals = []) {
624
+ const normalized = [];
625
+ for (const pair of Array.isArray(intervals) ? intervals : []) {
626
+ if (!Array.isArray(pair) || pair.length < 2) continue;
627
+ const s = Math.max(1, Math.floor(Number(pair[0])));
628
+ const e = Math.floor(Number(pair[1]));
629
+ if (Number.isFinite(s) && Number.isFinite(e) && e >= s) {
630
+ normalized.push([s, e]);
631
+ }
632
+ }
633
+ if (normalized.length === 0) return [];
634
+ normalized.sort((a, b) => (a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]));
635
+ const merged = [normalized[0]];
636
+ for (let i = 1; i < normalized.length; i += 1) {
637
+ const cur = normalized[i];
638
+ const last = merged[merged.length - 1];
639
+ if (cur[0] <= last[1] + 1) {
640
+ last[1] = Math.max(last[1], cur[1]);
641
+ } else {
642
+ merged.push([cur[0], cur[1]]);
643
+ }
644
+ }
645
+ return merged;
646
+ }
647
+
648
+ /**
649
+ * Checks whether `[reqStart, reqEnd]` overlaps already-in-context intervals and returns a
650
+ * contiguous unread trim when partial overlap is substantial.
651
+ */
652
+ export function trimRequestedRangeAgainstIntervals(reqStart, reqEnd, rawIntervals = []) {
653
+ const start = Math.max(1, Math.floor(Number(reqStart) || 1));
654
+ const end = Math.floor(Number(reqEnd) || 0);
655
+ if (end < start) return { status: 'none' };
656
+ const merged = mergeLineIntervals(rawIntervals);
657
+ if (merged.length === 0) return { status: 'none' };
658
+
659
+ const reqLen = end - start + 1;
660
+ let overlapLines = 0;
661
+ const uncovered = [];
662
+ let cursor = start;
663
+
664
+ for (const [is, ie] of merged) {
665
+ if (ie < start) continue;
666
+ if (is > end) break;
667
+ const ovStart = Math.max(start, is);
668
+ const ovEnd = Math.min(end, ie);
669
+ if (ovEnd >= ovStart) {
670
+ overlapLines += ovEnd - ovStart + 1;
671
+ }
672
+ if (cursor < is) {
673
+ uncovered.push([cursor, Math.min(end, is - 1)]);
674
+ }
675
+ cursor = Math.max(cursor, ie + 1);
676
+ if (cursor > end) break;
677
+ }
678
+ if (cursor <= end) {
679
+ uncovered.push([cursor, end]);
680
+ }
681
+
682
+ if (overlapLines === 0) return { status: 'none' };
683
+ if (
684
+ uncovered.length === 1 &&
685
+ overlapLines >= Math.ceil(reqLen * 0.5) &&
686
+ overlapLines >= 10
687
+ ) {
688
+ const [uStart, uEnd] = uncovered[0];
689
+ return {
690
+ status: 'trimmed',
691
+ offset: uStart,
692
+ limit: uEnd - uStart + 1,
693
+ savedLines: overlapLines
694
+ };
695
+ }
696
+ return { status: 'none' };
697
+ }
698
+
699
+ export function recordReadIntervalEntry(store, normKey, statObj, startLine, endLine, nowMs = Date.now()) {
700
+ if (!store || !normKey || !statObj || endLine < startLine) return;
701
+ if (!store.__readIntervals || typeof store.__readIntervals !== 'object') {
702
+ store.__readIntervals = {};
703
+ }
704
+ const prev = store.__readIntervals[normKey];
705
+ const sameStat =
706
+ prev &&
707
+ Number(prev.mtimeMs) === Number(statObj.mtimeMs) &&
708
+ Number(prev.size) === Number(statObj.size);
709
+ const existing = sameStat && Array.isArray(prev.intervals) ? prev.intervals : [];
710
+ const recordedAt = Number.isFinite(Number(nowMs)) ? Number(nowMs) : Date.now();
711
+ store.__readIntervals[normKey] = {
712
+ mtimeMs: Number(statObj.mtimeMs),
713
+ size: Number(statObj.size),
714
+ recordedAt,
715
+ intervals: mergeLineIntervals([...existing, [startLine, endLine]])
716
+ };
717
+ }
718
+
719
+ function writeReadSnapStoreUnlocked(
720
+ snapFilePath,
721
+ store,
722
+ { clearIntervalKeys = [], clearAllIntervals = false } = {}
723
+ ) {
724
+ let diskStore = {};
725
+ if (fs.existsSync(snapFilePath)) {
726
+ try {
727
+ const parsed = JSON.parse(fs.readFileSync(snapFilePath, 'utf8'));
728
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) diskStore = parsed;
729
+ } catch (err) {
730
+ void err; // ignore: corrupt snapshot overwritten cleanly
731
+ }
732
+ }
733
+ const mergedStore = { ...diskStore, ...store };
734
+ if (clearAllIntervals) {
735
+ mergedStore.__readIntervals = {};
736
+ } else if (diskStore.__readIntervals || store.__readIntervals) {
737
+ const nextIntervals = { ...(diskStore.__readIntervals || {}) };
738
+ for (const [k, v] of Object.entries(store.__readIntervals || {})) {
739
+ const prev = nextIntervals[k];
740
+ if (
741
+ prev &&
742
+ v &&
743
+ Number(prev.mtimeMs) === Number(v.mtimeMs) &&
744
+ Number(prev.size) === Number(v.size)
745
+ ) {
746
+ const recordedAt =
747
+ Math.max(Number(prev.recordedAt || 0), Number(v.recordedAt || 0)) || Date.now();
748
+ nextIntervals[k] = {
749
+ mtimeMs: Number(v.mtimeMs),
750
+ size: Number(v.size),
751
+ recordedAt,
752
+ intervals: mergeLineIntervals([...(prev.intervals || []), ...(v.intervals || [])])
753
+ };
754
+ } else {
755
+ nextIntervals[k] = v && typeof v === 'object' && !v.recordedAt
756
+ ? { ...v, recordedAt: Date.now() }
757
+ : v;
758
+ }
759
+ }
760
+ for (const delKey of clearIntervalKeys) {
761
+ delete nextIntervals[delKey];
762
+ }
763
+ mergedStore.__readIntervals = nextIntervals;
764
+ }
765
+
766
+ if (mergedStore.__readIntervals && typeof mergedStore.__readIntervals === 'object') {
767
+ const intervalKeys = Object.keys(mergedStore.__readIntervals);
768
+ while (intervalKeys.length > 24) {
769
+ const oldestInterval = intervalKeys.shift();
770
+ delete mergedStore.__readIntervals[oldestInterval];
771
+ }
772
+ }
773
+ atomicWriteFileSync(snapFilePath, JSON.stringify(mergedStore), { encoding: 'utf8' });
774
+ return mergedStore;
775
+ }
776
+
777
+ export function saveReadSnapStore(snapFilePath, store, options = {}) {
778
+ if (!snapFilePath) return;
779
+ try {
780
+ withFileLockSync(snapFilePath, () => writeReadSnapStoreUnlocked(snapFilePath, store, options));
781
+ } catch (writeErr) {
782
+ void writeErr; // ignore: non-fatal read snapshot persistence
783
+ }
784
+ }
785
+
786
+ export function updateReadSnapStoreAtomicSync(baseCwd, sessionId, mutatorFn, options = {}) {
787
+ const snapFilePath = getReadSnapFilePath(baseCwd, sessionId, options);
788
+ if (!snapFilePath || typeof mutatorFn !== 'function') return null;
789
+ return withFileLockSync(snapFilePath, () => {
790
+ const { store } = loadReadSnapStore(baseCwd, sessionId, options);
791
+ const updated = mutatorFn(store) || store;
792
+ return writeReadSnapStoreUnlocked(snapFilePath, updated);
793
+ });
794
+ }
795
+
796
+ export default {
797
+ DEFAULT_MAX_UNSLICED_LINES,
798
+ DEFAULT_MAX_UNSLICED_BYTES,
799
+ DEFAULT_MAX_SLICE_LINES,
800
+ DEFAULT_MAX_SLICE_BYTES,
801
+ CLAMP_TARGET_BYTES,
802
+ CLAMP_TARGET_LINES,
803
+ NEVER_TRIM_CODE_HARD_CEILING_BYTES,
804
+ OOM_HEAD_PROBE_BYTES,
805
+ HUGE_FILE_HEAD_PROBE_BYTES,
806
+ MEASURED_REREAD_P_CODE,
807
+ MEASURED_REREAD_P_DOC,
808
+ DEFAULT_READ_INTERVAL_TTL_MS,
809
+ STRUCTURED_DATA_EXT_RE,
810
+ isBurnoffArtifactPath,
811
+ isGeneratedOrMinifiedCodePath,
812
+ isActiveSourceCodePath,
813
+ isStructuredDataPath,
814
+ matchesNeverClampExt,
815
+ computeByteBoundedSliceWindow,
816
+ buildCompactClampLandmarks,
817
+ evaluateClampExpectedValue,
818
+ evaluateShieldReadGuard,
819
+ getReadSnapFilePath,
820
+ loadReadSnapStore,
821
+ mergeLineIntervals,
822
+ trimRequestedRangeAgainstIntervals,
823
+ recordReadIntervalEntry,
824
+ saveReadSnapStore,
825
+ updateReadSnapStoreAtomicSync
826
+ };