burnoff 1.4.1 → 2.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.
Files changed (62) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.github/workflows/burnoff-pr-gate.yml +5 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +2 -2
  4. package/CHANGELOG.md +74 -0
  5. package/README.md +187 -213
  6. package/SECURITY.md +38 -0
  7. package/bin/burnoff.mjs +307 -32
  8. package/commands/burnoff.md +6 -4
  9. package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
  10. package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
  11. package/hooks/hook-io.mjs +216 -11
  12. package/hooks/hooks.json +44 -0
  13. package/hooks/post-tool-use.mjs +3 -1
  14. package/hooks/pre-tool-use.mjs +47 -8
  15. package/hooks/session-lifecycle.mjs +24 -3
  16. package/hooks/user-prompt-submit.mjs +98 -0
  17. package/package.json +6 -4
  18. package/scripts/bench-hooks.mjs +34 -3
  19. package/scripts/bench-savings.mjs +318 -0
  20. package/scripts/burnoff-statusline.mjs +138 -6
  21. package/src/ci/ci-gate.mjs +199 -13
  22. package/src/ci/pr-cost.mjs +417 -45
  23. package/src/ci/pr-summary.mjs +467 -0
  24. package/src/cli/audit.mjs +179 -28
  25. package/src/cli/doctor.mjs +32 -6
  26. package/src/cli/hook-health.mjs +9 -1
  27. package/src/cli/init.mjs +226 -39
  28. package/src/cli/preview.mjs +299 -0
  29. package/src/cli/startup-audit/formatter.mjs +248 -0
  30. package/src/cli/startup-audit/jsonc.mjs +601 -0
  31. package/src/cli/startup-audit/mcp-audit.mjs +735 -0
  32. package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
  33. package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
  34. package/src/cli/startup-audit.mjs +451 -2471
  35. package/src/clients/claude-code.mjs +41 -4
  36. package/src/config/catalog.json +295 -0
  37. package/src/config/effort.mjs +145 -0
  38. package/src/config/harness-quirks.mjs +340 -0
  39. package/src/config/loader.mjs +27 -2
  40. package/src/config/policy.mjs +81 -9
  41. package/src/config/pricing.mjs +247 -19
  42. package/src/config/semver.mjs +25 -0
  43. package/src/config/uncached-attribution.mjs +280 -41
  44. package/src/guards/compaction-baton.mjs +248 -0
  45. package/src/guards/loop-breaker.mjs +328 -47
  46. package/src/guards/model-switch-hook.mjs +126 -0
  47. package/src/guards/phase5-detectors.mjs +275 -21
  48. package/src/guards/post-tool-engine.mjs +333 -11
  49. package/src/guards/pre-tool-engine.mjs +607 -45
  50. package/src/guards/prefix-guard.mjs +609 -0
  51. package/src/guards/prompt-guard.mjs +309 -0
  52. package/src/guards/read-clamp.mjs +192 -8
  53. package/src/guards/session-hook.mjs +149 -7
  54. package/src/guards/shell-guard.mjs +56 -5
  55. package/src/guards/snooze.mjs +169 -5
  56. package/src/ipc/daemon.mjs +76 -0
  57. package/src/ipc/fast-client.mjs +165 -4
  58. package/src/ipc/protocol.mjs +16 -3
  59. package/src/storage/antigravity-parser.mjs +16 -2
  60. package/src/storage/file-lock.mjs +16 -3
  61. package/src/storage/jsonl-parser.mjs +133 -22
  62. package/src/storage/telemetry-metrics.mjs +254 -4
@@ -8,8 +8,9 @@
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { getClientAdapter, normalizeHookEvent } from '../clients/detect.mjs';
11
- import { tryTier1PreToolFastPath } from '../../hooks/hook-io.mjs';
11
+ import { tryTier1PreToolFastPath, normalizePlatformPathKey } from '../../hooks/hook-io.mjs';
12
12
  import { loadBurnoffPolicy } from '../config/policy.mjs';
13
+ import { getHomeDir } from '../config/paths.mjs';
13
14
  import { computeTotalPromptTokens } from '../config/loader.mjs';
14
15
  import { recordInterventionSavings, recordSavingsReceipt } from '../storage/ledger.mjs';
15
16
  import {
@@ -24,13 +25,17 @@ import {
24
25
  evaluateDet04ConsecutiveFailures,
25
26
  evaluateDet05SubagentFanout,
26
27
  evaluateScopeAndQuotaBrake,
28
+ extractModuleDir,
29
+ normalizeScopePath,
27
30
  readBreakerStateSnapshot,
28
31
  recordSubagentSpawnAtomicSync,
29
32
  updateBreakerStateAtomicSync
30
33
  } from './loop-breaker.mjs';
31
34
  import {
35
+ DEFAULT_READ_INTERVAL_MAX_TURN_GAP,
32
36
  DEFAULT_READ_INTERVAL_TTL_MS,
33
37
  evaluateShieldReadGuard,
38
+ isReadIntervalEntryFresh,
34
39
  loadReadSnapStore,
35
40
  trimRequestedRangeAgainstIntervals,
36
41
  recordReadIntervalEntry,
@@ -38,18 +43,79 @@ import {
38
43
  } from './read-clamp.mjs';
39
44
  import {
40
45
  consumeMatchingAskSnoozeAtomicSync,
46
+ getWorkspacePauseStatus,
41
47
  matchesSnoozeEntry
42
48
  } from './snooze.mjs';
43
49
  import {
44
50
  PHASE5_DEFAULTS,
45
51
  evaluateDet07CommandOutputGuard,
46
52
  evaluateDet08EditIntegrityGuard,
47
- evaluateDet09EditThrash
53
+ evaluateDet09EditThrash,
54
+ evaluateDet10FullFileRewriteGuard
48
55
  } from './phase5-detectors.mjs';
56
+ import { evaluatePrefixIntegrity } from './prefix-guard.mjs';
57
+ import { effortChangePreservesCache, resolveEffortLevel } from '../config/effort.mjs';
49
58
 
50
59
  const READ_TOOL_REGEX = /^(?:Read|read_file|view_file)$/i;
60
+ const DISCOVERY_TOOL_REGEX = /^(?:Read|Grep|Glob|read_file|view_file|grep_search|find_by_name|list_dir)$/i;
51
61
  const EDIT_WRITE_OR_READ_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit|Read|Grep|Glob|read_file|view_file|grep_search)$/i;
52
62
  const EDIT_WRITE_SCOPE_LOCK_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit)$/i;
