burnoff 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,727 @@
1
+ /**
2
+ * @file src/guards/phase5-detectors.mjs
3
+ * Phase 5 runtime guard detectors (`DET-07`, `DET-08`, `DET-09`):
4
+ * - `DET-07`: Bash stdout-flood & Read-clamp bypass guard
5
+ * - `DET-08`: Edit-time test-weakening & empty-catch integrity guard
6
+ * - `DET-09`: Same-file rapid edit-thrash breaker (resets on verification runs)
7
+ * Zero external dependencies.
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import {
13
+ NEVER_TRIM_CODE_HARD_CEILING_BYTES,
14
+ isActiveSourceCodePath,
15
+ isStructuredDataPath,
16
+ matchesNeverClampExt
17
+ } from './read-clamp.mjs';
18
+ import { SHELL_TOOL_REGEX } from './shell-guard.mjs';
19
+
20
+ export const PHASE5_DEFAULTS = Object.freeze({
21
+ det07Enabled: true,
22
+ det07Action: 'ask',
23
+ det07ReadBypassMaxBytes: 16_384,
24
+ det07ReadBypassMaxLines: 250,
25
+ det08Enabled: true,
26
+ det08Action: 'ask',
27
+ det08CheckTestSkip: true,
28
+ det08CheckEmptyCatch: true,
29
+ det09Enabled: true,
30
+ det09Action: 'ask',
31
+ det09MaxEditsPerFile: 5,
32
+ det09WindowSec: 300
33
+ });
34
+
35
+ const EDIT_WRITE_TOOL_RE =
36
+ /^(?:Edit|Write|MultiEdit|NotebookEdit|edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content)$/i;
37
+
38
+ const ACTIVE_CODE_EXT_RE =
39
+ /\.(?:mjs|cjs|js|jsx|ts|tsx|py|go|rs|java|kt|kts|cs|cpp|cc|c|rb|php|swift|scala|vue|svelte)$/i;
40
+
41
+ const TEST_FILE_PATH_RE =
42
+ /(?:^|\/)(?:tests?|__tests__|spec)(?:\/|$)|\.(?:test|spec)\.[^./]+$|(?:^|\/)test_[^/]+\.py$/i;
43
+
44
+ const VERIFICATION_SHELL_RE =
45
+ /\b(?:npm\s+(?:test|run\s+(?:test|build|lint|check|typecheck)\b)|npx\s+(?:vitest|jest|mocha|tsc|eslint|prettier|playwright|cypress|burnoff\s+(?:doctor|audit))\b|pnpm\s+(?:test|build|lint)|yarn\s+(?:test|build|lint)|node\s+--test\b|pytest\b|python(?:3)?\s+-m\s+(?:pytest|unittest)\b|cargo\s+(?:test|check|build|clippy)\b|go\s+(?:test|vet|build)\b|dotnet\s+(?:test|build)\b|mvn\s+test\b|gradle\s+test\b|tsc\b|eslint\b|ruff\b|mypy\b|git\s+(?:stash|commit|status|diff)\b)/i;
46
+
47
+ const BOUNDING_PIPE_RE =
48
+ /\|\s*(?:head|tail|wc|grep|egrep|fgrep|rg|jq|awk|sed|cut|sort|uniq|less|more|Select-Object|Measure-Object|Select-String|Out-Null|Out-File|Format-Table)\b/i;
49
+
50
+ const EXEMPT_MCP_CONFIG_RE = /^(?:\.mcp\.json|mcp_config\.json)$/i;
51
+
52
+ /**
53
+ * Resolves the enforcement decision (`allow` | `advisory` | `ask` | `deny`) for Phase 5 detectors.
54
+ */
55
+ export function resolvePhase5Decision(configuredAction = 'ask', guardMode = 'guard') {
56
+ const mode = String(guardMode || 'guard').trim().toLowerCase();
57
+ const action = String(configuredAction || 'ask').trim().toLowerCase();
58
+
59
+ if (mode === 'off' || mode === 'disabled') {
60
+ return 'allow';
61
+ }
62
+ if (mode === 'advisory' || mode === 'warn') {
63
+ return 'advisory';
64
+ }
65
+ if (mode === 'strict' || mode === 'auto' || mode === 'auto_pilot') {
66
+ return action === 'advisory' ? 'advisory' : 'deny';
67
+ }
68
+ if (action === 'deny') return 'deny';
69
+ if (action === 'advisory' || action === 'allow') return 'advisory';
70
+ return 'ask';
71
+ }
72
+
73
+ /**
74
+ * Returns true if the shell command represents a verification/test/build/lint/checkpoint step
75
+ * whose successful execution clears `DET-09` same-file edit thrash history.
76
+ */
77
+ export function isVerificationShellCommand(command = '') {
78
+ return VERIFICATION_SHELL_RE.test(String(command || ''));
79
+ }
80
+
81
+ /**
82
+ * Normalizes a target file path to a consistent POSIX key for `DET-09` edit-thrash tracking.
83
+ */
84
+ export function normalizeEditThrashPath(filePath = '', cwd = '') {
85
+ const raw = String(filePath || '').trim();
86
+ if (!raw) return '';
87
+ const resolved = cwd
88
+ ? (path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(String(cwd), raw))
89
+ : path.resolve(raw);
90
+ return resolved.replace(/\\/g, '/').toLowerCase();
91
+ }
92
+
93
+ function isExemptMcpConfigFile(filePath = '') {
94
+ const base = path.basename(String(filePath || '').trim());
95
+ return EXEMPT_MCP_CONFIG_RE.test(base);
96
+ }
97
+
98
+ function splitCommandSegments(command = '') {
99
+ const segments = [];
100
+ let current = '';
101
+ let inSingle = false;
102
+ let inDouble = false;
103
+ const text = String(command || '');
104
+
105
+ for (let i = 0; i < text.length; i += 1) {
106
+ const ch = text[i];
107
+ const next = text[i + 1] || '';
108
+
109
+ if (ch === '\\' && !inSingle && i + 1 < text.length) {
110
+ current += ch + next;
111
+ i += 1;
112
+ continue;
113
+ }
114
+ if (ch === '\'' && !inDouble) {
115
+ inSingle = !inSingle;
116
+ current += ch;
117
+ continue;
118
+ }
119
+ if (ch === '"' && !inSingle) {
120
+ inDouble = !inDouble;
121
+ current += ch;
122
+ continue;
123
+ }
124
+
125
+ if (!inSingle && !inDouble) {
126
+ if ((ch === '&' && next === '&') || (ch === '|' && next === '|')) {
127
+ if (current.trim()) segments.push(current.trim());
128
+ current = '';
129
+ i += 1;
130
+ continue;
131
+ }
132
+ if (ch === ';' || ch === '\n') {
133
+ if (current.trim()) segments.push(current.trim());
134
+ current = '';
135
+ continue;
136
+ }
137
+ }
138
+
139
+ current += ch;
140
+ }
141
+
142
+ if (current.trim()) segments.push(current.trim());
143
+ return segments;
144
+ }
145
+
146
+ function tokenizeSimpleArgs(segment = '') {
147
+ const tokens = [];
148
+ let current = '';
149
+ let inSingle = false;
150
+ let inDouble = false;
151
+ let hasToken = false;
152
+ const text = String(segment || '');
153
+
154
+ for (let i = 0; i < text.length; i += 1) {
155
+ const ch = text[i];
156
+ if (ch === '\'' && !inDouble) {
157
+ inSingle = !inSingle;
158
+ hasToken = true;
159
+ continue;
160
+ }
161
+ if (ch === '"' && !inSingle) {
162
+ inDouble = !inDouble;
163
+ hasToken = true;
164
+ continue;
165
+ }
166
+ if (!inSingle && !inDouble && /\s/.test(ch)) {
167
+ if (hasToken || current.length > 0) {
168
+ tokens.push(current);
169
+ current = '';
170
+ hasToken = false;
171
+ }
172
+ continue;
173
+ }
174
+ current += ch;
175
+ hasToken = true;
176
+ }
177
+
178
+ if (hasToken || current.length > 0) {
179
+ tokens.push(current);
180
+ }
181
+ return tokens;
182
+ }
183
+
184
+ function hasBoundingPipeOrRedirect(segment = '') {
185
+ if (BOUNDING_PIPE_RE.test(segment)) return true;
186
+ if (/<</.test(segment)) return true;
187
+
188
+ // Strip fd-duplication / stderr redirection before looking for stdout file redirects (`>` / `>>`).
189
+ const scrubbed = segment
190
+ .replace(/\b[12]?>&[12]\b/g, ' ')
191
+ .replace(/\b2>>?\s*\S+/g, ' ');
192
+ return /(?:^|\s|[^\d])>>?\s*\S+/.test(scrubbed);
193
+ }
194
+
195
+ function inspectReadBypassSegment(segment, { cwd, maxBytes, maxLines, neverClampExt, neverClampCodeOffCliff }) {
196
+ if (hasBoundingPipeOrRedirect(segment)) return null;
197
+ const match = segment.match(/^(?:cat|nl|more|type|get-content|gc)\s+([\s\S]+)$/i);
198
+ if (!match) return null;
199
+
200
+ if (/^(?:get-content|gc)\b/i.test(segment) && /(?:^|\s)-(?:TotalCount|Head|First|Tail)\b/i.test(segment)) {
201
+ return null;
202
+ }
203
+
204
+ const tokens = tokenizeSimpleArgs(match[1]);
205
+ const candidateArgs = [];
206
+ for (let i = 0; i < tokens.length; i += 1) {
207
+ const tok = tokens[i];
208
+ if (!tok || tok === '|') break;
209
+ if (tok.startsWith('-')) {
210
+ if (/^-(?:n|Encoding|Path|LiteralPath)$/i.test(tok) && tokens[i + 1]) {
211
+ if (/^-(?:Path|LiteralPath)$/i.test(tok)) {
212
+ candidateArgs.push(tokens[i + 1]);
213
+ }
214
+ i += 1;
215
+ }
216
+ continue;
217
+ }
218
+ candidateArgs.push(tok);
219
+ }
220
+
221
+ const baseDir = cwd ? path.resolve(String(cwd)) : process.cwd();
222
+ for (const arg of candidateArgs) {
223
+ if (/[*?[\]{}]/.test(arg)) continue;
224
+ const absPath = path.isAbsolute(arg) ? path.resolve(arg) : path.resolve(baseDir, arg);
225
+ let stat;
226
+ try {
227
+ if (!fs.existsSync(absPath)) continue;
228
+ stat = fs.statSync(absPath);
229
+ } catch {
230
+ continue; // ignore: unreadable or transient path skipped by DET-07
231
+ }
232
+ if (!stat.isFile()) continue;
233
+
234
+ if (neverClampCodeOffCliff !== false && isActiveSourceCodePath(absPath) && stat.size <= NEVER_TRIM_CODE_HARD_CEILING_BYTES) {
235
+ continue;
236
+ }
237
+ if (
238
+ (isStructuredDataPath(absPath) && stat.size <= NEVER_TRIM_CODE_HARD_CEILING_BYTES) ||
239
+ matchesNeverClampExt(absPath, neverClampExt)
240
+ ) {
241
+ continue;
242
+ }
243
+
244
+ let lineCount = null;
245
+ if (stat.size <= maxBytes && stat.size <= 1_048_576) {
246
+ try {
247
+ const buf = fs.readFileSync(absPath);
248
+ let nl = 0;
249
+ for (let i = 0; i < buf.length; i += 1) {
250
+ if (buf[i] === 10) nl += 1;
251
+ }
252
+ lineCount = buf.length === 0 ? 0 : nl + 1;
253
+ } catch {
254
+ continue; // ignore: unreadable file content skipped by DET-07
255
+ }
256
+ }
257
+
258
+ if (stat.size > maxBytes || (lineCount !== null && lineCount > maxLines)) {
259
+ const kb = (stat.size / 1024).toFixed(1);
260
+ const estTok = Math.max(1, Math.round(stat.size / 4));
261
+ return {
262
+ subType: 'READ_CLAMP_BYPASS',
263
+ filePath: absPath,
264
+ reason:
265
+ `[Burnoff DET-07 Stdout Flood / Read-Clamp Bypass] "${segment.slice(0, 120)}" would dump ` +
266
+ `${path.basename(absPath)} (${kb} KB, ~${estTok.toLocaleString('en-US')} est. tok) to stdout, bypassing DET-06. ` +
267
+ `Use bounded Read (offset/limit) or pipe to "| head -n 100".`
268
+ };
269
+ }
270
+ }
271
+
272
+ return null;
273
+ }
274
+
275
+ function inspectUnboundedGitSegment(segment, cwd) {
276
+ if (hasBoundingPipeOrRedirect(segment)) return null;
277
+
278
+ const logMatch = segment.match(/^(?:git\s+(?:-[Cc]\s+\S+\s+)*log)(?:\s+([\s\S]*))?$/i);
279
+ if (logMatch) {
280
+ const rest = String(logMatch[1] || '');
281
+ const isBounded =
282
+ /(?:^|\s)(?:-n\s*\d+|-\d+\b|--max-count(?:=|\s+)\d+|--since\b|--after\b|--until\b|-S\b|-G\b|--grep\b|--walk-reflogs\b|--shortlog\b)/i.test(rest) ||
283
+ /\S+\.\.\S+/.test(rest);
284
+ if (!isBounded) {
285
+ return {
286
+ subType: 'UNBOUNDED_GIT_OUTPUT',
287
+ reason:
288
+ `[Burnoff DET-07 Stdout Flood Guard] Unbounded "git log" can dump full commit history to context. ` +
289
+ `Add "-n 20 --oneline" or pipe to "| head -n 50".`
290
+ };
291
+ }
292
+ return null;
293
+ }
294
+
295
+ const diffMatch = segment.match(/^(?:git\s+(?:-[Cc]\s+\S+\s+)*diff)(?:\s+([\s\S]*))?$/i);
296
+ if (diffMatch) {
297
+ const rest = String(diffMatch[1] || '');
298
+ const hasStatOrSummary =
299
+ /(?:^|\s)--(?:stat|numstat|shortstat|name-only|name-status|check|quiet|exit-code|summary|dirstat)\b/i.test(rest) ||
300
+ /(?:^|\s)--\s+\S+/.test(rest);
301
+ if (hasStatOrSummary) return null;
302
+
303
+ const tokens = tokenizeSimpleArgs(rest);
304
+ const baseDir = cwd ? path.resolve(String(cwd)) : process.cwd();
305
+ const hasExplicitFileScope = tokens.some((tok) => {
306
+ if (!tok || tok.startsWith('-')) return false;
307
+ if (/^(?:HEAD(?:~\d+|\^\d*)?|main|master|develop|@{[^}]+})$/i.test(tok)) return false;
308
+ if (/\.\./.test(tok)) return false;
309
+ if (cwd) {
310
+ try {
311
+ if (fs.existsSync(path.resolve(baseDir, tok))) return true;
312
+ } catch {
313
+ // ignore: fall back to heuristic path shape check
314
+ }
315
+ }
316
+ if (/^(?:origin|upstream|refs)\//i.test(tok)) return false;
317
+ return tok.includes('/') || /\.[a-zA-Z0-9]{1,10}$/.test(tok);
318
+ });
319
+ if (!hasExplicitFileScope) {
320
+ return {
321
+ subType: 'UNBOUNDED_GIT_OUTPUT',
322
+ reason:
323
+ `[Burnoff DET-07 Stdout Flood Guard] Unbounded "git diff" can dump large patch hunks across the repository. ` +
324
+ `Use "git diff --stat" first or scope to a single file path.`
325
+ };
326
+ }
327
+ }
328
+
329
+ return null;
330
+ }
331
+
332
+ function inspectUnboundedContainerLogSegment(segment) {
333
+ if (hasBoundingPipeOrRedirect(segment)) return null;
334
+ if (!/^(?:docker(?:\s+compose)?|docker-compose|kubectl)\s+logs\b/i.test(segment)) {
335
+ return null;
336
+ }
337
+ const isBounded = /(?:^|\s)(?:--tail(?:=|\s+)\S+|-n\s*\d+|--since(?:=|\s+)\S+|--since-time(?:=|\s+)\S+|--limit-bytes(?:=|\s+)\S+)/i.test(
338
+ segment
339
+ );
340
+ if (isBounded) return null;
341
+
342
+ return {
343
+ subType: 'UNBOUNDED_CONTAINER_LOGS',
344
+ reason:
345
+ `[Burnoff DET-07 Stdout Flood Guard] Unbounded container/pod logs can flood context with thousands of lines. ` +
346
+ `Add "--tail=100" (or "--tail 100") or pipe through "| tail -n 100".`
347
+ };
348
+ }
349
+
350
+ function inspectUnboundedSearchSegment(segment) {
351
+ if (hasBoundingPipeOrRedirect(segment)) return null;
352
+
353
+ if (/^find\s+(?:\/|\.)(?:\s|$)/i.test(segment)) {
354
+ const isBounded = /(?:^|\s)-(?:maxdepth|name|iname|path|prune)\b/i.test(segment);
355
+ if (!isBounded) {
356
+ return {
357
+ subType: 'UNBOUNDED_RECURSIVE_SEARCH',
358
+ reason:
359
+ `[Burnoff DET-07 Stdout Flood Guard] Unbounded recursive "find" can enumerate node_modules or entire filesystems. ` +
360
+ `Add "-maxdepth 3" / "-name <pattern>" or use the Glob tool.`
361
+ };
362
+ }
363
+ }
364
+
365
+ const grepMatch = segment.match(/^grep\s+([\s\S]+)$/i);
366
+ if (grepMatch) {
367
+ const rest = grepMatch[1];
368
+ const hasRecursive = /(?:^|\s)-(?:[a-zA-Z]*[rR][a-zA-Z]*)\b|(?:^|\s)--recursive\b/.test(rest);
369
+ if (!hasRecursive) return null;
370
+ if (/--exclude-dir(?:=|\s)|\s--include(?:=|\s)/i.test(rest)) return null;
371
+
372
+ const tokens = tokenizeSimpleArgs(rest);
373
+ const positional = [];
374
+ for (let i = 0; i < tokens.length; i += 1) {
375
+ const tok = tokens[i];
376
+ if (tok.startsWith('-')) {
377
+ if (/^-[efmABCD]$|^--(?:regexp|file|exclude|include|exclude-dir)$/i.test(tok)) {
378
+ i += 1;
379
+ }
380
+ continue;
381
+ }
382
+ positional.push(tok);
383
+ }
384
+ // First positional is the pattern (when -e wasn't passed), remaining positional args are paths.
385
+ const hasExplicitPatternFlag = /(?:^|\s)(?:-e|-f|--regexp|--file)\b/.test(rest);
386
+ const pathArgs = hasExplicitPatternFlag ? positional : positional.slice(1);
387
+ const targetsUnscopedRoot =
388
+ pathArgs.length === 0 || pathArgs.some((p) => p === '.' || p === './' || p === '/' || p === '.\\');
389
+ if (targetsUnscopedRoot) {
390
+ return {
391
+ subType: 'UNBOUNDED_RECURSIVE_SEARCH',
392
+ reason:
393
+ `[Burnoff DET-07 Stdout Flood Guard] Unbounded recursive "grep" at "." or "/" can scan node_modules and .git. ` +
394
+ `Scope to a subdirectory, add "--exclude-dir=node_modules --exclude-dir=.git", or use the Grep tool.`
395
+ };
396
+ }
397
+ }
398
+
399
+ return null;
400
+ }
401
+
402
+ /**
403
+ * DET-07: Bash Stdout-Flood & Read-Clamp Bypass Guard.
404
+ */
405
+ export function evaluateDet07CommandOutputGuard(params = {}) {
406
+ const toolName = String(params.toolName || '');
407
+ const command = String(params.command || '').trim();
408
+ const basePass = {
409
+ detectorId: 'DET-07',
410
+ triggered: false,
411
+ decision: 'allow',
412
+ subType: null,
413
+ reason: null,
414
+ additionalContext: null
415
+ };
416
+
417
+ if (!command || !SHELL_TOOL_REGEX.test(toolName)) {
418
+ return basePass;
419
+ }
420
+
421
+ const guardMode = params.mode ?? params.flightMode ?? 'guard';
422
+ const resolvedDecision = resolvePhase5Decision(params.action ?? PHASE5_DEFAULTS.det07Action, guardMode);
423
+ if (resolvedDecision === 'allow') {
424
+ return basePass;
425
+ }
426
+
427
+ const maxBytes = Math.max(1024, Number(params.maxBytes ?? PHASE5_DEFAULTS.det07ReadBypassMaxBytes));
428
+ const maxLines = Math.max(20, Number(params.maxLines ?? PHASE5_DEFAULTS.det07ReadBypassMaxLines));
429
+ const segments = splitCommandSegments(command);
430
+
431
+ let hit = null;
432
+ for (const segment of segments) {
433
+ hit =
434
+ inspectReadBypassSegment(segment, {
435
+ cwd: params.cwd,
436
+ maxBytes,
437
+ maxLines,
438
+ neverClampExt: params.neverClampExt,
439
+ neverClampCodeOffCliff: params.neverClampCodeOffCliff
440
+ }) ||
441
+ inspectUnboundedGitSegment(segment, params.cwd) ||
442
+ inspectUnboundedContainerLogSegment(segment) ||
443
+ inspectUnboundedSearchSegment(segment);
444
+ if (hit) break;
445
+ }
446
+
447
+ if (!hit) {
448
+ return basePass;
449
+ }
450
+
451
+ const finalDecision = resolvedDecision === 'advisory' ? 'allow' : resolvedDecision;
452
+ return {
453
+ detectorId: 'DET-07',
454
+ triggered: true,
455
+ decision: finalDecision,
456
+ subType: hit.subType,
457
+ filePath: hit.filePath || null,
458
+ reason: hit.reason,
459
+ additionalContext: finalDecision === 'allow' ? hit.reason : null
460
+ };
461
+ }
462
+
463
+ function extractEditPairs(toolName, toolInput = {}, filePath = '', cwd = '') {
464
+ if (Array.isArray(toolInput.edits)) {
465
+ return toolInput.edits.map((e) => ({
466
+ oldText: String(e?.old_string || ''),
467
+ newText: String(e?.new_string || '')
468
+ }));
469
+ }
470
+ if (Array.isArray(toolInput.ReplacementChunks)) {
471
+ return toolInput.ReplacementChunks.map((c) => ({
472
+ oldText: String(c?.TargetContent || ''),
473
+ newText: String(c?.ReplacementContent || '')
474
+ }));
475
+ }
476
+ if (
477
+ toolInput.new_string !== undefined ||
478
+ toolInput.Replacement !== undefined ||
479
+ toolInput.ReplacementContent !== undefined
480
+ ) {
481
+ return [
482
+ {
483
+ oldText: String(toolInput.old_string ?? toolInput.Target ?? toolInput.TargetContent ?? ''),
484
+ newText: String(toolInput.new_string ?? toolInput.Replacement ?? toolInput.ReplacementContent ?? '')
485
+ }
486
+ ];
487
+ }
488
+ const writeContent =
489
+ toolInput.content ?? toolInput.Content ?? toolInput.CodeContent ?? toolInput.new_source;
490
+ if (writeContent !== undefined) {
491
+ let oldText = '';
492
+ if (/^(?:Write|write_file|write_to_file)$/i.test(toolName) && filePath) {
493
+ const baseDir = cwd ? path.resolve(String(cwd)) : process.cwd();
494
+ const absPath = path.isAbsolute(filePath) ? path.resolve(filePath) : path.resolve(baseDir, filePath);
495
+ try {
496
+ if (fs.existsSync(absPath)) {
497
+ const st = fs.statSync(absPath);
498
+ if (st.isFile() && st.size <= 524_288) {
499
+ oldText = fs.readFileSync(absPath, 'utf8');
500
+ }
501
+ }
502
+ } catch {
503
+ oldText = ''; // ignore: unreadable existing target falls back to empty oldText
504
+ }
505
+ }
506
+ return [{ oldText, newText: String(writeContent) }];
507
+ }
508
+ return [];
509
+ }
510
+
511
+ function countTestWeakeningMarkers(text = '') {
512
+ if (!text) return 0;
513
+ const activeLines = String(text)
514
+ .split(/\r?\n/)
515
+ .filter((line) => {
516
+ const trimmed = line.trim();
517
+ if (!trimmed) return false;
518
+ if (/^(?:\/\/|#|\/\*|\*)/.test(trimmed)) return false;
519
+ if (/\b(?:burnoff-allow|ignore:)\b/i.test(trimmed)) return false;
520
+ return true;
521
+ })
522
+ .join('\n');
523
+
524
+ if (!activeLines) return 0;
525
+
526
+ let count = 0;
527
+ const patterns = [
528
+ /\b(?:test|it|describe|suite|context)\.(?:skip|only|todo)\s*\(/g,
529
+ /\b(?:xit|xdescribe|xtest|fit|fdescribe)\s*\(/g,
530
+ /\b(?:test|it|describe)\s*\([^,\n]+,\s*\{[^}\n]*\bskip\s*:\s*true\b/g,
531
+ /@(?:pytest\.mark|unittest)\.skip(?:If|Unless)?\b/g,
532
+ /\bpytest\.skip\s*\(/g
533
+ ];
534
+ for (const re of patterns) {
535
+ const matches = activeLines.match(re);
536
+ if (matches) count += matches.length;
537
+ }
538
+ return count;
539
+ }
540
+
541
+ function countEmptyCatchBlocks(text = '', filePath = '') {
542
+ if (!text) return 0;
543
+ if (/\.py$/i.test(String(filePath || ''))) {
544
+ const lines = String(text).split(/\r?\n/);
545
+ let pyCount = 0;
546
+ for (let i = 0; i < lines.length - 1; i += 1) {
547
+ const line = lines[i];
548
+ if (/#/.test(line)) continue;
549
+ if (!/^\s*except(?:\s+[^:#\n]+)?:\s*$/.test(line)) continue;
550
+ const nextLine = lines[i + 1];
551
+ if (!nextLine || /#/.test(nextLine)) continue;
552
+ if (/^(\s*)pass\s*$/.test(nextLine)) {
553
+ const passIndent = nextLine.match(/^(\s*)/)[1].length;
554
+ const exceptIndent = line.match(/^(\s*)/)[1].length;
555
+ if (passIndent > exceptIndent) {
556
+ pyCount += 1;
557
+ }
558
+ }
559
+ }
560
+ return pyCount;
561
+ }
562
+
563
+ const catchMatches = String(text).match(/\bcatch\s*(?:\([^)]*\))?\s*\{\s*\}/g);
564
+ return catchMatches ? catchMatches.length : 0;
565
+ }
566
+
567
+ /**
568
+ * DET-08: Edit-Time Test-Weakening & Empty-Catch Guard.
569
+ */
570
+ export function evaluateDet08EditIntegrityGuard(params = {}) {
571
+ const toolName = String(params.toolName || '');
572
+ const filePath = String(params.filePath || '').trim();
573
+ const basePass = {
574
+ detectorId: 'DET-08',
575
+ triggered: false,
576
+ decision: 'allow',
577
+ subType: null,
578
+ reason: null,
579
+ additionalContext: null
580
+ };
581
+
582
+ if (!filePath || !EDIT_WRITE_TOOL_RE.test(toolName) || isExemptMcpConfigFile(filePath)) {
583
+ return basePass;
584
+ }
585
+
586
+ const normPath = filePath.replace(/\\/g, '/');
587
+ if (!ACTIVE_CODE_EXT_RE.test(normPath)) {
588
+ return basePass;
589
+ }
590
+
591
+ const guardMode = params.mode ?? params.flightMode ?? 'guard';
592
+ const resolvedDecision = resolvePhase5Decision(params.action ?? PHASE5_DEFAULTS.det08Action, guardMode);
593
+ if (resolvedDecision === 'allow') {
594
+ return basePass;
595
+ }
596
+
597
+ const pairs = extractEditPairs(toolName, params.toolInput || {}, filePath, params.cwd);
598
+ if (pairs.length === 0) {
599
+ return basePass;
600
+ }
601
+
602
+ const combinedOld = pairs.map((p) => p.oldText).join('\n');
603
+ const combinedNew = pairs.map((p) => p.newText).join('\n');
604
+ const checkTestSkip = params.checkTestSkip !== false && TEST_FILE_PATH_RE.test(normPath);
605
+ const checkEmptyCatch = params.checkEmptyCatch !== false;
606
+
607
+ const newSkipsAdded =
608
+ checkTestSkip && countTestWeakeningMarkers(combinedNew) > countTestWeakeningMarkers(combinedOld);
609
+ const newEmptyCatchAdded =
610
+ checkEmptyCatch &&
611
+ countEmptyCatchBlocks(combinedNew, normPath) > countEmptyCatchBlocks(combinedOld, normPath);
612
+
613
+ if (!newSkipsAdded && !newEmptyCatchAdded) {
614
+ return basePass;
615
+ }
616
+
617
+ const subType =
618
+ newSkipsAdded && newEmptyCatchAdded
619
+ ? 'BOTH'
620
+ : newSkipsAdded
621
+ ? 'TEST_WEAKENING'
622
+ : 'EMPTY_CATCH_BLOCK';
623
+
624
+ const findings = [];
625
+ if (newSkipsAdded) findings.push('skipped/disabled tests (.skip/.only/xit/pytest.skip)');
626
+ if (newEmptyCatchAdded) findings.push('empty catch / bare except-pass error swallowing');
627
+
628
+ const commentHint = /\.py$/i.test(normPath) ? '# ignore: <reason>' : '// ignore: <reason>';
629
+ const reason =
630
+ `[Burnoff DET-08 Edit Integrity Guard] Detected newly introduced ${findings.join(' and ')} in "${path.basename(filePath)}". ` +
631
+ `Keep test coverage intact and log or comment ("${commentHint}") intentional error handlers.`;
632
+ const finalDecision = resolvedDecision === 'advisory' ? 'allow' : resolvedDecision;
633
+
634
+ return {
635
+ detectorId: 'DET-08',
636
+ triggered: true,
637
+ decision: finalDecision,
638
+ subType,
639
+ filePath,
640
+ reason,
641
+ additionalContext: finalDecision === 'allow' ? reason : null
642
+ };
643
+ }
644
+
645
+ /**
646
+ * DET-09: Same-File Rapid Edit-Thrash Breaker.
647
+ */
648
+ export function evaluateDet09EditThrash(params = {}) {
649
+ const toolName = String(params.toolName || '');
650
+ const filePath = String(params.filePath || '').trim();
651
+ const basePass = {
652
+ detectorId: 'DET-09',
653
+ triggered: false,
654
+ decision: 'allow',
655
+ subType: null,
656
+ editCount: 0,
657
+ maxEditsPerFile: Number(params.maxEditsPerFile ?? PHASE5_DEFAULTS.det09MaxEditsPerFile),
658
+ windowSec: Number(params.windowSec ?? PHASE5_DEFAULTS.det09WindowSec),
659
+ fileKey: '',
660
+ reason: null,
661
+ additionalContext: null
662
+ };
663
+
664
+ if (!filePath || !EDIT_WRITE_TOOL_RE.test(toolName) || isExemptMcpConfigFile(filePath)) {
665
+ return basePass;
666
+ }
667
+
668
+ const guardMode = params.mode ?? params.flightMode ?? 'guard';
669
+ const resolvedDecision = resolvePhase5Decision(params.action ?? PHASE5_DEFAULTS.det09Action, guardMode);
670
+ if (resolvedDecision === 'allow') {
671
+ return basePass;
672
+ }
673
+
674
+ const nowMs = Number.isFinite(Number(params.nowMs)) ? Number(params.nowMs) : Date.now();
675
+ const maxEditsPerFile = Math.max(1, Number(params.maxEditsPerFile ?? PHASE5_DEFAULTS.det09MaxEditsPerFile));
676
+ const windowSec = Math.max(10, Number(params.windowSec ?? PHASE5_DEFAULTS.det09WindowSec));
677
+ const windowStartMs = nowMs - windowSec * 1000;
678
+
679
+ const fileKey = normalizeEditThrashPath(filePath, params.cwd);
680
+ const historyObj =
681
+ params.editThrashHistory && typeof params.editThrashHistory === 'object'
682
+ ? params.editThrashHistory
683
+ : {};
684
+ const priorTimestamps = Array.isArray(historyObj[fileKey]) ? historyObj[fileKey] : [];
685
+ const activeTimestamps = priorTimestamps
686
+ .map((ts) => Number(ts))
687
+ .filter((ts) => Number.isFinite(ts) && ts >= windowStartMs && ts <= nowMs);
688
+ const editCount = activeTimestamps.length + 1;
689
+
690
+ if (editCount <= maxEditsPerFile) {
691
+ return {
692
+ ...basePass,
693
+ editCount,
694
+ maxEditsPerFile,
695
+ windowSec,
696
+ fileKey
697
+ };
698
+ }
699
+
700
+ const reason =
701
+ `[Burnoff DET-09 Edit-Thrash Breaker] Edit #${editCount} to "${path.basename(filePath)}" within ${windowSec}s ` +
702
+ `(cap: ${maxEditsPerFile}) without a passing verification run. Run tests/build to verify your current state or consolidate remaining edits.`;
703
+ const finalDecision = resolvedDecision === 'advisory' ? 'allow' : resolvedDecision;
704
+
705
+ return {
706
+ detectorId: 'DET-09',
707
+ triggered: true,
708
+ decision: finalDecision,
709
+ subType: 'SAME_FILE_EDIT_THRASH',
710
+ editCount,
711
+ maxEditsPerFile,
712
+ windowSec,
713
+ fileKey,
714
+ reason,
715
+ additionalContext: finalDecision === 'allow' ? reason : null
716
+ };
717
+ }
718
+
719
+ export default {
720
+ PHASE5_DEFAULTS,
721
+ resolvePhase5Decision,
722
+ isVerificationShellCommand,
723
+ normalizeEditThrashPath,
724
+ evaluateDet07CommandOutputGuard,
725
+ evaluateDet08EditIntegrityGuard,
726
+ evaluateDet09EditThrash
727
+ };