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.
- package/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/burnoff-pr-gate.yml +5 -3
- package/.github/workflows/burnoff-startup-lint.yml +2 -2
- package/CHANGELOG.md +74 -0
- package/README.md +187 -213
- package/SECURITY.md +38 -0
- package/bin/burnoff.mjs +307 -32
- package/commands/burnoff.md +6 -4
- package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
- package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
- package/hooks/hook-io.mjs +216 -11
- package/hooks/hooks.json +44 -0
- package/hooks/post-tool-use.mjs +3 -1
- package/hooks/pre-tool-use.mjs +47 -8
- package/hooks/session-lifecycle.mjs +24 -3
- package/hooks/user-prompt-submit.mjs +98 -0
- package/package.json +6 -4
- package/scripts/bench-hooks.mjs +34 -3
- package/scripts/bench-savings.mjs +318 -0
- package/scripts/burnoff-statusline.mjs +138 -6
- package/src/ci/ci-gate.mjs +199 -13
- package/src/ci/pr-cost.mjs +417 -45
- package/src/ci/pr-summary.mjs +467 -0
- package/src/cli/audit.mjs +179 -28
- package/src/cli/doctor.mjs +32 -6
- package/src/cli/hook-health.mjs +9 -1
- package/src/cli/init.mjs +226 -39
- package/src/cli/preview.mjs +299 -0
- package/src/cli/startup-audit/formatter.mjs +248 -0
- package/src/cli/startup-audit/jsonc.mjs +601 -0
- package/src/cli/startup-audit/mcp-audit.mjs +735 -0
- package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
- package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
- package/src/cli/startup-audit.mjs +451 -2471
- package/src/clients/claude-code.mjs +41 -4
- package/src/config/catalog.json +295 -0
- package/src/config/effort.mjs +145 -0
- package/src/config/harness-quirks.mjs +340 -0
- package/src/config/loader.mjs +27 -2
- package/src/config/policy.mjs +81 -9
- package/src/config/pricing.mjs +247 -19
- package/src/config/semver.mjs +25 -0
- package/src/config/uncached-attribution.mjs +280 -41
- package/src/guards/compaction-baton.mjs +248 -0
- package/src/guards/loop-breaker.mjs +328 -47
- package/src/guards/model-switch-hook.mjs +126 -0
- package/src/guards/phase5-detectors.mjs +275 -21
- package/src/guards/post-tool-engine.mjs +333 -11
- package/src/guards/pre-tool-engine.mjs +607 -45
- package/src/guards/prefix-guard.mjs +609 -0
- package/src/guards/prompt-guard.mjs +309 -0
- package/src/guards/read-clamp.mjs +192 -8
- package/src/guards/session-hook.mjs +149 -7
- package/src/guards/shell-guard.mjs +56 -5
- package/src/guards/snooze.mjs +169 -5
- package/src/ipc/daemon.mjs +76 -0
- package/src/ipc/fast-client.mjs +165 -4
- package/src/ipc/protocol.mjs +16 -3
- package/src/storage/antigravity-parser.mjs +16 -2
- package/src/storage/file-lock.mjs +16 -3
- package/src/storage/jsonl-parser.mjs +133 -22
- package/src/storage/telemetry-metrics.mjs +254 -4
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/guards/model-switch-hook.mjs
|
|
3
|
+
* Claude Code `PreModelSwitch` / `PostModelSwitch` handler (`BO-MOD-02`).
|
|
4
|
+
*
|
|
5
|
+
* - `PreModelSwitch` (`from_model`, `to_model`): advisory by default; exit `2` only when
|
|
6
|
+
* `guards.modelSwitchAction: deny` and a warm prefix or A->B->A ping-pong is at stake.
|
|
7
|
+
* - `PostModelSwitch`: observational; records `lastModel` / `recentModels` and emits a concise
|
|
8
|
+
* cache-rebuild advisory when the switch abandoned a warm prefix.
|
|
9
|
+
*
|
|
10
|
+
* Lives beside (not inside) `prefix-guard.mjs` because `loop-breaker.mjs` already imports
|
|
11
|
+
* `prefix-guard.mjs`; the pure scoring lives in `evaluateModelSwitch` there.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import path from 'node:path';
|
|
15
|
+
import { loadBurnoffPolicy } from '../config/policy.mjs';
|
|
16
|
+
import { readBreakerStateSnapshot, updateBreakerStateAtomicSync } from './loop-breaker.mjs';
|
|
17
|
+
import { evaluateModelSwitch } from './prefix-guard.mjs';
|
|
18
|
+
|
|
19
|
+
const DEFAULT_CACHE_TTL_5M_MS = 5 * 60 * 1000;
|
|
20
|
+
const DEFAULT_CACHE_TTL_1H_MS = 60 * 60 * 1000;
|
|
21
|
+
|
|
22
|
+
export function isModelSwitchEvent(event = {}, options = {}) {
|
|
23
|
+
const name = String(event?.hook_event_name || event?.hookEventName || options?.hookEventName || '');
|
|
24
|
+
return /^(?:Pre|Post)ModelSwitch$/i.test(name.trim());
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Evaluates a `PreModelSwitch` or `PostModelSwitch` payload and persists post-switch state.
|
|
29
|
+
*/
|
|
30
|
+
export function runModelSwitchHook(event = {}, options = {}) {
|
|
31
|
+
const hookEventName = String(
|
|
32
|
+
event.hook_event_name || event.hookEventName || options.hookEventName || ''
|
|
33
|
+
).trim();
|
|
34
|
+
const isPost = /^PostModelSwitch$/i.test(hookEventName);
|
|
35
|
+
const sessionId = String(event.session_id || event.sessionId || options.sessionId || 'default');
|
|
36
|
+
const rawCwd = String(event.cwd || options.cwd || '').trim();
|
|
37
|
+
const baseCwd = rawCwd ? path.resolve(rawCwd) : process.cwd();
|
|
38
|
+
const cwdOptions = { ...(rawCwd ? { ...options, cwd: baseCwd } : options) };
|
|
39
|
+
const policy = options.policy || loadBurnoffPolicy(baseCwd);
|
|
40
|
+
const shouldPersistState =
|
|
41
|
+
options.persistState !== false &&
|
|
42
|
+
Boolean(rawCwd || options.breakerStatePath || options.persistState);
|
|
43
|
+
|
|
44
|
+
const rawNow = options.nowMs ?? event.timestamp;
|
|
45
|
+
const nowMs = Number.isFinite(Number(rawNow)) ? Number(rawNow) : Date.now();
|
|
46
|
+
|
|
47
|
+
let prior = null;
|
|
48
|
+
if (shouldPersistState) {
|
|
49
|
+
try {
|
|
50
|
+
prior = readBreakerStateSnapshot(sessionId, cwdOptions);
|
|
51
|
+
} catch (err) {
|
|
52
|
+
void err; // ignore: unreadable breaker snapshot falls back to a stateless evaluation
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const ttlTier = String(
|
|
57
|
+
event.cacheTtlTier || prior?.cacheTtlTier || policy.guards?.cacheTtlTier || '5m'
|
|
58
|
+
).toLowerCase();
|
|
59
|
+
const evalResult = evaluateModelSwitch({
|
|
60
|
+
phase: isPost ? 'post' : 'pre',
|
|
61
|
+
event,
|
|
62
|
+
prior,
|
|
63
|
+
policy,
|
|
64
|
+
effectiveTtlMs: ttlTier === '1h' ? DEFAULT_CACHE_TTL_1H_MS : DEFAULT_CACHE_TTL_5M_MS,
|
|
65
|
+
nowMs,
|
|
66
|
+
env: options.env
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
if (isPost && shouldPersistState && Object.keys(evalResult.nextStatePatch).length > 0) {
|
|
70
|
+
try {
|
|
71
|
+
updateBreakerStateAtomicSync(
|
|
72
|
+
sessionId,
|
|
73
|
+
(cur) => ({
|
|
74
|
+
schemaVersion: '1.0.0',
|
|
75
|
+
...(cur && typeof cur === 'object' ? cur : {}),
|
|
76
|
+
...evalResult.nextStatePatch,
|
|
77
|
+
sessionId,
|
|
78
|
+
updatedAt: nowMs
|
|
79
|
+
}),
|
|
80
|
+
cwdOptions
|
|
81
|
+
);
|
|
82
|
+
} catch (err) {
|
|
83
|
+
void err; // ignore: non-fatal post-switch state persistence
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const detectorIds = [...new Set(evalResult.findings.map((f) => f.detectorId))];
|
|
88
|
+
const reason = evalResult.findings.map((f) => f.reason).join('\n');
|
|
89
|
+
|
|
90
|
+
if (evalResult.decision === 'deny') {
|
|
91
|
+
return {
|
|
92
|
+
exitCode: 2,
|
|
93
|
+
stdout: '',
|
|
94
|
+
stderr: reason,
|
|
95
|
+
detectorIds,
|
|
96
|
+
verdict: { triggered: true, detectorId: detectorIds[0], detectorIds, decision: 'deny', reason }
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (!reason) {
|
|
101
|
+
return {
|
|
102
|
+
exitCode: 0,
|
|
103
|
+
stdout: '',
|
|
104
|
+
stderr: '',
|
|
105
|
+
detectorIds: [],
|
|
106
|
+
verdict: { triggered: false, decision: 'allow', detectorIds: [], reason: null }
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
exitCode: 0,
|
|
112
|
+
stdout: JSON.stringify({ systemMessage: reason }),
|
|
113
|
+
stderr: '',
|
|
114
|
+
detectorIds,
|
|
115
|
+
verdict: {
|
|
116
|
+
triggered: true,
|
|
117
|
+
detectorId: detectorIds[0],
|
|
118
|
+
detectorIds,
|
|
119
|
+
decision: 'allow',
|
|
120
|
+
reason,
|
|
121
|
+
additionalContext: reason
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export default { isModelSwitchEvent, runModelSwitchHook };
|
|
@@ -12,10 +12,13 @@ import path from 'node:path';
|
|
|
12
12
|
import {
|
|
13
13
|
NEVER_TRIM_CODE_HARD_CEILING_BYTES,
|
|
14
14
|
isActiveSourceCodePath,
|
|
15
|
+
isGeneratedOrMinifiedCodePath,
|
|
16
|
+
isLockfilePath,
|
|
15
17
|
isStructuredDataPath,
|
|
16
18
|
matchesNeverClampExt
|
|
17
19
|
} from './read-clamp.mjs';
|
|
18
20
|
import { SHELL_TOOL_REGEX } from './shell-guard.mjs';
|
|
21
|
+
import { normalizePlatformPathKey } from '../../hooks/hook-io.mjs';
|
|
19
22
|
|
|
20
23
|
export const PHASE5_DEFAULTS = Object.freeze({
|
|
21
24
|
det07Enabled: true,
|
|
@@ -26,10 +29,14 @@ export const PHASE5_DEFAULTS = Object.freeze({
|
|
|
26
29
|
det08Action: 'ask',
|
|
27
30
|
det08CheckTestSkip: true,
|
|
28
31
|
det08CheckEmptyCatch: true,
|
|
32
|
+
det08CheckAssertionDrop: true,
|
|
33
|
+
det08AssertionDropAction: 'advisory',
|
|
29
34
|
det09Enabled: true,
|
|
30
|
-
det09Action: '
|
|
35
|
+
det09Action: 'advisory',
|
|
31
36
|
det09MaxEditsPerFile: 5,
|
|
32
|
-
det09WindowSec: 300
|
|
37
|
+
det09WindowSec: 300,
|
|
38
|
+
det10Enabled: true,
|
|
39
|
+
det10Action: 'ask'
|
|
33
40
|
});
|
|
34
41
|
|
|
35
42
|
const EDIT_WRITE_TOOL_RE =
|
|
@@ -87,7 +94,7 @@ export function normalizeEditThrashPath(filePath = '', cwd = '') {
|
|
|
87
94
|
const resolved = cwd
|
|
88
95
|
? (path.isAbsolute(raw) ? path.resolve(raw) : path.resolve(String(cwd), raw))
|
|
89
96
|
: path.resolve(raw);
|
|
90
|
-
return resolved
|
|
97
|
+
return normalizePlatformPathKey(resolved);
|
|
91
98
|
}
|
|
92
99
|
|
|
93
100
|
function isExemptMcpConfigFile(filePath = '') {
|
|
@@ -231,12 +238,19 @@ function inspectReadBypassSegment(segment, { cwd, maxBytes, maxLines, neverClamp
|
|
|
231
238
|
}
|
|
232
239
|
if (!stat.isFile()) continue;
|
|
233
240
|
|
|
234
|
-
|
|
241
|
+
const isArtifactOrLockfile = isLockfilePath(absPath) || isGeneratedOrMinifiedCodePath(absPath);
|
|
242
|
+
if (
|
|
243
|
+
!isArtifactOrLockfile &&
|
|
244
|
+
neverClampCodeOffCliff !== false &&
|
|
245
|
+
isActiveSourceCodePath(absPath) &&
|
|
246
|
+
stat.size <= NEVER_TRIM_CODE_HARD_CEILING_BYTES
|
|
247
|
+
) {
|
|
235
248
|
continue;
|
|
236
249
|
}
|
|
237
250
|
if (
|
|
238
|
-
|
|
239
|
-
|
|
251
|
+
!isArtifactOrLockfile &&
|
|
252
|
+
((isStructuredDataPath(absPath) && stat.size <= NEVER_TRIM_CODE_HARD_CEILING_BYTES) ||
|
|
253
|
+
matchesNeverClampExt(absPath, neverClampExt))
|
|
240
254
|
) {
|
|
241
255
|
continue;
|
|
242
256
|
}
|
|
@@ -258,13 +272,18 @@ function inspectReadBypassSegment(segment, { cwd, maxBytes, maxLines, neverClamp
|
|
|
258
272
|
if (stat.size > maxBytes || (lineCount !== null && lineCount > maxLines)) {
|
|
259
273
|
const kb = (stat.size / 1024).toFixed(1);
|
|
260
274
|
const estTok = Math.max(1, Math.round(stat.size / 4));
|
|
275
|
+
const baseName = path.basename(absPath);
|
|
276
|
+
const tip = isLockfilePath(absPath)
|
|
277
|
+
? 'Use `npm ls <pkg>`, `cargo tree -i <crate>`, or read package.json/Cargo.toml instead.'
|
|
278
|
+
: isGeneratedOrMinifiedCodePath(absPath)
|
|
279
|
+
? 'Read the original src/ files or source maps instead of generated/minified bundles.'
|
|
280
|
+
: 'Use bounded Read (offset/limit) or pipe to "| head -n 100".';
|
|
261
281
|
return {
|
|
262
|
-
subType: 'READ_CLAMP_BYPASS',
|
|
282
|
+
subType: isArtifactOrLockfile ? 'ARTIFACT_READ_BYPASS' : 'READ_CLAMP_BYPASS',
|
|
263
283
|
filePath: absPath,
|
|
264
284
|
reason:
|
|
265
285
|
`[Burnoff DET-07 Stdout Flood / Read-Clamp Bypass] "${segment.slice(0, 120)}" would dump ` +
|
|
266
|
-
`${
|
|
267
|
-
`Use bounded Read (offset/limit) or pipe to "| head -n 100".`
|
|
286
|
+
`${baseName} (${kb} KB, ~${estTok.toLocaleString('en-US')} est. tok) to stdout, bypassing DET-06. ${tip}`
|
|
268
287
|
};
|
|
269
288
|
}
|
|
270
289
|
}
|
|
@@ -350,7 +369,19 @@ function inspectUnboundedContainerLogSegment(segment) {
|
|
|
350
369
|
function inspectUnboundedSearchSegment(segment) {
|
|
351
370
|
if (hasBoundingPipeOrRedirect(segment)) return null;
|
|
352
371
|
|
|
353
|
-
if (/^find\s
|
|
372
|
+
if (/^find\s+\/(?:\s|$)/i.test(segment)) {
|
|
373
|
+
const hasMaxDepth = /(?:^|\s)-maxdepth\b/i.test(segment);
|
|
374
|
+
if (!hasMaxDepth) {
|
|
375
|
+
return {
|
|
376
|
+
subType: 'UNBOUNDED_RECURSIVE_SEARCH',
|
|
377
|
+
reason:
|
|
378
|
+
`[Burnoff DET-07 Stdout Flood Guard] Root filesystem "find /" without -maxdepth can scan huge directory trees. ` +
|
|
379
|
+
`Scope to a workspace subdirectory, add "-maxdepth 3", or use the Glob tool.`
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
if (/^find\s+\.(?:\s|$)/i.test(segment)) {
|
|
354
385
|
const isBounded = /(?:^|\s)-(?:maxdepth|name|iname|path|prune)\b/i.test(segment);
|
|
355
386
|
if (!isBounded) {
|
|
356
387
|
return {
|
|
@@ -362,6 +393,24 @@ function inspectUnboundedSearchSegment(segment) {
|
|
|
362
393
|
}
|
|
363
394
|
}
|
|
364
395
|
|
|
396
|
+
if (/^ls\b/i.test(segment) && /(?:^|\s)(?:-[a-zA-Z]*R[a-zA-Z]*|--recursive)\b/.test(segment)) {
|
|
397
|
+
return {
|
|
398
|
+
subType: 'UNBOUNDED_RECURSIVE_SEARCH',
|
|
399
|
+
reason:
|
|
400
|
+
`[Burnoff DET-07 Stdout Flood Guard] Recursive "ls -R" can enumerate entire directory trees and flood context. ` +
|
|
401
|
+
`Use a targeted Glob pattern or pipe to "| head -n 100".`
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
if (/^tree(?:\s|$)/i.test(segment) && !/(?:^|\s)(?:-L\s*\d+|--level(?:=|\s+)\d+)/.test(segment)) {
|
|
406
|
+
return {
|
|
407
|
+
subType: 'UNBOUNDED_RECURSIVE_SEARCH',
|
|
408
|
+
reason:
|
|
409
|
+
`[Burnoff DET-07 Stdout Flood Guard] Unbounded "tree" without "-L <depth>" can flood context. ` +
|
|
410
|
+
`Pass "-L 2 -I node_modules" or use Glob.`
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
|
|
365
414
|
const grepMatch = segment.match(/^grep\s+([\s\S]+)$/i);
|
|
366
415
|
if (grepMatch) {
|
|
367
416
|
const rest = grepMatch[1];
|
|
@@ -564,8 +613,65 @@ function countEmptyCatchBlocks(text = '', filePath = '') {
|
|
|
564
613
|
return catchMatches ? catchMatches.length : 0;
|
|
565
614
|
}
|
|
566
615
|
|
|
616
|
+
const LAZY_COMMENT_BODY_RE =
|
|
617
|
+
/^\s*(?:\/\/|\/\*|#|<!--|--)\s*(?:\.{2,3}|…)?\s*(?:rest\s+of|existing|remaining|unchanged|omitted|previous|other)\s+(?:the\s+)?(?:code|impl(?:ementation)?|lines|methods|functions|body|logic|handlers|file)\b/i;
|
|
618
|
+
const LAZY_COMMENT_ELLIPSIS_RE =
|
|
619
|
+
/^\s*(?:\/\/|\/\*|#|<!--|--)\s*(?:\.{2,3}|…)\s*(?:snip|unchanged|omitted|etc\.?)\b/i;
|
|
620
|
+
const STUB_MARKER_RE =
|
|
621
|
+
/^\s*(?:\/\/|#)\s*stub\b|\b(?:NotImplementedError|TODO:\s*implement)\b/i;
|
|
622
|
+
|
|
623
|
+
function countLazyElisionMarkers(text = '') {
|
|
624
|
+
if (!text) return 0;
|
|
625
|
+
let count = 0;
|
|
626
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
627
|
+
const trimmed = line.trim();
|
|
628
|
+
if (!trimmed) continue;
|
|
629
|
+
if (/\b(?:burnoff-allow|ignore:)\b/i.test(trimmed)) continue;
|
|
630
|
+
if (LAZY_COMMENT_BODY_RE.test(trimmed) || LAZY_COMMENT_ELLIPSIS_RE.test(trimmed)) {
|
|
631
|
+
count += 1;
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return count;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
function countNonEmptyLines(text = '') {
|
|
638
|
+
if (!text) return 0;
|
|
639
|
+
let n = 0;
|
|
640
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
641
|
+
if (line.trim().length > 0) n += 1;
|
|
642
|
+
}
|
|
643
|
+
return n;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function countStubMarkers(text = '') {
|
|
647
|
+
if (!text) return 0;
|
|
648
|
+
let count = 0;
|
|
649
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
650
|
+
if (STUB_MARKER_RE.test(line)) count += 1;
|
|
651
|
+
}
|
|
652
|
+
return count;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const TEST_ASSERTION_LINE_RE =
|
|
656
|
+
/\bexpect\s*\(|\bassert\s*\(|\bassert\.[A-Za-z_]\w*\s*\(|\bassert(?:_eq|_ne)?!\s*\(|\bt\.(?:Error|Errorf|Fatal|Fatalf)\s*\(|\brequire\.[A-Za-z_]\w*\s*\(/;
|
|
657
|
+
|
|
567
658
|
/**
|
|
568
|
-
*
|
|
659
|
+
* Counts non-comment lines containing unit-test assertion calls (`expect`, `assert`, `require`, `t.Error`).
|
|
660
|
+
*/
|
|
661
|
+
export function countTestAssertions(text = '') {
|
|
662
|
+
if (!text) return 0;
|
|
663
|
+
let count = 0;
|
|
664
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
665
|
+
const trimmed = line.trim();
|
|
666
|
+
if (!trimmed) continue;
|
|
667
|
+
if (/^(?:\/\/|#|\/\*|\*)/.test(trimmed)) continue;
|
|
668
|
+
if (TEST_ASSERTION_LINE_RE.test(trimmed)) count += 1;
|
|
669
|
+
}
|
|
670
|
+
return count;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* DET-08: Edit-Time Test-Weakening, Empty-Catch, Lazy-Elision & Destructive-Shrinkage Guard.
|
|
569
675
|
*/
|
|
570
676
|
export function evaluateDet08EditIntegrityGuard(params = {}) {
|
|
571
677
|
const toolName = String(params.toolName || '');
|
|
@@ -603,33 +709,84 @@ export function evaluateDet08EditIntegrityGuard(params = {}) {
|
|
|
603
709
|
const combinedNew = pairs.map((p) => p.newText).join('\n');
|
|
604
710
|
const checkTestSkip = params.checkTestSkip !== false && TEST_FILE_PATH_RE.test(normPath);
|
|
605
711
|
const checkEmptyCatch = params.checkEmptyCatch !== false;
|
|
712
|
+
const checkLazyElision = params.checkLazyElision !== false;
|
|
713
|
+
const checkDestructiveShrink = params.checkDestructiveShrink !== false;
|
|
606
714
|
|
|
607
715
|
const newSkipsAdded =
|
|
608
716
|
checkTestSkip && countTestWeakeningMarkers(combinedNew) > countTestWeakeningMarkers(combinedOld);
|
|
609
717
|
const newEmptyCatchAdded =
|
|
610
718
|
checkEmptyCatch &&
|
|
611
719
|
countEmptyCatchBlocks(combinedNew, normPath) > countEmptyCatchBlocks(combinedOld, normPath);
|
|
612
|
-
|
|
613
|
-
|
|
720
|
+
const newLazyElisionAdded =
|
|
721
|
+
checkLazyElision &&
|
|
722
|
+
countLazyElisionMarkers(combinedNew) > countLazyElisionMarkers(combinedOld);
|
|
723
|
+
|
|
724
|
+
const oldNonEmpty = countNonEmptyLines(combinedOld);
|
|
725
|
+
const newNonEmpty = countNonEmptyLines(combinedNew);
|
|
726
|
+
const newStubsAdded = countStubMarkers(combinedNew) > countStubMarkers(combinedOld);
|
|
727
|
+
const severeShrink =
|
|
728
|
+
checkDestructiveShrink &&
|
|
729
|
+
oldNonEmpty >= 50 &&
|
|
730
|
+
(newNonEmpty < Math.floor(oldNonEmpty * 0.4) ||
|
|
731
|
+
(newNonEmpty < Math.floor(oldNonEmpty * 0.55) && (newLazyElisionAdded || newStubsAdded)));
|
|
732
|
+
|
|
733
|
+
const dropDecision = resolvePhase5Decision(
|
|
734
|
+
params.assertionDropAction ?? PHASE5_DEFAULTS.det08AssertionDropAction,
|
|
735
|
+
guardMode
|
|
736
|
+
);
|
|
737
|
+
const oldAssertions = countTestAssertions(combinedOld);
|
|
738
|
+
const newAssertions = countTestAssertions(combinedNew);
|
|
739
|
+
const assertionDrop =
|
|
740
|
+
params.checkAssertionDrop !== false &&
|
|
741
|
+
TEST_FILE_PATH_RE.test(normPath) &&
|
|
742
|
+
dropDecision !== 'allow' &&
|
|
743
|
+
oldAssertions >= 4 &&
|
|
744
|
+
newAssertions <= Math.floor(oldAssertions * 0.5) &&
|
|
745
|
+
!severeShrink;
|
|
746
|
+
|
|
747
|
+
if (!newSkipsAdded && !newEmptyCatchAdded && !newLazyElisionAdded && !severeShrink && !assertionDrop) {
|
|
614
748
|
return basePass;
|
|
615
749
|
}
|
|
616
750
|
|
|
751
|
+
const assertionDropOnly =
|
|
752
|
+
assertionDrop && !newSkipsAdded && !newEmptyCatchAdded && !newLazyElisionAdded && !severeShrink;
|
|
753
|
+
|
|
754
|
+
const activeFlags = [];
|
|
755
|
+
if (newSkipsAdded) activeFlags.push('TEST_WEAKENING');
|
|
756
|
+
if (newEmptyCatchAdded) activeFlags.push('EMPTY_CATCH_BLOCK');
|
|
757
|
+
if (newLazyElisionAdded) activeFlags.push('LAZY_ELISION');
|
|
758
|
+
if (severeShrink) activeFlags.push('DESTRUCTIVE_SHRINKAGE');
|
|
759
|
+
if (assertionDrop) activeFlags.push('ASSERTION_COUNT_DROP');
|
|
760
|
+
|
|
617
761
|
const subType =
|
|
618
|
-
|
|
619
|
-
? '
|
|
620
|
-
: newSkipsAdded
|
|
621
|
-
? '
|
|
622
|
-
:
|
|
762
|
+
assertionDropOnly
|
|
763
|
+
? 'ASSERTION_COUNT_DROP'
|
|
764
|
+
: newSkipsAdded && newEmptyCatchAdded && activeFlags.length === 2
|
|
765
|
+
? 'BOTH'
|
|
766
|
+
: activeFlags.length === 1
|
|
767
|
+
? activeFlags[0]
|
|
768
|
+
: newSkipsAdded && activeFlags.every((f) => f === 'TEST_WEAKENING' || f === 'ASSERTION_COUNT_DROP')
|
|
769
|
+
? 'TEST_WEAKENING'
|
|
770
|
+
: 'MULTI';
|
|
623
771
|
|
|
624
772
|
const findings = [];
|
|
625
773
|
if (newSkipsAdded) findings.push('skipped/disabled tests (.skip/.only/xit/pytest.skip)');
|
|
626
774
|
if (newEmptyCatchAdded) findings.push('empty catch / bare except-pass error swallowing');
|
|
775
|
+
if (newLazyElisionAdded) findings.push('lazy elision placeholder comments');
|
|
776
|
+
if (severeShrink) {
|
|
777
|
+
const shrinkPct = Math.round((1 - newNonEmpty / Math.max(1, oldNonEmpty)) * 100);
|
|
778
|
+
findings.push(`destructive code shrinkage (${oldNonEmpty} -> ${newNonEmpty} non-empty lines, -${shrinkPct}%)`);
|
|
779
|
+
}
|
|
780
|
+
if (assertionDrop) {
|
|
781
|
+
findings.push(`assertion count drop (${oldAssertions} -> ${newAssertions} assertions)`);
|
|
782
|
+
}
|
|
627
783
|
|
|
628
784
|
const commentHint = /\.py$/i.test(normPath) ? '# ignore: <reason>' : '// ignore: <reason>';
|
|
629
785
|
const reason =
|
|
630
786
|
`[Burnoff DET-08 Edit Integrity Guard] Detected newly introduced ${findings.join(' and ')} in "${path.basename(filePath)}". ` +
|
|
631
|
-
`
|
|
632
|
-
const
|
|
787
|
+
`Emit complete code edits without elision placeholders, keep test coverage intact, and log or comment ("${commentHint}") intentional error handlers.`;
|
|
788
|
+
const effectiveDecision = assertionDropOnly ? dropDecision : resolvedDecision;
|
|
789
|
+
const finalDecision = effectiveDecision === 'advisory' ? 'allow' : effectiveDecision;
|
|
633
790
|
|
|
634
791
|
return {
|
|
635
792
|
detectorId: 'DET-08',
|
|
@@ -642,6 +799,102 @@ export function evaluateDet08EditIntegrityGuard(params = {}) {
|
|
|
642
799
|
};
|
|
643
800
|
}
|
|
644
801
|
|
|
802
|
+
/**
|
|
803
|
+
* DET-10: Full-File Rewrite Regurgitation Guard.
|
|
804
|
+
* Flags full-file `Write` operations on existing >=200-line files when >=85% of lines are unchanged.
|
|
805
|
+
*/
|
|
806
|
+
export function evaluateDet10FullFileRewriteGuard(params = {}) {
|
|
807
|
+
const toolName = String(params.toolName || '');
|
|
808
|
+
const filePath = String(params.filePath || '').trim();
|
|
809
|
+
const basePass = {
|
|
810
|
+
detectorId: 'DET-10',
|
|
811
|
+
triggered: false,
|
|
812
|
+
decision: 'allow',
|
|
813
|
+
subType: null,
|
|
814
|
+
unchangedRatio: 0,
|
|
815
|
+
changedLines: 0,
|
|
816
|
+
reason: null,
|
|
817
|
+
additionalContext: null
|
|
818
|
+
};
|
|
819
|
+
|
|
820
|
+
if (!filePath || !/^(?:Write|write_file|write_to_file)$/i.test(toolName) || isExemptMcpConfigFile(filePath)) {
|
|
821
|
+
return basePass;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
const guardMode = params.mode ?? params.flightMode ?? 'guard';
|
|
825
|
+
const resolvedDecision = resolvePhase5Decision(params.action ?? PHASE5_DEFAULTS.det10Action, guardMode);
|
|
826
|
+
if (resolvedDecision === 'allow') {
|
|
827
|
+
return basePass;
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
const toolInput = params.toolInput || {};
|
|
831
|
+
const writeContent =
|
|
832
|
+
toolInput.content ?? toolInput.Content ?? toolInput.CodeContent ?? toolInput.new_source;
|
|
833
|
+
if (typeof writeContent !== 'string' || writeContent.length === 0) {
|
|
834
|
+
return basePass;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
const baseDir = params.cwd ? path.resolve(String(params.cwd)) : process.cwd();
|
|
838
|
+
const absPath = path.isAbsolute(filePath) ? path.resolve(filePath) : path.resolve(baseDir, filePath);
|
|
839
|
+
let oldText = '';
|
|
840
|
+
try {
|
|
841
|
+
if (!fs.existsSync(absPath)) return basePass;
|
|
842
|
+
const st = fs.statSync(absPath);
|
|
843
|
+
if (!st.isFile() || st.size === 0 || st.size > 524_288) return basePass;
|
|
844
|
+
oldText = fs.readFileSync(absPath, 'utf8');
|
|
845
|
+
} catch {
|
|
846
|
+
return basePass; // ignore: unreadable existing target falls back to allow
|
|
847
|
+
}
|
|
848
|
+
if (oldText.includes('\0')) return basePass;
|
|
849
|
+
|
|
850
|
+
const oldLines = oldText.replace(/\r\n/g, '\n').split('\n');
|
|
851
|
+
if (oldLines.length < 200) {
|
|
852
|
+
return basePass;
|
|
853
|
+
}
|
|
854
|
+
const newLines = writeContent.replace(/\r\n/g, '\n').split('\n');
|
|
855
|
+
|
|
856
|
+
const counts = new Map();
|
|
857
|
+
for (const line of oldLines) {
|
|
858
|
+
counts.set(line, (counts.get(line) || 0) + 1);
|
|
859
|
+
}
|
|
860
|
+
let sharedLines = 0;
|
|
861
|
+
for (const line of newLines) {
|
|
862
|
+
const c = counts.get(line) || 0;
|
|
863
|
+
if (c > 0) {
|
|
864
|
+
sharedLines += 1;
|
|
865
|
+
counts.set(line, c - 1);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
const unchangedRatio = sharedLines / oldLines.length;
|
|
870
|
+
const changedLines = Math.max(oldLines.length, newLines.length) - sharedLines;
|
|
871
|
+
const maxChangedAllowed = Math.max(60, Math.ceil(oldLines.length * 0.15));
|
|
872
|
+
|
|
873
|
+
if (unchangedRatio < 0.85 || changedLines > maxChangedAllowed) {
|
|
874
|
+
return basePass;
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
const pct = Math.round(unchangedRatio * 100);
|
|
878
|
+
const estTok = Math.ceil(writeContent.length / 4);
|
|
879
|
+
const reason =
|
|
880
|
+
`[Burnoff DET-10 Full-File Rewrite Guard] ${toolName} rewrites ${newLines.length} lines (~${estTok.toLocaleString('en-US')} output tok) ` +
|
|
881
|
+
`of "${path.basename(filePath)}" with ${pct}% (${sharedLines}/${oldLines.length}) unchanged lines (~${changedLines} changed). ` +
|
|
882
|
+
`Use targeted Edit / MultiEdit hunks instead of regurgitating the entire file.`;
|
|
883
|
+
const finalDecision = resolvedDecision === 'advisory' ? 'allow' : resolvedDecision;
|
|
884
|
+
|
|
885
|
+
return {
|
|
886
|
+
detectorId: 'DET-10',
|
|
887
|
+
triggered: true,
|
|
888
|
+
decision: finalDecision,
|
|
889
|
+
subType: 'FULL_FILE_REWRITE',
|
|
890
|
+
filePath,
|
|
891
|
+
unchangedRatio: Number(unchangedRatio.toFixed(4)),
|
|
892
|
+
changedLines,
|
|
893
|
+
reason,
|
|
894
|
+
additionalContext: finalDecision === 'allow' ? reason : null
|
|
895
|
+
};
|
|
896
|
+
}
|
|
897
|
+
|
|
645
898
|
/**
|
|
646
899
|
* DET-09: Same-File Rapid Edit-Thrash Breaker.
|
|
647
900
|
*/
|
|
@@ -723,5 +976,6 @@ export default {
|
|
|
723
976
|
normalizeEditThrashPath,
|
|
724
977
|
evaluateDet07CommandOutputGuard,
|
|
725
978
|
evaluateDet08EditIntegrityGuard,
|
|
726
|
-
evaluateDet09EditThrash
|
|
979
|
+
evaluateDet09EditThrash,
|
|
980
|
+
evaluateDet10FullFileRewriteGuard
|
|
727
981
|
};
|