burnoff 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,31 +7,83 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { withFileLockSync } from '../storage/file-lock.mjs';
10
- import { atomicWriteJsonSync } from '../storage/atomic-io.mjs';
10
+ import { atomicWriteJsonSync, sleepSync } from '../storage/atomic-io.mjs';
11
11
  import { getBurnoffRuntimeDir, getHomeDir } from '../config/paths.mjs';
12
12
 
13
13
  export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 3;
14
14
  export const DEFAULT_SCOPE_LOCK_TTL_MS = 15 * 60 * 1000;
15
+ const DET04_EXEMPT_READ_TOOLS = /^(?:Read|Grep|Glob)$/i;
15
16
 
16
17
  function readJsonSafe(filePath, fallback = null) {
17
- try {
18
- if (!filePath || !fs.existsSync(filePath)) return fallback;
19
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
20
- } catch (err) {
21
- void err; // ignore: unreadable or corrupt state JSON falls back safely
22
- return fallback;
18
+ if (!filePath) return fallback;
19
+ for (let attempt = 0; attempt < 12; attempt += 1) {
20
+ try {
21
+ if (!fs.existsSync(filePath)) return fallback;
22
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
23
+ } catch (err) {
24
+ if (
25
+ attempt < 11 &&
26
+ (err?.code === 'EPERM' || err?.code === 'EBUSY' || err?.code === 'EACCES')
27
+ ) {
28
+ sleepSync(5);
29
+ continue;
30
+ }
31
+ return fallback;
32
+ }
23
33
  }
34
+ return fallback;
24
35
  }
25
36
 
26
37
  function getEffectiveCwd(options = {}) {
27
38
  return options?.cwd ? path.resolve(String(options.cwd)) : process.cwd();
28
39
  }
29
40
 
41
+ export function computeToolFailureKey({ toolName = '', command = '', filePath = '' } = {}) {
42
+ const normTool = String(toolName || '').trim() || 'unknown';
43
+ const rawCmd = String(command || '').trim();
44
+ if (rawCmd) {
45
+ const cmdPrefix = rawCmd.split(/\s+/).slice(0, 2).join(' ');
46
+ return `${normTool}:${cmdPrefix}`;
47
+ }
48
+ const rawFile = String(filePath || '').trim();
49
+ if (rawFile) {
50
+ return `${normTool}:${rawFile.replace(/\\/g, '/')}`;
51
+ }
52
+ return normTool;
53
+ }
54
+
30
55
  /**
31
56
  * DET-04: Consecutive Tool Failure Breaker (`>= maxConsecutiveFailures` -> block next attempt).
32
57
  */
33
58
  export function evaluateDet04ConsecutiveFailures(params = {}) {
34
- const count = Math.max(0, Number(params.consecutiveFailures || 0));
59
+ const toolName = String(params.toolName || '');
60
+ const command = String(params.command || '');
61
+ if (DET04_EXEMPT_READ_TOOLS.test(toolName) || /\bgit\s+stash\b/i.test(command)) {
62
+ return {
63
+ detectorId: 'DET-04',
64
+ triggered: false,
65
+ decision: 'allow',
66
+ consecutiveFailures: 0,
67
+ lastFailedToolKey: params.lastFailedToolKey || null,
68
+ reason: null
69
+ };
70
+ }
71
+
72
+ const hasIncomingIdentity = Boolean(
73
+ params.toolKey || params.toolName || params.command || params.filePath
74
+ );
75
+ const incomingKey =
76
+ params.toolKey ||
77
+ computeToolFailureKey({
78
+ toolName,
79
+ command,
80
+ filePath: params.filePath
81
+ });
82
+ const sameTool =
83
+ !params.lastFailedToolKey ||
84
+ !hasIncomingIdentity ||
85
+ incomingKey === params.lastFailedToolKey;
86
+ const count = sameTool ? Math.max(0, Number(params.consecutiveFailures || 0)) : 0;
35
87
  const threshold = Math.max(1, Number(params.maxConsecutiveFailures ?? params.threshold ?? DEFAULT_MAX_CONSECUTIVE_FAILURES));
36
88
  const toolSuffix = params.toolName ? ` on ${params.toolName}` : '';
37
89
 
@@ -41,8 +93,8 @@ export function evaluateDet04ConsecutiveFailures(params = {}) {
41
93
  triggered: true,
42
94
  decision: 'deny',
43
95
  consecutiveFailures: count,
44
- lastFailedToolKey: params.lastFailedToolKey || null,
45
- reason: `[Burnoff DET-04 Consecutive Failure Breaker] ${count} consecutive tool failures detected${toolSuffix}. Halting next attempt to prevent retry churn; re-verify assumptions before retrying.`
96
+ lastFailedToolKey: params.lastFailedToolKey || incomingKey || null,
97
+ reason: `[Burnoff DET-04 Consecutive Failure Breaker] ${count} consecutive identical tool failures detected${toolSuffix}. Halting next attempt to prevent retry churn; re-verify assumptions before retrying.`
46
98
  };
47
99
  }
48
100
 
@@ -104,7 +156,10 @@ export function updateBreakerStateAtomicSync(sessionId = 'default', mutatorFn, o
104
156
  const prior = readJsonSafe(filePath, null);
105
157
  const next = mutatorFn(prior);
106
158
  if (next && typeof next === 'object') {
107
- atomicWriteJsonSync(filePath, next, options);
159
+ atomicWriteJsonSync(filePath, next, {
160
+ ...options,
161
+ maxRetries: Math.max(10, Number(options?.maxRetries || 10))
162
+ });
108
163
  }
109
164
  return next;
110
165
  },
@@ -117,7 +172,7 @@ export function updateBreakerStateAtomicSync(sessionId = 'default', mutatorFn, o
117
172
  */
118
173
  export function recordToolOutcomeAtomicSync(
119
174
  sessionId = 'default',
120
- { toolName = '', command = '', failed = false, nowMs = Date.now() } = {},
175
+ { toolName = '', command = '', filePath = '', failed = false, nowMs = Date.now() } = {},
121
176
  options = {}
122
177
  ) {
123
178
  const isStashPush =
@@ -125,19 +180,21 @@ export function recordToolOutcomeAtomicSync(
125
180
  Boolean(command) &&
126
181
  /\bgit\s+stash\b/i.test(String(command)) &&
127
182
  !/\bgit\s+stash\s+(?:pop|drop|clear|apply|list|show)\b/i.test(String(command));
183
+ const toolKey = computeToolFailureKey({ toolName, command, filePath });
128
184
 
129
185
  return updateBreakerStateAtomicSync(
130
186
  sessionId,
131
187
  (prior) => {
132
188
  const base = prior && typeof prior === 'object' ? { ...prior } : {};
133
189
  const prevFailures = Math.max(0, Number(base.consecutiveFailures || 0));
134
- const nextFailures = failed ? prevFailures + 1 : 0;
190
+ const sameTool = !base.lastFailedToolKey || base.lastFailedToolKey === toolKey;
191
+ const nextFailures = failed ? (sameTool ? prevFailures + 1 : 1) : 0;
135
192
  const next = {
136
193
  ...base,
137
194
  schemaVersion: '1.0.0',
138
195
  sessionId: String(sessionId || 'default'),
139
196
  consecutiveFailures: nextFailures,
140
- lastFailedToolKey: failed ? (String(toolName || base.lastFailedToolKey || 'unknown')) : null,
197
+ lastFailedToolKey: failed ? toolKey : null,
141
198
  updatedAt: nowMs
142
199
  };
143
200
  if (isStashPush) {
@@ -482,6 +539,7 @@ export function evaluateScopeAndQuotaBrake(params = {}, options = {}) {
482
539
  export default {
483
540
  DEFAULT_MAX_CONSECUTIVE_FAILURES,
484
541
  DEFAULT_SCOPE_LOCK_TTL_MS,
542
+ computeToolFailureKey,
485
543
  evaluateDet04ConsecutiveFailures,
486
544
  sanitizeBreakerSessionId,
487
545
  getBreakerStateFilePath,
@@ -10,9 +10,14 @@ import fs from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import crypto from 'node:crypto';
12
12
  import { loadBurnoffPolicy } from '../config/policy.mjs';
13
+ import { getHomeDir } from '../config/paths.mjs';
13
14
  import { computeTotalPromptTokens, resolveEffectiveRates } from '../config/loader.mjs';
14
15
  import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
15
- import { compressCliOutputFts5Sync, classifyShellPostToolPolicy } from '../storage/fts5-archive.mjs';
16
+ import {
17
+ compressCliOutputFts5Sync,
18
+ classifyShellPostToolPolicy,
19
+ getDefaultToolLogsDbPath
20
+ } from '../storage/fts5-archive.mjs';
16
21
  import { recordSavingsReceipt, LEDGER_BUCKETS } from '../storage/ledger.mjs';
17
22
  import { recordToolOutcomeAtomicSync } from './loop-breaker.mjs';
18
23
 
@@ -179,10 +184,13 @@ export function didToolExecutionFail(event = {}) {
179
184
 
180
185
  function resolvePostOutputMode(policyPost = {}) {
181
186
  const envRaw = String(globalThis.process?.env?.BURNOFF_POST_OUTPUT_MODE || '').trim().toLowerCase();
182
- if (envRaw === 'context') return 'context';
183
- if (envRaw === 'replace') return 'replace';
187
+ if (envRaw === 'context' || envRaw === 'additionalcontext') return 'context';
188
+ if (envRaw === 'replace' || envRaw === 'updatedtooloutput') return 'replace';
189
+ if (envRaw === 'auto') return 'auto';
184
190
  const cfgMode = String(policyPost.outputMode || 'auto').trim().toLowerCase();
185
- return cfgMode === 'context' ? 'context' : 'replace';
191
+ if (cfgMode === 'context' || cfgMode === 'additionalcontext') return 'context';
192
+ if (cfgMode === 'replace' || cfgMode === 'updatedtooloutput') return 'replace';
193
+ return 'auto';
186
194
  }
187
195
 
188
196
  function offloadOversizedOutput(toolName, cleanText, filteredLines, criticalErrorLines, baseCwd) {
@@ -338,6 +346,9 @@ export function runPostToolUseHook(event = {}, options = {}) {
338
346
  const postCfg = policy.postTool || {};
339
347
 
340
348
  const toolInput = event.tool_input || event.toolInput || {};
349
+ const filePath = String(
350
+ toolInput.file_path || toolInput.notebook_path || toolInput.filePath || toolInput.path || toolInput.Path || toolInput.TargetFile || event.filePath || ''
351
+ ).trim();
341
352
  const cmdStr = String(
342
353
  toolInput.command || toolInput.CommandLine || toolInput.cmd || event.command || ''
343
354
  );
@@ -358,6 +369,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
358
369
  {
359
370
  toolName,
360
371
  command: cmdStr,
372
+ filePath,
361
373
  failed,
362
374
  nowMs: options.nowMs ?? Date.now()
363
375
  },
@@ -375,7 +387,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
375
387
  };
376
388
  }
377
389
 
378
- const unprefixed = toolName.replace(/^(?:default_api:|mcp__[a-zA-Z0-9_-]+__)/i, '');
390
+ const unprefixed = toolName.replace(/^mcp__[a-zA-Z0-9_-]+__/i, '');
379
391
  if (PROTECTED_WORKSPACE_TOOL_RE.test(unprefixed) || !ELIGIBLE_POST_TOOL_RE.test(toolName)) {
380
392
  return {
381
393
  exitCode: 0,
@@ -416,7 +428,9 @@ export function runPostToolUseHook(event = {}, options = {}) {
416
428
  const ansiCleanShell = stripAnsiAndSpinners(rawOutput);
417
429
  const criticalLines = extractCriticalErrorLines(ansiCleanShell);
418
430
  const ftsDbPath =
419
- options.dbPath || path.join(baseCwd, '.claude', 'cache', 'tool_logs_fts5.db');
431
+ options.dbPath ||
432
+ options.ftsDbPath ||
433
+ getDefaultToolLogsDbPath(options.homeDir || getHomeDir());
420
434
  const turnId = String(event.tool_use_id || event.turn_id || event.turnId || `turn-${Date.now()}`);
421
435
  const ftsComp = compressCliOutputFts5Sync({
422
436
  sessionId,
@@ -425,6 +439,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
425
439
  exitCode: typeof rawExit === 'number' ? rawExit : (failed ? 1 : 0),
426
440
  rawOutput: ansiCleanShell,
427
441
  dbPath: ftsDbPath,
442
+ homeDir: options.homeDir || getHomeDir(),
428
443
  recordLedger: false,
429
444
  minBytes: minFtsBytes,
430
445
  minTokensSaved: Number(options.minTokensSaved ?? 500),
@@ -480,9 +495,14 @@ export function runPostToolUseHook(event = {}, options = {}) {
480
495
  : { ok: false };
481
496
  const wouldInflate = !isMcpTool && replacement.ok && finalOutput.length >= rawOutput.length;
482
497
  const effectiveReplacementOk = replacement.ok && !wouldInflate;
483
- const allowContextFallback = !isMcpTool && !effectiveReplacementOk && postOutputMode === 'context';
484
-
485
- if (!wasModified || (!isMcpTool && !effectiveReplacementOk && !allowContextFallback)) {
498
+ const hasActionablePointer = Boolean(sanitized.offloaded || ftsSavedTokens > 0);
499
+ const emitContext =
500
+ !isMcpTool &&
501
+ !effectiveReplacementOk &&
502
+ wasModified &&
503
+ (postOutputMode === 'context' || (postOutputMode === 'auto' && hasActionablePointer));
504
+
505
+ if (!wasModified || (!isMcpTool && !effectiveReplacementOk && !emitContext)) {
486
506
  return {
487
507
  exitCode: 0,
488
508
  stdout: '',
@@ -491,8 +511,8 @@ export function runPostToolUseHook(event = {}, options = {}) {
491
511
  };
492
512
  }
493
513
 
494
- const outputReplaced = isMcpTool ? wasModified : effectiveReplacementOk;
495
- const totalSavedTokens = outputReplaced
514
+ const outputAcceptedByHost = isMcpTool ? wasModified : effectiveReplacementOk;
515
+ const totalSavedTokens = outputAcceptedByHost
496
516
  ? (ftsSavedTokens > 0 ? ftsSavedTokens : sanitized.savedTokens)
497
517
  : 0;
498
518
 
@@ -501,7 +521,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
501
521
  typeof event.model === 'string'
502
522
  ? event.model
503
523
  : event.model?.id || event.model?.model_id || event.modelId || event.model_id;
504
- const modelId = rawEventModel || 'claude-sonnet-4-6';
524
+ const modelId = rawEventModel || 'claude-sonnet-5-5';
505
525
  const usageSource = event.usage || event.context_window?.current_usage || {};
506
526
  const totalPromptTokens = computeTotalPromptTokens(usageSource);
507
527
  const rates = resolveEffectiveRates(modelId, totalPromptTokens, cwdOptions);
@@ -519,6 +539,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
519
539
  recordSavingsReceipt(
520
540
  {
521
541
  sessionId,
542
+ cwd: baseCwd,
522
543
  modelId: rates.unknownModel ? (rates.rawModelId || modelId) : rates.modelId,
523
544
  ledgerBucket: LEDGER_BUCKETS.AVOIDED_WRITE,
524
545
  category: sanitized.offloaded
@@ -9,7 +9,7 @@ import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { loadBurnoffPolicy } from '../config/policy.mjs';
11
11
  import { computeTotalPromptTokens } from '../config/loader.mjs';
12
- import { recordInterventionSavings } from '../storage/ledger.mjs';
12
+ import { recordInterventionSavings, recordSavingsReceipt } from '../storage/ledger.mjs';
13
13
  import {
14
14
  SHELL_TOOL_REGEX,
15
15
  evaluateDet01GitAndShellSafety,
@@ -81,7 +81,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
81
81
  ).trim();
82
82
  const modelId =
83
83
  (typeof event.model === 'string' ? event.model : event.model?.id || event.modelId || event.model_id) ||
84
- 'claude-sonnet-4-6';
84
+ 'claude-sonnet-5-5';
85
85
 
86
86
  let advisoryNotice = null;
87
87
 
@@ -141,6 +141,22 @@ export function runPreToolUseHook(event = {}, options = {}) {
141
141
  verdict: det01
142
142
  };
143
143
  }
144
+ if (canRecordLedger) {
145
+ recordSavingsReceipt(
146
+ {
147
+ sessionId,
148
+ cwd: baseCwd,
149
+ category: 'RING0_VIOLATION_BLOCKED',
150
+ detectorId: det01.detectorId,
151
+ ring0Violation: true,
152
+ modelId,
153
+ savedTokens: 0,
154
+ savedUSD: 0,
155
+ detail: det01.reason
156
+ },
157
+ cwdOptions
158
+ );
159
+ }
144
160
  return {
145
161
  exitCode: 2,
146
162
  stdout: '',
@@ -159,6 +175,22 @@ export function runPreToolUseHook(event = {}, options = {}) {
159
175
  command
160
176
  });
161
177
  if (det02.triggered) {
178
+ if (canRecordLedger) {
179
+ recordSavingsReceipt(
180
+ {
181
+ sessionId,
182
+ cwd: baseCwd,
183
+ category: 'RING0_VIOLATION_BLOCKED',
184
+ detectorId: det02.detectorId,
185
+ ring0Violation: true,
186
+ modelId,
187
+ savedTokens: 0,
188
+ savedUSD: 0,
189
+ detail: det02.reason
190
+ },
191
+ cwdOptions
192
+ );
193
+ }
162
194
  return {
163
195
  exitCode: 2,
164
196
  stdout: '',
@@ -200,10 +232,28 @@ export function runPreToolUseHook(event = {}, options = {}) {
200
232
  consecutiveFailures,
201
233
  lastFailedToolKey: priorSnap?.lastFailedToolKey || null,
202
234
  toolName,
235
+ command,
236
+ filePath: rawPath,
203
237
  maxConsecutiveFailures:
204
238
  options.maxConsecutiveFailures ?? guardsCfg.det04Threshold ?? 3
205
239
  });
206
240
  if (det04.triggered && det04.decision === 'deny') {
241
+ if (canRecordLedger) {
242
+ recordSavingsReceipt(
243
+ {
244
+ sessionId,
245
+ cwd: baseCwd,
246
+ category: 'RING0_VIOLATION_BLOCKED',
247
+ detectorId: det04.detectorId,
248
+ ring0Violation: true,
249
+ modelId,
250
+ savedTokens: 0,
251
+ savedUSD: 0,
252
+ detail: det04.reason
253
+ },
254
+ cwdOptions
255
+ );
256
+ }
207
257
  return {
208
258
  exitCode: 2,
209
259
  stdout: '',
@@ -346,12 +396,14 @@ export function runPreToolUseHook(event = {}, options = {}) {
346
396
  const shieldVerdict = evaluateShieldReadGuard({
347
397
  sessionId,
348
398
  cwd: baseCwd,
399
+ homeDir: options.homeDir,
349
400
  filePath: rawPath,
350
401
  hasSliceBounds: hasExplicitLineSlice || hasLineBounds,
351
402
  sliceOffset: effectiveSliceOffset,
352
403
  sliceLimit: effectiveSliceLimit,
353
404
  currentPromptTokens: promptTok,
354
405
  modelId,
406
+ policy,
355
407
  shieldConfig: options.shieldConfig,
356
408
  forceActive: Boolean(options.shieldForceActive),
357
409
  recordLedger: canRecordLedger,
@@ -7,7 +7,7 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import crypto from 'node:crypto';
10
- import { resolveEffectiveRates, getModelPricingCliff } from '../config/loader.mjs';
10
+ import { resolveEffectiveRates } from '../config/loader.mjs';
11
11
  import { loadBurnoffPolicy } from '../config/policy.mjs';
12
12
  import { withFileLockSync } from '../storage/file-lock.mjs';
13
13
  import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
@@ -169,12 +169,14 @@ export function evaluateClampExpectedValue({
169
169
  export function evaluateShieldReadGuard({
170
170
  sessionId = 'default',
171
171
  cwd = process.cwd(),
172
+ homeDir,
172
173
  filePath = '',
173
174
  hasSliceBounds = false,
174
175
  sliceOffset = null,
175
176
  sliceLimit = null,
176
177
  currentPromptTokens = 0,
177
- modelId = 'claude-sonnet-4-6',
178
+ modelId = 'claude-sonnet-5-5',
179
+ policy: providedPolicy = null,
178
180
  shieldConfig = null,
179
181
  forceActive = false,
180
182
  recordLedger = true,
@@ -196,7 +198,7 @@ export function evaluateShieldReadGuard({
196
198
  return { action: 'allow' };
197
199
  }
198
200
 
199
- const policy = loadBurnoffPolicy(baseCwd);
201
+ const policy = providedPolicy || loadBurnoffPolicy(baseCwd);
200
202
  const rc = policy.readClamp || {};
201
203
  const enabled = forceActive || (shieldConfig?.enabled !== undefined ? Boolean(shieldConfig.enabled) : rc.enabled !== false);
202
204
  const headProbeMaxBytes = Math.max(
@@ -221,9 +223,11 @@ export function evaluateShieldReadGuard({
221
223
  const cfgSliceLines = Number(shieldConfig?.maxSliceLines ?? DEFAULT_MAX_SLICE_LINES);
222
224
  const cfgSliceBytes = Number(shieldConfig?.maxSliceBytes ?? DEFAULT_MAX_SLICE_BYTES);
223
225
 
224
- const cliffObj = getModelPricingCliff(modelId, { cwd: baseCwd });
225
- const cliffTokens = cliffObj ? Number(cliffObj.thresholdTokens || 0) : 0;
226
226
  const promptTok = Math.max(0, Number(currentPromptTokens) || 0);
227
+ const baseRates = promptTok > 0
228
+ ? resolveEffectiveRates(modelId, promptTok, { cwd: baseCwd, homeDir })
229
+ : null;
230
+ const cliffTokens = baseRates?.cliffThresholdTokens ? Number(baseRates.cliffThresholdTokens) : 0;
227
231
  const nearCliff = cliffTokens > 0 && promptTok >= Math.floor(cliffTokens * 0.9);
228
232
 
229
233
  if (!enabled && !nearCliff) {
@@ -310,7 +314,9 @@ export function evaluateShieldReadGuard({
310
314
  const isCode = isActiveSourceCodePath(absFile);
311
315
  const realizedFactor = isCode ? codeRealizationFactor : 1 - MEASURED_REREAD_P_DOC;
312
316
  const realizedClampSavedTokens = Math.max(0, Math.round(clampSavedTokens * realizedFactor));
313
- const rates = resolveEffectiveRates(modelId, promptTok, { cwd: baseCwd });
317
+ const rates = recordLedger
318
+ ? (baseRates || resolveEffectiveRates(modelId, promptTok, { cwd: baseCwd, homeDir }))
319
+ : null;
314
320
  const clampSavedUSD = rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
315
321
  ? Number(((realizedClampSavedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
316
322
  : 0;
@@ -328,6 +334,7 @@ export function evaluateShieldReadGuard({
328
334
  recordInterventionSavings(
329
335
  {
330
336
  sessionId,
337
+ cwd: baseCwd,
331
338
  category: 'BOUNDED_READ_ENFORCED',
332
339
  modelId,
333
340
  savedTokens: realizedClampSavedTokens,
@@ -337,7 +344,7 @@ export function evaluateShieldReadGuard({
337
344
  dedupeId: `huge_clamp:${dedupeHash}`,
338
345
  detail: `Fast-clamped huge file ${displayFile} (${(stat.size / (1024 * 1024)).toFixed(1)} MB)`
339
346
  },
340
- { cwd: baseCwd, ...(ledgerPath ? { ledgerPath } : {}) }
347
+ { cwd: baseCwd, skipFsync: true, ...(homeDir ? { homeDir } : {}), ...(ledgerPath ? { ledgerPath } : {}) }
341
348
  );
342
349
  }
343
350
 
@@ -478,6 +485,7 @@ export function evaluateShieldReadGuard({
478
485
  recordInterventionSavings(
479
486
  {
480
487
  sessionId,
488
+ cwd: baseCwd,
481
489
  category: 'BOUNDED_READ_ENFORCED',
482
490
  modelId,
483
491
  savedTokens: realizedClampSavedTokens,
@@ -487,7 +495,7 @@ export function evaluateShieldReadGuard({
487
495
  dedupeId: `clamp:${clampDedupeHash}`,
488
496
  detail: `Clamped read of ${displayFile} (${reqOffset}..${clampEnd} of ${totalLines} lines)`
489
497
  },
490
- { cwd: baseCwd, ...(ledgerPath ? { ledgerPath } : {}) }
498
+ { cwd: baseCwd, skipFsync: true, ...(homeDir ? { homeDir } : {}), ...(ledgerPath ? { ledgerPath } : {}) }
491
499
  );
492
500
  }
493
501
 
@@ -514,7 +522,7 @@ export function evaluateShieldReadGuard({
514
522
 
515
523
  export function getReadSnapFilePath(baseCwd, sessionId = 'default') {
516
524
  if (!baseCwd) return '';
517
- const safeSid = String(sessionId || 'default').replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64) || 'default';
525
+ const safeSid = String(sessionId || 'default').replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 64) || 'default';
518
526
  return path.join(path.resolve(String(baseCwd)), '.claude', 'cache', `read_snapshots_${safeSid}.json`);
519
527
  }
520
528
 
@@ -635,56 +643,63 @@ export function recordReadIntervalEntry(store, normKey, statObj, startLine, endL
635
643
  };
636
644
  }
637
645
 
638
- export function saveReadSnapStore(snapFilePath, store, { clearIntervalKeys = [], clearAllIntervals = false } = {}) {
639
- if (!snapFilePath) return;
640
- try {
641
- withFileLockSync(snapFilePath, () => {
642
- let diskStore = {};
643
- if (fs.existsSync(snapFilePath)) {
644
- try {
645
- const parsed = JSON.parse(fs.readFileSync(snapFilePath, 'utf8'));
646
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) diskStore = parsed;
647
- } catch (err) {
648
- void err; // ignore: corrupt snapshot overwritten cleanly
649
- }
650
- }
651
- const mergedStore = { ...diskStore, ...store };
652
- if (clearAllIntervals) {
653
- mergedStore.__readIntervals = {};
654
- } else if (diskStore.__readIntervals || store.__readIntervals) {
655
- const nextIntervals = { ...(diskStore.__readIntervals || {}) };
656
- for (const [k, v] of Object.entries(store.__readIntervals || {})) {
657
- const prev = nextIntervals[k];
658
- if (
659
- prev &&
660
- v &&
661
- Number(prev.mtimeMs) === Number(v.mtimeMs) &&
662
- Number(prev.size) === Number(v.size)
663
- ) {
664
- nextIntervals[k] = {
665
- mtimeMs: Number(v.mtimeMs),
666
- size: Number(v.size),
667
- intervals: mergeLineIntervals([...(prev.intervals || []), ...(v.intervals || [])])
668
- };
669
- } else {
670
- nextIntervals[k] = v;
671
- }
672
- }
673
- for (const delKey of clearIntervalKeys) {
674
- delete nextIntervals[delKey];
675
- }
676
- mergedStore.__readIntervals = nextIntervals;
646
+ function writeReadSnapStoreUnlocked(
647
+ snapFilePath,
648
+ store,
649
+ { clearIntervalKeys = [], clearAllIntervals = false } = {}
650
+ ) {
651
+ let diskStore = {};
652
+ if (fs.existsSync(snapFilePath)) {
653
+ try {
654
+ const parsed = JSON.parse(fs.readFileSync(snapFilePath, 'utf8'));
655
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) diskStore = parsed;
656
+ } catch (err) {
657
+ void err; // ignore: corrupt snapshot overwritten cleanly
658
+ }
659
+ }
660
+ const mergedStore = { ...diskStore, ...store };
661
+ if (clearAllIntervals) {
662
+ mergedStore.__readIntervals = {};
663
+ } else if (diskStore.__readIntervals || store.__readIntervals) {
664
+ const nextIntervals = { ...(diskStore.__readIntervals || {}) };
665
+ for (const [k, v] of Object.entries(store.__readIntervals || {})) {
666
+ const prev = nextIntervals[k];
667
+ if (
668
+ prev &&
669
+ v &&
670
+ Number(prev.mtimeMs) === Number(v.mtimeMs) &&
671
+ Number(prev.size) === Number(v.size)
672
+ ) {
673
+ nextIntervals[k] = {
674
+ mtimeMs: Number(v.mtimeMs),
675
+ size: Number(v.size),
676
+ intervals: mergeLineIntervals([...(prev.intervals || []), ...(v.intervals || [])])
677
+ };
678
+ } else {
679
+ nextIntervals[k] = v;
677
680
  }
681
+ }
682
+ for (const delKey of clearIntervalKeys) {
683
+ delete nextIntervals[delKey];
684
+ }
685
+ mergedStore.__readIntervals = nextIntervals;
686
+ }
678
687
 
679
- if (mergedStore.__readIntervals && typeof mergedStore.__readIntervals === 'object') {
680
- const intervalKeys = Object.keys(mergedStore.__readIntervals);
681
- while (intervalKeys.length > 24) {
682
- const oldestInterval = intervalKeys.shift();
683
- delete mergedStore.__readIntervals[oldestInterval];
684
- }
685
- }
686
- atomicWriteFileSync(snapFilePath, JSON.stringify(mergedStore), { encoding: 'utf8' });
687
- });
688
+ if (mergedStore.__readIntervals && typeof mergedStore.__readIntervals === 'object') {
689
+ const intervalKeys = Object.keys(mergedStore.__readIntervals);
690
+ while (intervalKeys.length > 24) {
691
+ const oldestInterval = intervalKeys.shift();
692
+ delete mergedStore.__readIntervals[oldestInterval];
693
+ }
694
+ }
695
+ atomicWriteFileSync(snapFilePath, JSON.stringify(mergedStore), { encoding: 'utf8' });
696
+ return mergedStore;
697
+ }
698
+
699
+ export function saveReadSnapStore(snapFilePath, store, options = {}) {
700
+ if (!snapFilePath) return;
701
+ try {
702
+ withFileLockSync(snapFilePath, () => writeReadSnapStoreUnlocked(snapFilePath, store, options));
688
703
  } catch (writeErr) {
689
704
  void writeErr; // ignore: non-fatal read snapshot persistence
690
705
  }
@@ -696,8 +711,7 @@ export function updateReadSnapStoreAtomicSync(baseCwd, sessionId, mutatorFn) {
696
711
  return withFileLockSync(snapFilePath, () => {
697
712
  const { store } = loadReadSnapStore(baseCwd, sessionId);
698
713
  const updated = mutatorFn(store) || store;
699
- saveReadSnapStore(snapFilePath, updated);
700
- return updated;
714
+ return writeReadSnapStoreUnlocked(snapFilePath, updated);
701
715
  });
702
716
  }
703
717