63
+ const RASTER_IMAGE_EXT_RE = /\.(?:png|jpe?g|webp|gif|bmp|tiff)$/i;
64
+ const ALWAYS_ON_RULES_OR_MCP_RE = /(?:^|\/)(?:claude\.md|agents\.md|gemini\.md|\.mcp\.json)$/i;
65
+ const SUBAGENT_DEFINITION_FILE_RE = /(?:^|\/)\.claude\/agents\/[^/]+\.md$/i;
66
+
67
+ function countConfiguredMcpServers(baseCwd, homeDirOption) {
68
+ const names = new Set();
69
+ const readMcpMap = (filePath, projKey = null) => {
70
+ try {
71
+ if (!filePath || !fs.existsSync(filePath)) return;
72
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
73
+ const map = projKey ? parsed?.projects?.[projKey]?.mcpServers : parsed?.mcpServers;
74
+ if (map && typeof map === 'object') {
75
+ for (const k of Object.keys(map)) {
76
+ if (k) names.add(k);
77
+ }
78
+ }
79
+ } catch {
80
+ // ignore: unreadable optional mcp configuration
81
+ }
82
+ };
83
+ readMcpMap(path.join(baseCwd, '.mcp.json'));
84
+ const home = homeDirOption || getHomeDir();
85
+ if (home) {
86
+ readMcpMap(path.join(home, '.claude.json'));
87
+ readMcpMap(path.join(home, '.claude.json'), baseCwd);
88
+ }
89
+ const serverCount = names.size;
90
+ return { serverCount, estSchemaTokens: serverCount * 3200 };
91
+ }
92
+
93
+ export function countChangedLinesForEdit(toolName, tIn = {}) {
94
+ const tn = String(toolName || '');
95
+ const lineCount = (s) => (typeof s === 'string' && s.length > 0 ? s.split(/\r?\n/).length : 0);
96
+ if (/^(?:Edit|edit_file|replace_file_content)$/i.test(tn)) {
97
+ return Math.max(
98
+ lineCount(tIn.old_string ?? tIn.TargetContent ?? tIn.Target ?? ''),
99
+ lineCount(tIn.new_string ?? tIn.ReplacementContent ?? tIn.Replacement ?? '')
100
+ );
101
+ }
102
+ if (/^(?:MultiEdit|multi_replace_file_content)$/i.test(tn) && Array.isArray(tIn.edits || tIn.ReplacementChunks)) {
103
+ const edits = tIn.edits || tIn.ReplacementChunks;
104
+ return edits.reduce(
105
+ (sum, e) =>
106
+ sum +
107
+ Math.max(
108
+ lineCount(e?.old_string ?? e?.TargetContent ?? e?.Target ?? ''),
109
+ lineCount(e?.new_string ?? e?.ReplacementContent ?? e?.Replacement ?? '')
110
+ ),
111
+ 0
112
+ );
113
+ }
114
+ if (/^(?:Write|write_file|write_to_file)$/i.test(tn)) {
115
+ return lineCount(tIn.content ?? tIn.CodeContent ?? tIn.Content ?? '');
116
+ }
117
+ return 0;
118
+ }
53
119
 
