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
@@ -0,0 +1,309 @@
1
+ /**
2
+ * @file src/guards/prompt-guard.mjs
3
+ * `UserPromptSubmit` guard engine:
4
+ * - `DET-04`: Frustration / repeated-failure prompt cue coaching
5
+ * - `DET-13`: LLM-as-linter/formatter detection (>=25 pasted code lines + format-only intent)
6
+ * - `DET-14`: Conversational drip-feeding (>=4 micro-prompts <=15 words within 120s)
7
+ * - `DET-17`: Vague architectural / refactor prompt gate (plan-first coaching)
8
+ * - `BO-TTL-01`: Cold-cache resume warning when idle exceeds 5m / 1h cache TTL
9
+ * - `BO-MOD-02`: Mid-session model or effort switch prefix-invalidation warning
10
+ */
11
+
12
+ import path from 'node:path';
13
+ import { loadBurnoffPolicy } from '../config/policy.mjs';
14
+ import { readBreakerStateSnapshot, updateBreakerStateAtomicSync } from './loop-breaker.mjs';
15
+ import { evaluatePrefixIntegrity } from './prefix-guard.mjs';
16
+ import { resolveEffortLevel } from '../config/effort.mjs';
17
+ import { consumeCompactionBatonSync } from './compaction-baton.mjs';
18
+
19
+ const DEFAULT_CACHE_TTL_5M_MS = 5 * 60 * 1000;
20
+ const DEFAULT_CACHE_TTL_1H_MS = 60 * 60 * 1000;
21
+ const DRIP_FEED_WINDOW_MS = 120 * 1000;
22
+ const DRIP_FEED_MAX_WORDS = 15;
23
+ const DRIP_FEED_MIN_PROMPTS = 4;
24
+
25
+ const FORMAT_ONLY_INTENT_RE =
26
+ /\b(?:fix\s+(?:the\s+)?indent(?:ation)?|reindent|sort\s+(?:the\s+)?imports?|organize\s+imports?|format\s+(?:this|the\s+code|the\s+file|code|file)|run\s+prettier|prettier|eslint|ruff\s+format|gofmt|rustfmt|tabs?\s+to\s+spaces?|spaces?\s+to\s+tabs?|fix\s+whitespace|clean\s+up\s+formatting|lint\s+(?:this|the\s+code|the\s+file))\b/i;
27
+ const FEATURE_OR_BUG_INTENT_RE =
28
+ /\b(?:fix\s+(?:the\s+)?bug|implement|add\s+(?:a\s+)?feature|security\s+vuln|race\s+condition|memory\s+leak|failing\s+test|stack\s+trace|exception)\b/i;
29
+
30
+ const VAGUE_REFACTOR_INTENT_RE =
31
+ /\b(?:refactor|rewrite|overhaul|redesign|rearchitect|re-architect|modernize|restructure|migrate)\b/i;
32
+ const RETRY_FRUSTRATION_RE =
33
+ /\b(?:still\s+(?:broken|failing|errors?)|same\s+error|try\s+again|didn'?t\s+work|not\s+working|why\s+is\s+this\s+(?:still\s+)?failing)\b/i;
34
+
35
+ function countCodeLinesInPrompt(promptText = '') {
36
+ const text = String(promptText || '');
37
+ const fencedMatches = [...text.matchAll(/```[^\n]*\n([\s\S]*?)```/g)];
38
+ let fencedLines = 0;
39
+ for (const m of fencedMatches) {
40
+ const block = String(m[1] || '').trim();
41
+ if (block) fencedLines += block.split(/\r?\n/).length;
42
+ }
43
+ const allLines = text.split(/\r?\n/);
44
+ let codeLikeLines = 0;
45
+ for (const line of allLines) {
46
+ const trimmed = line.trim();
47
+ if (!trimmed) continue;
48
+ if (
49
+ /^(?:import|export|const|let|var|function|async\s+function|class|interface|type|def|async\s+def|func|pub\s+fn|return)\b/.test(
50
+ trimmed
51
+ ) ||
52
+ /[{};]$/.test(trimmed) ||
53
+ /^\s{2,}\S+/.test(line)
54
+ ) {
55
+ codeLikeLines += 1;
56
+ }
57
+ }
58
+ return {
59
+ totalLines: allLines.length,
60
+ fencedLines,
61
+ codeLikeLines,
62
+ effectiveCodeLines: Math.max(fencedLines, codeLikeLines)
63
+ };
64
+ }
65
+
66
+ function stripFencedBlocks(promptText = '') {
67
+ return String(promptText || '').replace(/```[\s\S]*?```/g, ' ').trim();
68
+ }
69
+
70
+ function countInstructionWords(promptText = '') {
71
+ const plain = stripFencedBlocks(promptText);
72
+ if (!plain) return 0;
73
+ return plain.split(/\s+/).filter(Boolean).length;
74
+ }
75
+
76
+ function hasExplicitScopeOrPlan(promptText = '') {
77
+ const plain = stripFencedBlocks(promptText);
78
+ if (/(?:^|\s)(?:[\w.-]+\/)+[\w.-]+/.test(plain)) return true;
79
+ if (/\b[\w-]+\.(?:mjs|cjs|js|jsx|ts|tsx|py|go|rs|java|rb|json|md|yml|yaml)\b/i.test(plain)) {
80
+ return true;
81
+ }
82
+ if (/^\s*(?:\d+\.|[-*]\s+)\S+/m.test(plain)) return true;
83
+ return false;
84
+ }
85
+
86
+ function normalizeModelValue(event = {}) {
87
+ if (typeof event.model === 'string') return event.model.trim();
88
+ if (event.model && typeof event.model === 'object') {
89
+ return String(event.model.id || event.model.name || '').trim();
90
+ }
91
+ return '';
92
+ }
93
+
94
+ /**
95
+ * Evaluates a `UserPromptSubmit` hook payload synchronously and persists prompt-level session telemetry.
96
+ */
97
+ export function evaluateUserPromptSubmit(event = {}, options = {}) {
98
+ const promptText = String(event.prompt || event.user_prompt || event.message || event.text || '');
99
+ const sessionId = String(event.session_id || event.sessionId || event.conversationId || 'default');
100
+ const rawCwd = String(event.cwd || options.cwd || '').trim();
101
+ const baseCwd = rawCwd ? path.resolve(rawCwd) : process.cwd();
102
+ const client = options.client || 'claude-code';
103
+ const cwdOptions = { ...(rawCwd ? { ...options, cwd: baseCwd } : options), client };
104
+
105
+ const policy = options.policy || loadBurnoffPolicy(baseCwd);
106
+ const guardsCfg = policy.guards || {};
107
+ const shouldPersistState =
108
+ options.persistState !== false &&
109
+ Boolean(rawCwd || options.breakerStatePath || options.persistState);
110
+
111
+ const rawNow = event.timestamp ?? options.nowMs;
112
+ const nowMs = Number.isFinite(Number(rawNow)) ? Number(rawNow) : Date.now();
113
+ const prior = shouldPersistState ? readBreakerStateSnapshot(sessionId, cwdOptions) : null;
114
+
115
+ const warnings = [];
116
+ const detectorIds = [];
117
+ const addFinding = (id, msg) => {
118
+ if (!detectorIds.includes(id)) detectorIds.push(id);
119
+ warnings.push(msg);
120
+ };
121
+
122
+ // 0. BO-CMP-01: One-shot compaction baton fallback if SessionStart(compact) was skipped
123
+ if (shouldPersistState && guardsCfg.compactionBatonEnabled !== false) {
124
+ const pendingBaton = consumeCompactionBatonSync(baseCwd, sessionId, { ...cwdOptions, nowMs });
125
+ if (pendingBaton?.context) {
126
+ addFinding('BO-CMP-01', pendingBaton.context);
127
+ }
128
+ }
129
+
130
+ // 1. DET-13: LLM as linter / formatter (opt-in via mode: coach or promptCoachEnabled/det13Enabled)
131
+ const coachActive =
132
+ String(guardsCfg.mode || '').toLowerCase() === 'coach' || guardsCfg.promptCoachEnabled === true;
133
+ const det13Active = guardsCfg.det13Enabled ?? coachActive;
134
+ const det14Active = guardsCfg.det14Enabled ?? coachActive;
135
+ const det17Active = guardsCfg.det17Enabled ?? coachActive;
136
+
137
+ if (det13Active && promptText) {
138
+ const codeStats = countCodeLinesInPrompt(promptText);
139
+ if (
140
+ FORMAT_ONLY_INTENT_RE.test(promptText) &&
141
+ !FEATURE_OR_BUG_INTENT_RE.test(promptText) &&
142
+ codeStats.effectiveCodeLines >= 25
143
+ ) {
144
+ addFinding(
145
+ 'DET-13',
146
+ `[Burnoff DET-13 Local Formatter Coach] Prompt includes ~${codeStats.effectiveCodeLines} lines of pasted code for formatting/import-sorting. Run deterministic formatters locally (\`npx prettier --write\`, \`npx eslint --fix\`, \`ruff format\`, or \`gofmt\`) instead of paying LLM input+output tokens.`
147
+ );
148
+ }
149
+ }
150
+
151
+ // 2. DET-14: Conversational drip-feeding
152
+ const instructionWords = countInstructionWords(promptText);
153
+ const prevRecentPrompts = Array.isArray(prior?.recentPrompts) ? prior.recentPrompts : [];
154
+ const nextRecentPrompts = [
155
+ ...prevRecentPrompts.filter(
156
+ (entry) => entry && Number.isFinite(Number(entry.ts)) && nowMs - Number(entry.ts) <= DRIP_FEED_WINDOW_MS
157
+ ),
158
+ ...(promptText.trim() ? [{ ts: nowMs, wordCount: instructionWords }] : [])
159
+ ].slice(-12);
160
+
161
+ const recentShortPrompts = nextRecentPrompts.filter(
162
+ (entry) => Number(entry.wordCount) > 0 && Number(entry.wordCount) <= DRIP_FEED_MAX_WORDS
163
+ );
164
+ const dripFeedActive = recentShortPrompts.length >= DRIP_FEED_MIN_PROMPTS;
165
+ if (det14Active && dripFeedActive) {
166
+ addFinding(
167
+ 'DET-14',
168
+ `[Burnoff DET-14 Micro-Prompt Batching Coach] Detected ${recentShortPrompts.length} micro-prompts (<=${DRIP_FEED_MAX_WORDS} words) within 120s. Each incremental follow-up replays the full thread prefix; batch related UI/code changes into one numbered specification.`
169
+ );
170
+ }
171
+
172
+ // 3. DET-17: Vague architectural / refactor prompt gate
173
+ let unplannedRefactorFlag = Boolean(prior?.unplannedRefactorFlag);
174
+ if (
175
+ det17Active &&
176
+ promptText &&
177
+ instructionWords > 0 &&
178
+ instructionWords <= 20 &&
179
+ VAGUE_REFACTOR_INTENT_RE.test(promptText) &&
180
+ !hasExplicitScopeOrPlan(promptText)
181
+ ) {
182
+ unplannedRefactorFlag = true;
183
+ const preview = promptText.trim().replace(/\s+/g, ' ').slice(0, 80);
184
+ addFinding(
185
+ 'DET-17',
186
+ `[Burnoff DET-17 Plan-First Coach] Broad architectural prompt ("${preview}") lacks target file paths or verification criteria. Inspect affected modules, list acceptance tests, or use /plan before editing multiple files.`
187
+ );
188
+ }
189
+
190
+ // 4. BO-TTL-01: Cold-cache resume check
191
+ const ttlTier = String(
192
+ event.cacheTtlTier || prior?.cacheTtlTier || policy.guards?.cacheTtlTier || '5m'
193
+ ).toLowerCase();
194
+ const effectiveTtlMs = ttlTier === '1h' ? DEFAULT_CACHE_TTL_1H_MS : DEFAULT_CACHE_TTL_5M_MS;
195
+ const explicitIdleMs = Number(event.idle_ms ?? event.idleMs);
196
+ const elapsedMs = Number.isFinite(explicitIdleMs)
197
+ ? explicitIdleMs
198
+ : prior?.lastTurnAtMs
199
+ ? Math.max(0, nowMs - Number(prior.lastTurnAtMs))
200
+ : 0;
201
+ let ttlWarningShownAtTurn = false;
202
+ if (elapsedMs > effectiveTtlMs) {
203
+ ttlWarningShownAtTurn = true;
204
+ addFinding(
205
+ 'BO-TTL-01',
206
+ `[Burnoff BO-TTL-01 Cold-Cache Resume Warning] Idle gap (${Math.round(elapsedMs / 1000)}s) exceeded the ${ttlTier} prompt-cache TTL. Cached prefix tokens have expired and will rebuild on this turn; consider /compact or starting a clean task.`
207
+ );
208
+ }
209
+
210
+ // 5. BO-MOD-02 & BO-PFX-01: Runtime prefix integrity (MCP/toolset, model/effort ping-pong, history slicing)
211
+ const incomingModel = normalizeModelValue(event);
212
+ const incomingEffort = resolveEffortLevel(event, { env: options.env });
213
+ const prefixEval = evaluatePrefixIntegrity({
214
+ event,
215
+ prior,
216
+ policy,
217
+ cwd: baseCwd,
218
+ homeDir: options.homeDir,
219
+ effectiveTtlMs,
220
+ nowMs,
221
+ explicitModel: incomingModel,
222
+ explicitEffort: incomingEffort,
223
+ env: options.env
224
+ });
225
+ for (const finding of prefixEval.findings) {
226
+ addFinding(finding.detectorId, finding.reason);
227
+ }
228
+
229
+ // 6. DET-04: Prompt-level retry frustration detection
230
+ const consecutiveFailures = Math.max(0, Number(prior?.consecutiveFailures || 0));
231
+ if (consecutiveFailures >= 2 && RETRY_FRUSTRATION_RE.test(promptText)) {
232
+ addFinding(
233
+ 'DET-04',
234
+ `[Burnoff DET-04 Retry Loop Coach] Previous action failed ${consecutiveFailures} consecutive times (${prior?.lastFailedToolKey || 'recent tool'}). Inspect the failing line/stack trace before retrying.`
235
+ );
236
+ }
237
+
238
+ if (shouldPersistState && guardsCfg.promptGuardPersist !== false) {
239
+ try {
240
+ updateBreakerStateAtomicSync(
241
+ sessionId,
242
+ (cur) => {
243
+ const base = cur && typeof cur === 'object' ? { ...cur } : {};
244
+ return {
245
+ schemaVersion: '1.0.0',
246
+ ...base,
247
+ ...prefixEval.nextStatePatch,
248
+ sessionId,
249
+ recentPrompts: nextRecentPrompts,
250
+ dripFeedActive,
251
+ unplannedRefactorFlag,
252
+ lastTurnAtMs: nowMs,
253
+ ...(event.cacheTtlTier ? { cacheTtlTier: ttlTier } : {}),
254
+ ...(ttlWarningShownAtTurn ? { lastTtlWarnedAtMs: nowMs } : {}),
255
+ ...(incomingModel ? { lastModel: incomingModel } : {}),
256
+ ...(incomingEffort ? { lastEffort: incomingEffort } : {}),
257
+ promptCount: Math.max(0, Number(base.promptCount || 0)) + 1,
258
+ updatedAt: nowMs
259
+ };
260
+ },
261
+ cwdOptions
262
+ );
263
+ } catch (err) {
264
+ void err; // ignore: non-fatal prompt guard state write
265
+ }
266
+ }
267
+
268
+ if (warnings.length === 0) {
269
+ return {
270
+ exitCode: 0,
271
+ stdout: '',
272
+ stderr: '',
273
+ detectorIds: [],
274
+ verdict: { triggered: false, decision: 'allow', detectorIds: [], reason: null }
275
+ };
276
+ }
277
+
278
+ const combined = warnings.join('\n');
279
+ const stdoutObj = {
280
+ hookSpecificOutput: {
281
+ hookEventName: 'UserPromptSubmit',
282
+ additionalContext: combined
283
+ },
284
+ systemMessage: combined
285
+ };
286
+ return {
287
+ exitCode: 0,
288
+ stdout: JSON.stringify(stdoutObj),
289
+ stderr: '',
290
+ detectorIds,
291
+ verdict: {
292
+ triggered: true,
293
+ detectorId: detectorIds[0],
294
+ detectorIds,
295
+ decision: 'allow',
296
+ reason: combined,
297
+ additionalContext: combined
298
+ }
299
+ };
300
+ }
301
+
302
+ export function runUserPromptSubmitHook(event = {}, options = {}) {
303
+ return evaluateUserPromptSubmit(event, options);
304
+ }
305
+
306
+ export default {
307
+ evaluateUserPromptSubmit,
308
+ runUserPromptSubmitHook
309
+ };
@@ -35,11 +35,46 @@ export const MEASURED_REREAD_P_DOC = 0.15;
35
35
  export const MEASURED_SOLO_TURN_P_GIVEN_REREAD = 0.19;
36
36
  export const ASSUMED_MIN_PROMPT_TOKENS = 20_000;
37
37
  export const DEFAULT_READ_INTERVAL_TTL_MS = 30 * 60 * 1000;
38
+ /** Identical-read dedup coaching expires after this many `UserPromptSubmit` turns (or the age TTL, whichever is first). */
39
+ export const DEFAULT_READ_INTERVAL_MAX_TURN_GAP = 15;
40
+
41
+ /**
42
+ * True when a recorded read-interval entry is still fresh enough to justify unchanged-re-read
43
+ * dedup coaching: younger than `ttlMs` and, when both turn counters are known, within `maxTurnGap`
44
+ * turns. Long sessions therefore stop nagging about legitimately forgotten files.
45
+ */
46
+ export function isReadIntervalEntryFresh(
47
+ entry,
48
+ {
49
+ nowMs = Date.now(),
50
+ ttlMs = DEFAULT_READ_INTERVAL_TTL_MS,
51
+ currentTurn = null,
52
+ maxTurnGap = DEFAULT_READ_INTERVAL_MAX_TURN_GAP
53
+ } = {}
54
+ ) {
55
+ const recordedAt = Number(entry?.recordedAt || 0);
56
+ if (!(recordedAt > 0) || nowMs - recordedAt > ttlMs) return false;
57
+ const recordedTurn = entry?.recordedTurn;
58
+ if (
59
+ recordedTurn !== undefined &&
60
+ recordedTurn !== null &&
61
+ Number.isFinite(Number(recordedTurn)) &&
62
+ currentTurn !== null &&
63
+ currentTurn !== undefined &&
64
+ Number.isFinite(Number(currentTurn)) &&
65
+ Number(currentTurn) - Number(recordedTurn) > maxTurnGap
66
+ ) {
67
+ return false;
68
+ }
69
+ return true;
70
+ }
38
71
 
39
72
  const BURNOFF_CACHE_ARTIFACT_PATH_RE =
40
73
  /(?:^|\/)(?:\.claude\/cache\/artifacts|\.burnoff\/cache)(?:\/|$)/i;
41
74
  const GENERATED_OR_MINIFIED_CODE_RE =
42
75
  /(?:\.min|\.bundle|\.chunk)\.(?:m?js|cjs|css)$|(?:^|\/)(?:node_modules|dist|build|vendor|\.next|coverage)(?:\/|$)/i;
76
+ const LOCKFILE_BASENAME_RE =
77
+ /^(?:package-lock\.json|npm-shrinkwrap\.json|pnpm-lock\.yaml|yarn\.lock|Cargo\.lock|poetry\.lock|Pipfile\.lock|composer\.lock|Gemfile\.lock|go\.sum|bun\.lock|bun\.lockb)$/i;
43
78
  const ACTIVE_SOURCE_CODE_EXT_RE =
44
79
  /\.(?: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
80
  export const STRUCTURED_DATA_EXT_RE = /\.(?:json|yaml|yml|toml|xml|csv)$/i;
@@ -49,11 +84,25 @@ export function isBurnoffArtifactPath(filePath = '') {
49
84
  return BURNOFF_CACHE_ARTIFACT_PATH_RE.test(norm);
50
85
  }
51
86
 
87
+ export function isLockfilePath(filePath = '') {
88
+ const norm = String(filePath || '').replace(/\\/g, '/').trim();
89
+ if (!norm) return false;
90
+ return LOCKFILE_BASENAME_RE.test(path.posix.basename(norm));
91
+ }
92
+
52
93
  export function isGeneratedOrMinifiedCodePath(filePath = '') {
53
94
  const norm = String(filePath || '').replace(/\\/g, '/').trim();
54
95
  return GENERATED_OR_MINIFIED_CODE_RE.test(norm);
55
96
  }
56
97
 
98
+ export function isMinifiedBundleArtifact(filePath = '', rawLines = [], targetBytes = 0) {
99
+ if (isGeneratedOrMinifiedCodePath(filePath)) return true;
100
+ if (targetBytes > 16_384 && Array.isArray(rawLines) && rawLines.length > 0) {
101
+ return targetBytes / rawLines.length > 1_000;
102
+ }
103
+ return false;
104
+ }
105
+
57
106
  export function isActiveSourceCodePath(filePath = '') {
58
107
  const raw = String(filePath || '').trim();
59
108
  if (!raw || isGeneratedOrMinifiedCodePath(raw)) return false;
@@ -202,6 +251,7 @@ export function evaluateShieldReadGuard({
202
251
  policy: providedPolicy = null,
203
252
  shieldConfig = null,
204
253
  forceActive = false,
254
+ sightseeingMode = false,
205
255
  recordLedger = true,
206
256
  ledgerPath
207
257
  } = {}) {
@@ -348,7 +398,7 @@ export function evaluateShieldReadGuard({
348
398
  : 0;
349
399
  const clampEnd = reqOffset + clampLimit - 1;
350
400
  const hugeReason =
351
- `[Burnoff Read Clamp] Fast-clamped huge file ${displayFile} (${(stat.size / (1024 * 1024)).toFixed(1)} MB; ~${totalLinesEstimate.toLocaleString('en-US')} est. lines) ` +
401
+ `[Burnoff DET-06 Read Clamp] Fast-clamped huge file ${displayFile} (${(stat.size / (1024 * 1024)).toFixed(1)} MB; ~${totalLinesEstimate.toLocaleString('en-US')} est. lines) ` +
352
402
  `to L${reqOffset}..L${clampEnd} (~${(clampedBytes / 1024).toFixed(1)} KB). Pass bounded offset & limit to inspect other ranges.`;
353
403
 
354
404
  if (recordLedger) {
@@ -376,7 +426,8 @@ export function evaluateShieldReadGuard({
376
426
 
377
427
  return {
378
428
  action: 'clamp',
379
- detectorId: nearCliff ? 'DET-12' : 'DET-11',
429
+ detectorId: 'DET-06',
430
+ subCode: nearCliff ? 'DET-12' : 'DET-11',
380
431
  triggerReason: 'huge_file_oom_head_probe',
381
432
  reason: hugeReason,
382
433
  clampOffset: reqOffset,
@@ -421,6 +472,115 @@ export function evaluateShieldReadGuard({
421
472
  return { action: 'allow' };
422
473
  }
423
474
 
475
+ const avgBytesPerTargetLine = targetLineCount > 0 ? targetBytes / targetLineCount : targetBytes;
476
+ if (
477
+ isMinifiedBundleArtifact(absFile, targetSliceLines, targetBytes) &&
478
+ (targetLineCount < 40 || avgBytesPerTargetLine > 1_000)
479
+ ) {
480
+ const displayFile =
481
+ !relFile.startsWith('..') && !path.isAbsolute(relFile) ? relFile : path.basename(absFile);
482
+ const savedTokens = Math.max(0, Math.ceil(targetBytes / 4));
483
+ const rates = recordLedger
484
+ ? (baseRates || resolveEffectiveRates(modelId, promptTok, { cwd: baseCwd, homeDir }))
485
+ : null;
486
+ const savedUSD = rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
487
+ ? Number(((savedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
488
+ : 0;
489
+ if (recordLedger) {
490
+ const bundleHash = crypto
491
+ .createHash('sha256')
492
+ .update(`bundle:${absFile}:${stat.mtimeMs}`)
493
+ .digest('hex')
494
+ .slice(0, 16);
495
+ recordInterventionSavings(
496
+ {
497
+ sessionId,
498
+ cwd: baseCwd,
499
+ category: 'BOUNDED_READ_ENFORCED',
500
+ modelId,
501
+ savedTokens,
502
+ rawClampedTokens: savedTokens,
503
+ savedUSD,
504
+ dedupeId: `bundle_deny:${bundleHash}`,
505
+ detail: `Blocked minified/bundled artifact read of ${displayFile}`
506
+ },
507
+ { cwd: baseCwd, skipFsync: true, ...(homeDir ? { homeDir } : {}), ...(ledgerPath ? { ledgerPath } : {}) }
508
+ );
509
+ }
510
+ return {
511
+ action: 'deny',
512
+ detectorId: 'DET-06',
513
+ subCode: 'GENERATED_BUNDLE',
514
+ triggerReason: 'minified_bundle_artifact',
515
+ reason:
516
+ `[Burnoff DET-06 Artifact Firewall] Blocked read of minified/bundled artifact ${displayFile} ` +
517
+ `(${(targetBytes / 1024).toFixed(1)} KB across ${targetLineCount} lines). ` +
518
+ `Read original src/ files or source maps instead.`,
519
+ fileBytes: stat.size,
520
+ sliceBytes: targetBytes,
521
+ maxBytes,
522
+ savedTokens,
523
+ rawClampedTokens: savedTokens,
524
+ savedUSD
525
+ };
526
+ }
527
+
528
+ if (isLockfilePath(absFile) && !isSlicedCheck && (targetBytes > 16_384 || targetLineCount > 250)) {
529
+ const displayFile =
530
+ !relFile.startsWith('..') && !path.isAbsolute(relFile) ? relFile : path.basename(absFile);
531
+ const clampLimit = Math.min(80, targetLineCount);
532
+ const clampedBytes = Buffer.byteLength(targetSliceLines.slice(0, clampLimit).join('\n'), 'utf8');
533
+ const savedTokens = Math.max(0, Math.ceil((targetBytes - clampedBytes) / 4));
534
+ const rates = recordLedger
535
+ ? (baseRates || resolveEffectiveRates(modelId, promptTok, { cwd: baseCwd, homeDir }))
536
+ : null;
537
+ const savedUSD = rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
538
+ ? Number(((savedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
539
+ : 0;
540
+ if (recordLedger) {
541
+ const lockHash = crypto
542
+ .createHash('sha256')
543
+ .update(`lock:${absFile}:${clampLimit}:${stat.mtimeMs}`)
544
+ .digest('hex')
545
+ .slice(0, 16);
546
+ recordInterventionSavings(
547
+ {
548
+ sessionId,
549
+ cwd: baseCwd,
550
+ category: 'BOUNDED_READ_ENFORCED',
551
+ modelId,
552
+ savedTokens,
553
+ rawClampedTokens: savedTokens,
554
+ savedUSD,
555
+ dedupeId: `lock_clamp:${lockHash}`,
556
+ detail: `Clamped lockfile read of ${displayFile}`
557
+ },
558
+ { cwd: baseCwd, skipFsync: true, ...(homeDir ? { homeDir } : {}), ...(ledgerPath ? { ledgerPath } : {}) }
559
+ );
560
+ }
561
+ return {
562
+ action: 'clamp',
563
+ detectorId: 'DET-06',
564
+ subCode: 'LOCKFILE_CLAMP',
565
+ triggerReason: 'lockfile_clamp',
566
+ reason:
567
+ `[Burnoff DET-06 Lockfile Clamp] Clamped lockfile ${displayFile} (${(targetBytes / 1024).toFixed(1)} KB, ${targetLineCount} lines) ` +
568
+ `to L1..L${clampLimit} (~${(clampedBytes / 1024).toFixed(1)} KB). Use \`npm ls <pkg>\`, \`cargo tree -i <crate>\`, or read package.json/Cargo.toml instead.`,
569
+ clampOffset: 1,
570
+ clampLimit,
571
+ totalLines,
572
+ maxLines,
573
+ fileBytes: stat.size,
574
+ sliceBytes: targetBytes,
575
+ maxBytes,
576
+ clampedBytes,
577
+ nearCliff,
578
+ savedTokens,
579
+ rawClampedTokens: savedTokens,
580
+ savedUSD
581
+ };
582
+ }
583
+
424
584
  if (!nearCliff && matchesNeverClampExt(absFile, neverClampExt)) {
425
585
  return {
426
586
  action: 'allow',
@@ -450,6 +610,7 @@ export function evaluateShieldReadGuard({
450
610
  if (
451
611
  neverClampCodeOffCliff &&
452
612
  !nearCliff &&
613
+ !sightseeingMode &&
453
614
  isActiveSourceCodePath(absFile) &&
454
615
  targetBytes <= codeCeilingBytes
455
616
  ) {
@@ -511,7 +672,7 @@ export function evaluateShieldReadGuard({
511
672
  const clampEv = evaluateClampExpectedValue({
512
673
  clampSavedTokens,
513
674
  filePath: absFile,
514
- nearCliff,
675
+ nearCliff: nearCliff || sightseeingMode,
515
676
  promptTokens: promptTok,
516
677
  rates: rates && !rates.unknownModel ? rates : {}
517
678
  });
@@ -530,7 +691,9 @@ export function evaluateShieldReadGuard({
530
691
  !relFile.startsWith('..') && !path.isAbsolute(relFile) ? relFile : path.basename(absFile);
531
692
  const cliffTag = nearCliff
532
693
  ? ` (90% of ${(cliffTokens / 1000).toFixed(0)}k pricing cliff)`
533
- : '';
694
+ : sightseeingMode
695
+ ? ' (sightseeing mode)'
696
+ : '';
534
697
  const triggerReason = isSlicedCheck
535
698
  ? (exceedsLineCap ? 'explicit_slice_line_cap' : 'explicit_slice_byte_cap')
536
699
  : (exceedsLineCap ? 'line_cap' : 'byte_width_cap');
@@ -543,7 +706,7 @@ export function evaluateShieldReadGuard({
543
706
  const unreadSummary = unreadParts.length > 0 ? unreadParts.join(', ') : 'none';
544
707
  const landBlock = compactLandmarks ? `\n${compactLandmarks}` : '';
545
708
  const clampReason =
546
- `[Burnoff Read Clamp] Clamped ${isSlicedCheck ? 'wide slice' : 'unsliced Read'} of ${displayFile} (${capClause}${cliffTag}) ` +
709
+ `[Burnoff DET-06 Read Clamp] Clamped ${isSlicedCheck ? 'wide slice' : 'unsliced Read'} of ${displayFile} (${capClause}${cliffTag}) ` +
547
710
  `to L${reqOffset}..L${clampEnd} of ${totalLines} lines (~${(clampedBytes / 1024).toFixed(1)} KB; unread: ${unreadSummary}). ` +
548
711
  `Pass offset & limit to inspect remaining sections.${landBlock}`;
549
712
 
@@ -572,7 +735,8 @@ export function evaluateShieldReadGuard({
572
735
 
573
736
  return {
574
737
  action: 'clamp',
575
- detectorId: nearCliff ? 'DET-12' : 'DET-11',
738
+ detectorId: 'DET-06',
739
+ subCode: nearCliff ? 'DET-12' : 'DET-11',
576
740
  triggerReason,
577
741
  reason: clampReason,
578
742
  clampOffset: reqOffset,
@@ -648,8 +812,10 @@ export function mergeLineIntervals(intervals = []) {
648
812
  /**
649
813
  * Checks whether `[reqStart, reqEnd]` overlaps already-in-context intervals and returns a
650
814
  * contiguous unread trim when partial overlap is substantial.
815
+ * When `options.detectFullCover` is true and 100% of `[reqStart, reqEnd]` is already covered,
816
+ * returns `{ status: 'fully_covered', savedLines, anchorOffset, anchorLimit }`.
651
817
  */
652
- export function trimRequestedRangeAgainstIntervals(reqStart, reqEnd, rawIntervals = []) {
818
+ export function trimRequestedRangeAgainstIntervals(reqStart, reqEnd, rawIntervals = [], options = {}) {
653
819
  const start = Math.max(1, Math.floor(Number(reqStart) || 1));
654
820
  const end = Math.floor(Number(reqEnd) || 0);
655
821
  if (end < start) return { status: 'none' };
@@ -680,6 +846,14 @@ export function trimRequestedRangeAgainstIntervals(reqStart, reqEnd, rawInterval
680
846
  }
681
847
 
682
848
  if (overlapLines === 0) return { status: 'none' };
849
+ if (options?.detectFullCover === true && uncovered.length === 0) {
850
+ return {
851
+ status: 'fully_covered',
852
+ savedLines: reqLen,
853
+ anchorOffset: start,
854
+ anchorLimit: Math.min(15, reqLen)
855
+ };
856
+ }
683
857
  if (
684
858
  uncovered.length === 1 &&
685
859
  overlapLines >= Math.ceil(reqLen * 0.5) &&
@@ -696,7 +870,7 @@ export function trimRequestedRangeAgainstIntervals(reqStart, reqEnd, rawInterval
696
870
  return { status: 'none' };
697
871
  }
698
872
 
699
- export function recordReadIntervalEntry(store, normKey, statObj, startLine, endLine, nowMs = Date.now()) {
873
+ export function recordReadIntervalEntry(store, normKey, statObj, startLine, endLine, nowMs = Date.now(), turn = null) {
700
874
  if (!store || !normKey || !statObj || endLine < startLine) return;
701
875
  if (!store.__readIntervals || typeof store.__readIntervals !== 'object') {
702
876
  store.__readIntervals = {};
@@ -708,10 +882,12 @@ export function recordReadIntervalEntry(store, normKey, statObj, startLine, endL
708
882
  Number(prev.size) === Number(statObj.size);
709
883
  const existing = sameStat && Array.isArray(prev.intervals) ? prev.intervals : [];
710
884
  const recordedAt = Number.isFinite(Number(nowMs)) ? Number(nowMs) : Date.now();
885
+ const hasTurn = turn !== null && turn !== undefined && Number.isFinite(Number(turn));
711
886
  store.__readIntervals[normKey] = {
712
887
  mtimeMs: Number(statObj.mtimeMs),
713
888
  size: Number(statObj.size),
714
889
  recordedAt,
890
+ ...(hasTurn ? { recordedTurn: Number(turn) } : {}),
715
891
  intervals: mergeLineIntervals([...existing, [startLine, endLine]])
716
892
  };
717
893
  }
@@ -745,10 +921,14 @@ function writeReadSnapStoreUnlocked(
745
921
  ) {
746
922
  const recordedAt =
747
923
  Math.max(Number(prev.recordedAt || 0), Number(v.recordedAt || 0)) || Date.now();
924
+ const turns = [prev.recordedTurn, v.recordedTurn]
925
+ .filter((t) => t !== undefined && t !== null && Number.isFinite(Number(t)))
926
+ .map(Number);
748
927
  nextIntervals[k] = {
749
928
  mtimeMs: Number(v.mtimeMs),
750
929
  size: Number(v.size),
751
930
  recordedAt,
931
+ ...(turns.length > 0 ? { recordedTurn: Math.max(...turns) } : {}),
752
932
  intervals: mergeLineIntervals([...(prev.intervals || []), ...(v.intervals || [])])
753
933
  };
754
934
  } else {
@@ -809,6 +989,8 @@ export default {
809
989
  STRUCTURED_DATA_EXT_RE,
810
990
  isBurnoffArtifactPath,
811
991
  isGeneratedOrMinifiedCodePath,
992
+ isLockfilePath,
993
+ isMinifiedBundleArtifact,
812
994
  isActiveSourceCodePath,
813
995
  isStructuredDataPath,
814
996
  matchesNeverClampExt,
@@ -821,6 +1003,8 @@ export default {
821
1003
  mergeLineIntervals,
822
1004
  trimRequestedRangeAgainstIntervals,
823
1005
  recordReadIntervalEntry,
1006
+ isReadIntervalEntryFresh,
1007
+ DEFAULT_READ_INTERVAL_MAX_TURN_GAP,
824
1008
  saveReadSnapStore,
825
1009
  updateReadSnapStoreAtomicSync
826
1010
  };