54
120
  function evaluatePreToolUseCore(event = {}, options = {}) {
55
121
  const { client, adapter, canonical } =
@@ -57,7 +123,13 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
57
123
  ? { client: event.client || 'claude-code', adapter: getClientAdapter(event.client || 'claude-code'), canonical: event }
58
124
  : normalizeHookEvent(event, options);
59
125
 
60
- const finalize = (res) => (client === 'antigravity' ? adapter.renderPre(res) : res);
126
+ const finalize = (res) => {
127
+ if (client === 'antigravity') return adapter.renderPre(res);
128
+ if (client === 'claude-code' && canonical.hookEventName === 'PreSkillShellCommand') {
129
+ return adapter.renderPre(res, { hookEventName: canonical.hookEventName });
130
+ }
131
+ return res;
132
+ };
61
133
 
62
134
  const toolName = String(canonical.toolName || '');
63
135
  const fastAllowRes = tryTier1PreToolFastPath(
@@ -90,6 +162,9 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
90
162
  const priorSnap = shouldPersistState
91
163
  ? readBreakerStateSnapshot(sessionId, cwdOptions)
92
164
  : null;
165
+ const softPause = shouldPersistState
166
+ ? getWorkspacePauseStatus({ nowMs: options.nowMs ?? Date.now() }, cwdOptions)
167
+ : { active: false };
93
168
 
94
169
  if (policy?.exists && policy?.parseError && !priorSnap?.policyParseErrorWarned) {
95
170
  const writeStderr =
@@ -123,17 +198,67 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
123
198
  tIn.file_path || tIn.notebook_path || tIn.filePath || tIn.path || tIn.Path || tIn.TargetFile || event.filePath || ''
124
199
  ).trim();
125
200
  const modelId = canonical.model || 'claude-sonnet-5-5';
201
+ const explicitEventModel = String(canonical.model || '').trim();
202
+ // Claude Code sends `effort: { level }`; resolveEffortLevel never `String()`-coerces objects.
203
+ const explicitEffort = resolveEffortLevel(event, {
204
+ explicitEffort: canonical.effort,
205
+ env: options.env
206
+ });
207
+ const effortTier =
208
+ explicitEffort ||
209
+ resolveEffortLevel(event, {
210
+ priorEffort: priorSnap?.lastEffort,
211
+ transcriptPath: canonical.transcriptPath,
212
+ env: options.env
213
+ });
126
214
  const lastUserInput = canonical.lastUserInput || '';
127
215
  const guardMode = event.mode ?? options.mode ?? guardsCfg.mode ?? 'guard';
128
216
  const flightMode = event.flightMode ?? options.flightMode;
129
217
  const ownerId = String(
130
218
  canonical.agentId || event.ownerId || event.agentId || event.subagentId || sessionId
131
219
  );
220
+ const isSubagent = Boolean(
221
+ canonical.isSidechain ||
222
+ canonical.agentId ||
223
+ canonical.parentToolUseId ||
224
+ event.isSidechain ||
225
+ event.is_sidechain ||
226
+ event.agent_id ||
227
+ event.agentId ||
228
+ event.parent_tool_use_id ||
229
+ event.parentToolUseId
230
+ );
231
+ const eventUsage = event.usage || event.context_window?.current_usage || null;
232
+ const promptTok = Math.max(
233
+ computeTotalPromptTokens(event),
234
+ eventUsage ? computeTotalPromptTokens(eventUsage) : 0
235
+ );
132
236
 
133
- // Resolves interactive `ask` verdicts against active session/workspace snoozes.
237
+ // Resolves interactive `ask` verdicts against active workspace soft pause & session/workspace snoozes.
134
238
  // Security invariant: NEVER invoke for `deny` / `exitCode: 2` verdicts.
135
239
  const evaluateAskWithSnooze = (verdict, targetText = '') => {
136
240
  const evalNowMs = options.nowMs ?? Date.now();
241
+ if (softPause?.active) {
242
+ const remMins = Math.max(1, Math.ceil((softPause.remainingMs || 0) / 60_000));
243
+ return {
244
+ snoozed: true,
245
+ paused: true,
246
+ response: finalize({
247
+ exitCode: 0,
248
+ stdout: '',
249
+ stderr: '',
250
+ snoozed: true,
251
+ paused: true,
252
+ verdict: {
253
+ ...verdict,
254
+ decision: 'allow',
255
+ snoozed: true,
256
+ paused: true,
257
+ reason: `[Burnoff Paused] Soft gate ${verdict.detectorId} paused (${remMins}m left).`
258
+ }
259
+ })
260
+ };
261
+ }
137
262
  let match = null;
138
263
  if (Array.isArray(options.snoozes)) {
139
264
  const memHit = options.snoozes.find((entry) =>
@@ -196,6 +321,8 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
196
321
 
197
322
  let advisoryNotice = null;
198
323
  const appendAdvisory = (existing, nextVerdict) => {
324
+ if (!nextVerdict) return existing;
325
+ if (softPause?.active && !nextVerdict.ring0) return existing;
199
326
  if (!existing) return nextVerdict;
200
327
  return {
201
328
  ...existing,
@@ -269,11 +396,12 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
269
396
  {
270
397
  targetFilePath: EDIT_WRITE_OR_READ_REGEX.test(toolName) ? rawPath : '',
271
398
  isRead: isReadOp,
399
+ isSubagent,
272
400
  toolName,
273
401
  ownerId,
274
402
  rateLimits: event.rateLimits || options.rateLimits || {}
275
403
  },
276
- cwdOptions
404
+ { ...cwdOptions, persistReadScope: shouldPersistState }
277
405
  );
278
406
  if (det20.triggered) {
279
407
  if (det20.decision === 'deny') {
@@ -452,23 +580,37 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
452
580
  const subagentPromptText = String(
453
581
  tIn.prompt || tIn.Prompt || tIn.instructions || tIn.description || ''
454
582
  );
583
+ const subagentType = String(tIn.subagent_type || tIn.subagentType || '');
455
584
  const burstWindowSec = Number(
456
585
  options.subagentBurstWindowSec ?? guardsCfg.subagentBurstWindowSec ?? 60
457
586
  );
458
587
  const nowSubagentMs = options.nowMs ?? Date.now();
459
588
  const det05 = evaluateDet05SubagentFanout({
589
+ model: explicitEventModel || priorSnap?.lastModel || '',
460
590
  toolName,
591
+ subagentType,
461
592
  promptText: subagentPromptText,
462
593
  recentSpawnTimestampsMs:
463
594
  event.recentSpawnTimestampsMs ??
464
595
  options.recentSpawnTimestampsMs ??
465
596
  priorSnap?.subagentSpawnTimestampsMs ??
466
597
  [],
598
+ recentSpawns:
599
+ event.recentSpawns ??
600
+ options.recentSpawns ??
601
+ priorSnap?.recentSpawns ??
602
+ [],
467
603
  maxBurstCount:
468
604
  options.subagentMaxBurstCount ?? guardsCfg.subagentMaxBurstCount ?? 4,
605
+ openaiMaxBurstCount:
606
+ options.openaiMaxBurstCount ?? guardsCfg.openaiMaxBurstCount ?? 2,
469
607
  burstWindowSec,
470
608
  maxPromptChars:
471
609
  options.subagentMaxPromptChars ?? guardsCfg.subagentMaxPromptChars ?? 8000,
610
+ prefixCheckEnabled:
611
+ options.subagentPrefixCheckEnabled ?? guardsCfg.subagentPrefixCheckEnabled ?? true,
612
+ minSharedPrefixChars:
613
+ options.subagentPrefixMinSharedChars ?? guardsCfg.subagentPrefixMinSharedChars ?? 64,
472
614
  action:
473
615
  options.subagentFanoutAction ?? guardsCfg.subagentFanoutAction ?? 'advisory',
474
616
  nowMs: nowSubagentMs
@@ -502,7 +644,7 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
502
644
  if (shouldPersistState) {
503
645
  recordSubagentSpawnAtomicSync(
504
646
  sessionId,
505
- { nowMs: nowSubagentMs, burstWindowSec },
647
+ { nowMs: nowSubagentMs, burstWindowSec, promptText: subagentPromptText, subagentType },
506
648
  cwdOptions
507
649
  );
508
650
  }
@@ -551,12 +693,35 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
551
693
  checkTestSkip:
552
694
  options.det08CheckTestSkip ?? guardsCfg.det08CheckTestSkip ?? PHASE5_DEFAULTS.det08CheckTestSkip,
553
695
  checkEmptyCatch:
554
- options.det08CheckEmptyCatch ?? guardsCfg.det08CheckEmptyCatch ?? PHASE5_DEFAULTS.det08CheckEmptyCatch
696
+ options.det08CheckEmptyCatch ?? guardsCfg.det08CheckEmptyCatch ?? PHASE5_DEFAULTS.det08CheckEmptyCatch,
697
+ checkAssertionDrop:
698
+ options.det08CheckAssertionDrop ?? guardsCfg.det08CheckAssertionDrop ?? PHASE5_DEFAULTS.det08CheckAssertionDrop,
699
+ assertionDropAction:
700
+ options.det08AssertionDropAction ?? guardsCfg.det08AssertionDropAction ?? PHASE5_DEFAULTS.det08AssertionDropAction
555
701
  });
556
702
  const det08Response = handlePhase5Verdict(det08, rawPath, 'EDIT_INTEGRITY_GUARDED');
557
703
  if (det08Response) return det08Response;
558
704
  }
559
705
 
706
+ // 5d-2. DET-10: Full-File Rewrite / Regurgitation Guard
707
+ if (guardsCfg.det10Enabled !== false && /^(?:Write|write_file|write_to_file)$/i.test(toolName) && rawPath) {
708
+ const det10 = evaluateDet10FullFileRewriteGuard({
709
+ toolName,
710
+ filePath: rawPath,
711
+ toolInput: tIn,
712
+ cwd: baseCwd,
713
+ mode: guardMode,
714
+ flightMode,
715
+ action:
716
+ options.det10Action ??
717
+ guardsCfg.fullFileRewriteAction ??
718
+ guardsCfg.det10Action ??
719
+ PHASE5_DEFAULTS.det10Action
720
+ });
721
+ const det10Response = handlePhase5Verdict(det10, rawPath, 'FULL_FILE_REWRITE_GUARDED');
722
+ if (det10Response) return det10Response;
723
+ }
724
+
560
725
  // 5e. DET-09: Same-File Rapid Edit-Thrash Breaker (runs before DET-20 lock)
561
726
  if (guardsCfg.det09Enabled !== false && EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) && rawPath) {
562
727
  const det09 = evaluateDet09EditThrash({
@@ -585,18 +750,317 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
585
750
  if (det09Response) return det09Response;
586
751
  }
587
752
 
588
- // 6. Bounded Read Guard & Per-File Read-Interval Cache (`updatedInput`)
589
- const isSubagent = Boolean(
590
- canonical.isSidechain ||
591
- canonical.agentId ||
592
- canonical.parentToolUseId ||
593
- event.isSidechain ||
594
- event.is_sidechain ||
595
- event.agent_id ||
596
- event.agentId ||
597
- event.parent_tool_use_id ||
598
- event.parentToolUseId
753
+ // 5f. Runtime session telemetry & Phase 6 bad-habit detectors (DET-15, DET-17, DET-18, DET-19, BO-MOD-01, BO-MOD-02, BO-MCP-11)
754
+ const isReadTool = READ_TOOL_REGEX.test(toolName);
755
+ const isDiscoveryTool = DISCOVERY_TOOL_REGEX.test(toolName);
756
+ const isMutationTool = EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName);
757
+ const isMcpTool = /^mcp__/i.test(toolName);
758
+ const normRelTarget = rawPath ? normalizePlatformPathKey(normalizeScopePath(rawPath, baseCwd)) : '';
759
+ const normRawPath = rawPath ? rawPath.replace(/\\/g, '/') : '';
760
+ const isRulesOrMcpTarget = Boolean(normRelTarget) && ALWAYS_ON_RULES_OR_MCP_RE.test(normRelTarget);
761
+ const isSubagentDefinitionTarget =
762
+ Boolean(normRelTarget || normRawPath) &&
763
+ (SUBAGENT_DEFINITION_FILE_RE.test(normRelTarget) || SUBAGENT_DEFINITION_FILE_RE.test(normRawPath));
764
+ const explicitTurnNum = Number(event.turnCount ?? event.turn_count ?? event.turn ?? 0) || 0;
765
+ const promptTurnNum = Number(priorSnap?.promptCount || 0);
766
+ const hadPriorActivity =
767
+ Number(priorSnap?.discoveryCallsTotal || 0) + Number(priorSnap?.mutationCallsTotal || 0) > 0;
768
+ const isAfterTurnOne =
769
+ explicitTurnNum > 1 ||
770
+ promptTurnNum > 1 ||
771
+ (explicitTurnNum === 0 && promptTurnNum === 0 && hadPriorActivity);
772
+ const isRasterImageRead = isReadTool && Boolean(rawPath) && RASTER_IMAGE_EXT_RE.test(rawPath);
773
+
774
+ let sightseeingMode = false;
775
+ let discoveryCallsTotal = Number(priorSnap?.discoveryCallsTotal || 0);
776
+ let discoveryCallsSinceLastMutation = Number(priorSnap?.discoveryCallsSinceLastMutation || 0);
777
+ let mutationCallsTotal = Number(priorSnap?.mutationCallsTotal || 0);
778
+ const priorEditedFiles = Array.isArray(priorSnap?.editedFiles) ? [...priorSnap.editedFiles] : [];
779
+ let editedFiles = [...priorEditedFiles];
780
+ let imageReadCount = Number(priorSnap?.imageReadCount || 0);
781
+ let trivialEditStreak = Number(priorSnap?.trivialEditStreak || 0);
782
+ let nonMcpTurnCount = Number(priorSnap?.nonMcpTurnCount || 0);
783
+ let mcpCallsTotal = Number(priorSnap?.mcpCallsTotal || 0);
784
+ let lastMcpIdleWarnTurn = Number(priorSnap?.lastMcpIdleWarnTurn || 0);
785
+ let lastDet15WarnCount = Number(priorSnap?.lastDet15WarnCount || 0);
786
+ let det19WarnedCommitTs = priorSnap?.det19WarnedCommitTs ?? null;
787
+
788
+ if (isDiscoveryTool) {
789
+ discoveryCallsTotal += 1;
790
+ discoveryCallsSinceLastMutation += 1;
791
+ } else if (isMutationTool) {
792
+ discoveryCallsSinceLastMutation = 0;
793
+ mutationCallsTotal += 1;
794
+ if (normRelTarget && !editedFiles.includes(normRelTarget)) {
795
+ editedFiles = [...editedFiles, normRelTarget].slice(-32);
796
+ }
797
+ }
798
+
799
+ // DET-15: Exploration budget & sightseeing detection
800
+ const explorationBudget = Math.max(
801
+ 2,
802
+ Number(options.explorationBudgetCalls ?? guardsCfg.explorationBudgetCalls ?? 10)
599
803
  );
804
+ if (!isSubagent && discoveryCallsSinceLastMutation >= 8 && mutationCallsTotal === 0) {
805
+ sightseeingMode = true;
806
+ }
807
+ if (
808
+ isDiscoveryTool &&
809
+ !isSubagent &&
810
+ shouldPersistState &&
811
+ discoveryCallsSinceLastMutation >= explorationBudget &&
812
+ (lastDet15WarnCount === 0 || discoveryCallsSinceLastMutation - lastDet15WarnCount >= 5)
813
+ ) {
814
+ lastDet15WarnCount = discoveryCallsSinceLastMutation;
815
+ advisoryNotice = appendAdvisory(advisoryNotice, {
816
+ detectorId: 'DET-15',
817
+ triggered: true,
818
+ decision: 'allow',
819
+ subType: 'EXPLORATION_BUDGET_EXCEEDED',
820
+ reason:
821
+ `[Burnoff DET-15 Exploration Budget] ${discoveryCallsSinceLastMutation} consecutive discovery calls without an edit/write. ` +
822
+ `Switch from broad sightseeing to targeted symbol search or a concrete plan.`
823
+ });
824
+ }
825
+
826
+ // DET-18: Raster image / vision read guard
827
+ if (isRasterImageRead) {
828
+ imageReadCount += 1;
829
+ let imageBytes = 0;
830
+ try {
831
+ const absImgPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
832
+ if (fs.existsSync(absImgPath)) imageBytes = fs.statSync(absImgPath).size;
833
+ } catch (imgErr) {
834
+ void imgErr; // ignore: unreadable image size stat
835
+ }
836
+ if (imageReadCount >= 2 || imageBytes > 1_048_576) {
837
+ advisoryNotice = appendAdvisory(advisoryNotice, {
838
+ detectorId: 'DET-18',
839
+ triggered: true,
840
+ decision: 'allow',
841
+ subType: 'VISION_READ_GUARD',
842
+ reason:
843
+ `[Burnoff DET-18 Vision/Screenshot Guard] Image read "${path.basename(rawPath)}" ` +
844
+ `(count=${imageReadCount}, ~${Math.round(imageBytes / 1024)} KB) adds sticky multimodal tokens to every subsequent turn. ` +
845
+ `Paste DOM/computed CSS or error text instead of repeated high-res screenshots.`
846
+ });
847
+ }
848
+ }
849
+
850
+ // DET-19: Post-git-commit thread-rot coach when starting a new module feature
851
+ if (
852
+ isMutationTool &&
853
+ rawPath &&
854
+ !isRulesOrMcpTarget &&
855
+ priorSnap?.lastGitCommitAtMs &&
856
+ priorSnap?.det19WarnedCommitTs !== priorSnap.lastGitCommitAtMs
857
+ ) {
858
+ const targetModDir = extractModuleDir(rawPath, baseCwd);
859
+ const preCommitDirs = Array.isArray(priorSnap.preCommitModuleDirs) ? priorSnap.preCommitModuleDirs : [];
860
+ const movedToNewModule = Boolean(targetModDir) && !preCommitDirs.includes(targetModDir);
861
+ if (movedToNewModule || promptTok >= 80_000) {
862
+ det19WarnedCommitTs = priorSnap.lastGitCommitAtMs;
863
+ advisoryNotice = appendAdvisory(advisoryNotice, {
864
+ detectorId: 'DET-19',
865
+ triggered: true,
866
+ decision: 'allow',
867
+ subType: 'POST_COMMIT_NEW_MODULE',
868
+ reason:
869
+ `[Burnoff DET-19 Thread-Rot Coach] Editing "${targetModDir || path.basename(rawPath)}" after a recent git commit carries stale prior-task context. ` +
870
+ `Consider running /handoff and /clear (or /compact) before a new module feature.`
871
+ });
872
+ }
873
+ }
874
+
875
+ // BO-MOD-01 & DET-17: Trivial edits on Opus high/max effort & blind multi-file edit gate
876
+ const changedLines = isMutationTool ? countChangedLinesForEdit(toolName, tIn) : 0;
877
+ if (isMutationTool && rawPath && !isRulesOrMcpTarget) {
878
+ if (changedLines > 0 && changedLines <= 5) {
879
+ trivialEditStreak += 1;
880
+ } else if (changedLines > 5) {
881
+ trivialEditStreak = 0;
882
+ }
883
+
884
+ if (
885
+ /opus/i.test(modelId) &&
886
+ (!effortTier || /^(?:high|max|xhigh|default)$/i.test(effortTier)) &&
887
+ trivialEditStreak >= 3
888
+ ) {
889
+ const effortCacheSafe = effortChangePreservesCache({ model: modelId, env: options.env });
890
+ const effortGuidance = effortCacheSafe
891
+ ? 'Consider `/effort low` for routine edits (cache stays warm on this model/connection).'
892
+ : 'Changing effort mid-session invalidates the prompt cache on this model/connection; lower effort at your next fresh session or after /compact, or delegate routine edits to a lower-effort subagent.';
893
+ advisoryNotice = appendAdvisory(advisoryNotice, {
894
+ detectorId: 'BO-MOD-01',
895
+ triggered: true,
896
+ decision: 'allow',
897
+ subType: 'TRIVIAL_EDIT_OPUS_MAX_EFFORT',
898
+ reason:
899
+ `[Burnoff BO-MOD-01 Model/Effort Coach] ${trivialEditStreak} consecutive trivial edits (<=5 lines) on ${modelId} (effort=${effortTier || 'default'}). ` +
900
+ effortGuidance
901
+ });
902
+ }
903
+
904
+ const isNewBlindFile = Boolean(normRelTarget) && !priorEditedFiles.includes(normRelTarget);
905
+ const blindEditAction = String(
906
+ options.blindMultiFileEditAction ?? guardsCfg.blindMultiFileEditAction ?? 'ask'
907
+ )
908
+ .trim()
909
+ .toLowerCase();
910
+ if (
911
+ priorEditedFiles.length >= 1 &&
912
+ isNewBlindFile &&
913
+ Number(priorSnap?.discoveryCallsTotal || 0) === 0
914
+ ) {
915
+ if (priorSnap?.unplannedRefactorFlag === true && blindEditAction !== 'allow') {
916
+ const det17Verdict = {
917
+ detectorId: 'DET-17',
918
+ triggered: true,
919
+ decision: blindEditAction === 'deny' ? 'deny' : 'ask',
920
+ subType: 'BLIND_MULTI_FILE_EDIT',
921
+ reason:
922
+ `[Burnoff DET-17 Plan-First Gate] Editing a 2nd distinct file ("${normRelTarget}") after a broad refactor prompt with 0 discovery Reads/Greps. ` +
923
+ `Read affected symbols or draft a short plan before modifying multiple modules.`
924
+ };
925
+ if (det17Verdict.decision === 'deny') {
926
+ return finalize({
927
+ exitCode: 2,
928
+ stdout: '',
929
+ stderr: det17Verdict.reason,
930
+ verdict: det17Verdict
931
+ });
932
+ }
933
+ return evaluateAskWithSnooze(det17Verdict, rawPath).response;
934
+ } else if (priorEditedFiles.length >= 2 && changedLines > 5) {
935
+ advisoryNotice = appendAdvisory(advisoryNotice, {
936
+ detectorId: 'DET-17',
937
+ triggered: true,
938
+ decision: 'allow',
939
+ subType: 'BLIND_MULTI_FILE_EDIT',
940
+ reason:
941
+ `[Burnoff DET-17 Plan-First Coach] Editing multiple distinct files with 0 prior discovery Reads/Greps. ` +
942
+ `Inspect callers/tests first to avoid blind rework.`
943
+ });
944
+ }
945
+ }
946
+ }
947
+
948
+ // BO-MOD-02 & BO-PFX-01: Non-blocking advisory on rules/.mcp.json or .claude/agents/*.md edits OR mid-session prefix integrity
949
+ if (isMutationTool && isRulesOrMcpTarget) {
950
+ advisoryNotice = appendAdvisory(advisoryNotice, {
951
+ detectorId: 'BO-MOD-02',
952
+ triggered: true,
953
+ decision: 'allow',
954
+ subType: 'STATIC_PREFIX_FILE_MUTATION',
955
+ reason:
956
+ `[Burnoff BO-MOD-02 Static Prefix Advisory] Editing "${normRelTarget}" mid-session ` +
957
+ `(takes effect after /clear, /compact, or restart; the current session keeps the version loaded at start).`
958
+ });
959
+ }
960
+ if (isMutationTool && isSubagentDefinitionTarget && isAfterTurnOne) {
961
+ const agentName = path.basename(rawPath, path.extname(rawPath));
962
+ advisoryNotice = appendAdvisory(advisoryNotice, {
963
+ detectorId: 'BO-MOD-02',
964
+ triggered: true,
965
+ decision: 'allow',
966
+ subType: 'SUBAGENT_DEFINITION_EDIT',
967
+ reason:
968
+ `[Burnoff BO-MOD-02 Static Prefix Advisory] Editing agent ${agentName} mid-session changes its system prompt for the next delegation; that spawn starts cold. Batch agent-definition edits between tasks.`
969
+ });
970
+ }
971
+ const telemetryNowMs = options.nowMs ?? Date.now();
972
+ const ttlTier = String(
973
+ event.cacheTtlTier || priorSnap?.cacheTtlTier || policy.guards?.cacheTtlTier || '5m'
974
+ ).toLowerCase();
975
+ const effectiveTtlMs = ttlTier === '1h' ? 60 * 60 * 1000 : 5 * 60 * 1000;
976
+ const prefixEval = evaluatePrefixIntegrity({
977
+ event,
978
+ prior: priorSnap,
979
+ policy,
980
+ cwd: baseCwd,
981
+ homeDir: options.homeDir,
982
+ effectiveTtlMs,
983
+ nowMs: telemetryNowMs,
984
+ explicitModel: explicitEventModel,
985
+ explicitEffort,
986
+ env: options.env
987
+ });
988
+ for (const finding of prefixEval.findings) {
989
+ advisoryNotice = appendAdvisory(advisoryNotice, {
990
+ detectorId: finding.detectorId,
991
+ triggered: true,
992
+ decision: 'allow',
993
+ subType: finding.subType,
994
+ reason: finding.reason
995
+ });
996
+ }
997
+
998
+ // BO-MCP-11: Idle MCP schema bloat runtime counter
999
+ if (isMcpTool) {
1000
+ mcpCallsTotal += 1;
1001
+ nonMcpTurnCount = 0;
1002
+ } else {
1003
+ nonMcpTurnCount += 1;
1004
+ if (
1005
+ shouldPersistState &&
1006
+ mcpCallsTotal === 0 &&
1007
+ nonMcpTurnCount >= 5 &&
1008
+ (lastMcpIdleWarnTurn === 0 || nonMcpTurnCount - lastMcpIdleWarnTurn >= 15)
1009
+ ) {
1010
+ const mcpStats = countConfiguredMcpServers(baseCwd, options.homeDir);
1011
+ if (mcpStats.serverCount >= 5 || mcpStats.estSchemaTokens >= 15_000) {
1012
+ lastMcpIdleWarnTurn = nonMcpTurnCount;
1013
+ advisoryNotice = appendAdvisory(advisoryNotice, {
1014
+ detectorId: 'BO-MCP-11',
1015
+ triggered: true,
1016
+ decision: 'allow',
1017
+ subType: 'IDLE_MCP_SCHEMA_BLOAT',
1018
+ reason:
1019
+ `[Burnoff BO-MCP-11 Idle MCP Schema Bloat] ${mcpStats.serverCount} MCP servers (~${mcpStats.estSchemaTokens.toLocaleString('en-US')} est. tok/turn) ` +
1020
+ `loaded with 0 mcp__* invocations over ${nonMcpTurnCount} turns. Disable unused MCP servers or enable defer_loading.`
1021
+ });
1022
+ }
1023
+ }
1024
+ }
1025
+
1026
+ // Consolidated single atomic state write per PreToolUse evaluation
1027
+ if (shouldPersistState) {
1028
+ try {
1029
+ updateBreakerStateAtomicSync(
1030
+ sessionId,
1031
+ (cur) => {
1032
+ const base = cur && typeof cur === 'object' ? { ...cur } : {};
1033
+ return {
1034
+ ...base,
1035
+ ...prefixEval.nextStatePatch,
1036
+ schemaVersion: '1.0.0',
1037
+ sessionId,
1038
+ discoveryCallsTotal,
1039
+ discoveryCallsSinceLastMutation,
1040
+ mutationCallsTotal,
1041
+ editedFiles,
1042
+ imageReadCount,
1043
+ trivialEditStreak,
1044
+ nonMcpTurnCount,
1045
+ mcpCallsTotal,
1046
+ lastMcpIdleWarnTurn,
1047
+ lastDet15WarnCount,
1048
+ ...(det19WarnedCommitTs !== null ? { det19WarnedCommitTs } : {}),
1049
+ ...(event.cacheTtlTier ? { cacheTtlTier: ttlTier } : {}),
1050
+ ...(explicitEventModel ? { lastModel: explicitEventModel } : {}),
1051
+ ...(explicitEffort ? { lastEffort: explicitEffort } : {}),
1052
+ lastTurnAtMs: telemetryNowMs,
1053
+ updatedAt: telemetryNowMs
1054
+ };
1055
+ },
1056
+ cwdOptions
1057
+ );
1058
+ } catch (telErr) {
1059
+ void telErr; // ignore: non-fatal session telemetry persistence
1060
+ }
1061
+ }
1062
+
1063
+ // 6. Bounded Read Guard & Per-File Read-Interval Cache (`updatedInput`)
600
1064
  const nowSnapMs = options.nowMs ?? Date.now();
601
1065
  const readIntervalTtlMs = Math.max(
602
1066
  1000,
@@ -607,7 +1071,19 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
607
1071
  DEFAULT_READ_INTERVAL_TTL_MS
608
1072
  )
609
1073
  );
610
- const isReadTool = READ_TOOL_REGEX.test(toolName);
1074
+ const readIntervalMaxTurnGap = Math.max(
1075
+ 1,
1076
+ Number(
1077
+ options.readIntervalMaxTurnGap ??
1078
+ policy.readClamp?.intervalMaxTurnGap ??
1079
+ guardsCfg.readIntervalMaxTurnGap ??
1080
+ DEFAULT_READ_INTERVAL_MAX_TURN_GAP
1081
+ ) || DEFAULT_READ_INTERVAL_MAX_TURN_GAP
1082
+ );
1083
+ // `promptCount` advances once per UserPromptSubmit; absent (non-prompt clients) disables the turn gap.
1084
+ const currentReadTurn = Number.isFinite(Number(priorSnap?.promptCount))
1085
+ ? Number(priorSnap.promptCount)
1086
+ : null;
611
1087
  if (isReadTool && rawPath && !/\.(?:ipynb|pdf)$/i.test(rawPath)) {
612
1088
  const rawStartBound = tIn.offset ?? tIn.StartLine ?? tIn.start_line;
613
1089
  const rawEndBound = tIn.EndLine ?? tIn.end_line;
@@ -632,17 +1108,22 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
632
1108
  : null;
633
1109
 
634
1110
  let trimmedByInterval = null;
635
- if (!isSubagent && hasExplicitLineSlice && shouldPersistState && rawCwd) {
1111
+ let fullCoverByInterval = null;
1112
+ if (!softPause?.active && !isSubagent && shouldPersistState && rawCwd) {
636
1113
  try {
637
1114
  const absIntPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
638
1115
  if (fs.existsSync(absIntPath)) {
639
1116
  const stInt = fs.statSync(absIntPath);
640
1117
  if (stInt.isFile() && stInt.size > 0 && stInt.size <= 1024 * 1024) {
641
- const normIntKey = absIntPath.replace(/\\/g, '/').toLowerCase();
1118
+ const normIntKey = normalizePlatformPathKey(absIntPath);
642
1119
  const { store: intStore } = loadReadSnapStore(baseCwd, sessionId, cwdOptions);
643
1120
  const entry = intStore.__readIntervals?.[normIntKey];
644
- const recordedAt = Number(entry?.recordedAt || 0);
645
- const entryFresh = recordedAt > 0 && nowSnapMs - recordedAt <= readIntervalTtlMs;
1121
+ const entryFresh = isReadIntervalEntryFresh(entry, {
1122
+ nowMs: nowSnapMs,
1123
+ ttlMs: readIntervalTtlMs,
1124
+ currentTurn: currentReadTurn,
1125
+ maxTurnGap: readIntervalMaxTurnGap
1126
+ });
646
1127
  const entryValid =
647
1128
  entry &&
648
1129
  entryFresh &&
@@ -655,11 +1136,30 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
655
1136
  const totalFileLines =
656
1137
  rawIntSrc.length === 0 ? 0 : rawIntSrc.replace(/\r\n/g, '\n').split('\n').length;
657
1138
  const reqStart = effectiveSliceOffset || 1;
658
- const reqEnd = effectiveSliceLimit
659
- ? Math.min(totalFileLines, reqStart + effectiveSliceLimit - 1)
660
- : totalFileLines;
661
- const trimRes = trimRequestedRangeAgainstIntervals(reqStart, reqEnd, entry.intervals);
662
- if (trimRes.status === 'trimmed') {
1139
+ const reqEnd =
1140
+ hasExplicitLineSlice && effectiveSliceLimit
1141
+ ? Math.min(totalFileLines, reqStart + effectiveSliceLimit - 1)
1142
+ : hasExplicitLineSlice && rawEndBound !== undefined
1143
+ ? Math.min(totalFileLines, Math.max(reqStart, Math.floor(Number(rawEndBound))))
1144
+ : totalFileLines;
1145
+ const trimRes = trimRequestedRangeAgainstIntervals(reqStart, reqEnd, entry.intervals, {
1146
+ detectFullCover: true
1147
+ });
1148
+ if (trimRes.status === 'fully_covered') {
1149
+ const avgBytesPerLine = totalFileLines > 0 ? stInt.size / totalFileLines : 40;
1150
+ const savedTok = Math.max(
1151
+ 10,
1152
+ Math.round(((trimRes.savedLines - (trimRes.anchorLimit || 0)) * avgBytesPerLine) / 4)
1153
+ );
1154
+ fullCoverByInterval = {
1155
+ reqStart,
1156
+ reqEnd,
1157
+ offset: trimRes.anchorOffset || reqStart,
1158
+ limit: trimRes.anchorLimit || Math.min(15, Math.max(1, totalFileLines - reqStart + 1)),
1159
+ savedTokens: savedTok,
1160
+ absPath: absIntPath
1161
+ };
1162
+ } else if (hasExplicitLineSlice && trimRes.status === 'trimmed') {
663
1163
  const avgBytesPerLine = totalFileLines > 0 ? stInt.size / totalFileLines : 40;
664
1164
  const savedTok = Math.max(10, Math.round((trimRes.savedLines * avgBytesPerLine) / 4));
665
1165
  effectiveSliceOffset = trimRes.offset;
@@ -683,11 +1183,58 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
683
1183
  }
684
1184
  }
685
1185
 
686
- const eventUsage = event.usage || event.context_window?.current_usage || null;
687
- const promptTok = Math.max(
688
- computeTotalPromptTokens(event),
689
- eventUsage ? computeTotalPromptTokens(eventUsage) : 0
690
- );
1186
+ if (fullCoverByInterval) {
1187
+ if (canRecordLedger) {
1188
+ recordInterventionSavings(
1189
+ {
1190
+ sessionId,
1191
+ category: 'BOUNDED_READ_ENFORCED',
1192
+ modelId,
1193
+ savedTokens: fullCoverByInterval.savedTokens,
1194
+ dedupeId:
1195
+ canonical.toolUseId ||
1196
+ `reread_dedup:${sessionId}:${path.basename(fullCoverByInterval.absPath)}:${fullCoverByInterval.reqStart}:${fullCoverByInterval.reqEnd}`,
1197
+ detail: `Deduped unchanged re-read of ${path.basename(fullCoverByInterval.absPath)} L${fullCoverByInterval.reqStart}-L${fullCoverByInterval.reqEnd}`
1198
+ },
1199
+ cwdOptions
1200
+ );
1201
+ }
1202
+ const updatedInput = { ...tIn };
1203
+ delete updatedInput.StartLine;
1204
+ delete updatedInput.EndLine;
1205
+ updatedInput.offset = fullCoverByInterval.offset;
1206
+ updatedInput.limit = fullCoverByInterval.limit;
1207
+ const baseRereadReason =
1208
+ `[Burnoff DET-06 Unchanged Re-Read Dedup] L${fullCoverByInterval.reqStart}..L${fullCoverByInterval.reqEnd} of ` +
1209
+ `${path.basename(fullCoverByInterval.absPath)} is already loaded unchanged (same mtime/size); ` +
1210
+ `clamped to ${fullCoverByInterval.limit}-line anchor L${fullCoverByInterval.offset}..L${fullCoverByInterval.offset + fullCoverByInterval.limit - 1}.`;
1211
+ const mergedRereadContext = advisoryNotice
1212
+ ? `${baseRereadReason}\n${advisoryNotice.additionalContext || advisoryNotice.reason}`
1213
+ : baseRereadReason;
1214
+ const allowOut = {
1215
+ hookSpecificOutput: {
1216
+ hookEventName: 'PreToolUse',
1217
+ permissionDecision: 'allow',
1218
+ updatedInput,
1219
+ additionalContext: mergedRereadContext
1220
+ }
1221
+ };
1222
+ return finalize({
1223
+ exitCode: 0,
1224
+ stdout: JSON.stringify(allowOut),
1225
+ stderr: '',
1226
+ verdict: {
1227
+ triggered: true,
1228
+ detectorId: 'DET-06',
1229
+ subType: 'UNCHANGED_REREAD_DEDUP',
1230
+ decision: 'allow',
1231
+ updatedInput,
1232
+ savedTokens: fullCoverByInterval.savedTokens,
1233
+ reason: mergedRereadContext,
1234
+ additionalContext: mergedRereadContext
1235
+ }
1236
+ });
1237
+ }
691
1238
 
692
1239
  const shieldVerdict = evaluateShieldReadGuard({
693
1240
  sessionId,
@@ -701,12 +1248,13 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
701
1248
  modelId,
702
1249
  policy,
703
1250
  shieldConfig: options.shieldConfig,
1251
+ sightseeingMode,
704
1252
  forceActive: Boolean(options.shieldForceActive),
705
1253
  recordLedger: canRecordLedger,
706
1254
  ledgerPath: options.ledgerPath
707
1255
  });
708
1256
 
709
- if (shieldVerdict.action === 'clamp') {
1257
+ if (!softPause?.active && shieldVerdict.action === 'clamp') {
710
1258
  if (!isSubagent && shouldPersistState && rawCwd && !shieldVerdict.hugeFileFastClamp) {
711
1259
  try {
712
1260
  const absClampPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
@@ -720,11 +1268,12 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
720
1268
  (store) => {
721
1269
  recordReadIntervalEntry(
722
1270
  store,
723
- absClampPath.replace(/\\/g, '/').toLowerCase(),
1271
+ normalizePlatformPathKey(absClampPath),
724
1272
  stClamp,
725
1273
  clampStart,
726
1274
  clampEnd,
727
- nowSnapMs
1275
+ nowSnapMs,
1276
+ currentReadTurn
728
1277
  );
729
1278
  return store;
730
1279
  },
@@ -741,12 +1290,15 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
741
1290
  delete updatedInput.EndLine;
742
1291
  updatedInput.offset = shieldVerdict.clampOffset || 1;
743
1292
  updatedInput.limit = shieldVerdict.clampLimit;
1293
+ const mergedClampContext = advisoryNotice
1294
+ ? `${shieldVerdict.reason}\n${advisoryNotice.additionalContext || advisoryNotice.reason}`
1295
+ : shieldVerdict.reason;
744
1296
  const clampOut = {
745
1297
  hookSpecificOutput: {
746
1298
  hookEventName: 'PreToolUse',
747
1299
  permissionDecision: 'allow',
748
1300
  updatedInput,
749
- additionalContext: shieldVerdict.reason
1301
+ additionalContext: mergedClampContext
750
1302
  }
751
1303
  };
752
1304
  return finalize({
@@ -762,7 +1314,8 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
762
1314
  clampOffset: updatedInput.offset,
763
1315
  clampLimit: updatedInput.limit,
764
1316
  hugeFileFastClamp: Boolean(shieldVerdict.hugeFileFastClamp),
765
- reason: shieldVerdict.reason,
1317
+ reason: mergedClampContext,
1318
+ additionalContext: mergedClampContext,
766
1319
  fileBytes: shieldVerdict.fileBytes,
767
1320
  maxBytes: shieldVerdict.maxBytes,
768
1321
  clampedBytes: shieldVerdict.clampedBytes,
@@ -774,11 +1327,14 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
774
1327
  }
775
1328
 
776
1329
  if (shieldVerdict.action === 'deny') {
1330
+ const mergedDenyReason = advisoryNotice
1331
+ ? `${shieldVerdict.reason}\n${advisoryNotice.additionalContext || advisoryNotice.reason}`
1332
+ : shieldVerdict.reason;
777
1333
  const denyOut = {
778
1334
  hookSpecificOutput: {
779
1335
  hookEventName: 'PreToolUse',
780
1336
  permissionDecision: 'deny',
781
- permissionDecisionReason: shieldVerdict.reason
1337
+ permissionDecisionReason: mergedDenyReason
782
1338
  }
783
1339
  };
784
1340
  return finalize({
@@ -790,7 +1346,7 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
790
1346
  detectorId: shieldVerdict.detectorId,
791
1347
  triggerReason: shieldVerdict.triggerReason,
792
1348
  decision: 'deny',
793
- reason: shieldVerdict.reason,
1349
+ reason: mergedDenyReason,
794
1350
  fileBytes: shieldVerdict.fileBytes,
795
1351
  maxBytes: shieldVerdict.maxBytes,
796
1352
  savedTokens: shieldVerdict.savedTokens,
@@ -810,7 +1366,8 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
810
1366
  trimmedByInterval.statObj,
811
1367
  trimmedByInterval.offset,
812
1368
  trimmedByInterval.offset + trimmedByInterval.limit - 1,
813
- nowSnapMs
1369
+ nowSnapMs,
1370
+ currentReadTurn
814
1371
  );
815
1372
  return store;
816
1373
  },
@@ -839,12 +1396,15 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
839
1396
  const trimReason =
840
1397
  `[Burnoff Read-Interval Trim] L${trimmedByInterval.reqStart}..L${trimmedByInterval.reqEnd} overlapped already-loaded lines ` +
841
1398
  `of ${path.basename(trimmedByInterval.absPath)}; trimmed to unread L${trimmedByInterval.offset}..L${trimmedByInterval.offset + trimmedByInterval.limit - 1}.`;
1399
+ const mergedTrimContext = advisoryNotice
1400
+ ? `${trimReason}\n${advisoryNotice.additionalContext || advisoryNotice.reason}`
1401
+ : trimReason;
842
1402
  const allowOut = {
843
1403
  hookSpecificOutput: {
844
1404
  hookEventName: 'PreToolUse',
845
1405
  permissionDecision: 'allow',
846
1406
  updatedInput,
847
- additionalContext: trimReason
1407
+ additionalContext: mergedTrimContext
848
1408
  }
849
1409
  };
850
1410
  return finalize({
@@ -858,7 +1418,8 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
858
1418
  decision: 'allow',
859
1419
  updatedInput,
860
1420
  savedTokens: trimmedByInterval.savedTokens,
861
- reason: trimReason
1421
+ reason: mergedTrimContext,
1422
+ additionalContext: mergedTrimContext
862
1423
  }
863
1424
  });
864
1425
  }
@@ -883,11 +1444,12 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
883
1444
  (store) => {
884
1445
  recordReadIntervalEntry(
885
1446
  store,
886
- absRecPath.replace(/\\/g, '/').toLowerCase(),
1447
+ normalizePlatformPathKey(absRecPath),
887
1448
  stRec,
888
1449
  recStart,
889
1450
  recEnd,
890
- nowSnapMs
1451
+ nowSnapMs,
1452
+ currentReadTurn
891
1453
  );
892
1454
  return store;
893
1455
  },