buildproof 0.0.0-stage → 3.7.2

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/core/gate.js ADDED
@@ -0,0 +1,193 @@
1
+ 'use strict';
2
+ /**
3
+ * Fail-closed proof gate.
4
+ * A check counts only if it REALLY ran: finished in time, real exit code, and (for tests) at least one test executed.
5
+ * Anything missing, skipped, timed out or "no tests found" = NOT PROVEN. Never "done" by default.
6
+ */
7
+
8
+ /** Best-effort test count from common runners. Returns {passed, failed, total} or null when unknown. */
9
+ function testCounts(output) {
10
+ const s = String(output || '').replace(/\x1b\[[0-9;]*m/g, '');
11
+ let m;
12
+ // the runner prints its summary LAST: a test that prints a fake "# pass 999" earlier must not count
13
+ const last = (re) => { const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g'); let x = null; let y; while ((y = g.exec(s))) { x = y; if (y[0] === '') g.lastIndex++; } return x; };
14
+ // ---- other languages first (their summaries are exact) ----
15
+ const sumAll = (re, f) => { const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g'); let y, acc = null; while ((y = g.exec(s))) { const v = f(y); acc = acc ? { passed: acc.passed + v.passed, failed: acc.failed + v.failed } : v; } return acc && { ...acc, total: acc.passed + acc.failed }; };
16
+ // Go (go test -v): one "--- PASS: / --- FAIL:" line per test and subtest
17
+ if (/^\s*--- (PASS|FAIL|SKIP): /m.test(s) || /^(ok|FAIL|\?)\s+\S+\s/m.test(s) && /^=== RUN/m.test(s)) {
18
+ const passed = (s.match(/^\s*--- PASS: /gm) || []).length; const failed = (s.match(/^\s*--- FAIL: /gm) || []).length;
19
+ return { passed, failed, total: passed + failed };
20
+ }
21
+ // Rust (cargo test): "test result: ok. 3 passed; 0 failed; 1 ignored" per test binary -> summed
22
+ if ((m = sumAll(/^test result: (?:ok|FAILED)\. (\d+) passed; (\d+) failed/m, (y) => ({ passed: +y[1], failed: +y[2] })))) return m;
23
+ // .NET (dotnet test): "Passed! - Failed: 0, Passed: 3, Skipped: 0, Total: 3" per test project -> summed
24
+ if ((m = sumAll(/(?:Passed|Failed)!\s+-\s+Failed:\s+(\d+),\s+Passed:\s+(\d+),/m, (y) => ({ passed: +y[2], failed: +y[1] })))) return m;
25
+ // Maven / Gradle JUnit XML: last "Tests run: N, Failures: F, Errors: E, Skipped: S" = the total
26
+ if ((m = last(/Tests run: (\d+), Failures: (\d+), Errors: (\d+)(?:, Skipped: (\d+))?/))) { const sk = +(m[4] || 0); const failed = +m[2] + +m[3]; return { passed: +m[1] - failed - sk, failed, total: +m[1] - sk }; }
27
+ // RSpec: "12 examples, 1 failure, 2 pending"
28
+ if ((m = last(/^(\d+) examples?, (\d+) failures?(?:, (\d+) pending)?/m))) { const pend = +(m[3] || 0); return { passed: +m[1] - +m[2] - pend, failed: +m[2], total: +m[1] - pend }; }
29
+ // Minitest: "3 runs, 5 assertions, 1 failures, 0 errors, 1 skips"
30
+ if ((m = last(/^(\d+) runs, \d+ assertions, (\d+) failures, (\d+) errors, (\d+) skips/m))) { const failed = +m[2] + +m[3]; const t = +m[1] - +m[4]; return { passed: t - failed, failed, total: t }; }
31
+ // PHPUnit: "OK (3 tests, 5 assertions)" / "Tests: 4, Assertions: 6, Failures: 1, Errors: 1, Skipped: 1."
32
+ if ((m = last(/^OK \((\d+) tests?, \d+ assertions?\)/m))) return { passed: +m[1], failed: 0, total: +m[1] };
33
+ if ((m = last(/^Tests: (\d+), Assertions: \d+([^\r\n]*)/m))) { const g = (k) => +((m[2].match(new RegExp(k + ': (\\d+)')) || [0, 0])[1]); const failed = g('Failures') + g('Errors'); const t = +m[1] - g('Skipped') - g('Incomplete'); return { passed: t - failed, failed, total: t }; }
34
+ // Jest: "Tests: 1 failed, 41 passed, 42 total"
35
+ if ((m = last(/Tests:\s+(.*?)(\d+) total/))) {
36
+ const passed = +(m[1].match(/(\d+) passed/) || [0, 0])[1];
37
+ const failed = +(m[1].match(/(\d+) failed/) || [0, 0])[1];
38
+ return { passed, failed, total: +m[2] };
39
+ }
40
+ // Vitest: "Tests 41 passed | 1 failed (42)"
41
+ if ((m = last(/Tests\s+(.*?)\((\d+)\)/))) {
42
+ const passed = +(m[1].match(/(\d+) passed/) || [0, 0])[1];
43
+ const failed = +(m[1].match(/(\d+) failed/) || [0, 0])[1];
44
+ return { passed, failed, total: +m[2] };
45
+ }
46
+ // node --test / TAP: "# pass 42" "# fail 0"
47
+ if ((m = last(/^# pass (\d+)/m))) {
48
+ const failed = +((last(/^# fail (\d+)/m) || [0, 0])[1]);
49
+ return { passed: +m[1], failed, total: +m[1] + failed };
50
+ }
51
+ // Mocha: "42 passing" "1 failing"
52
+ if ((m = last(/(\d+) passing/))) {
53
+ const failed = +((last(/(\d+) failing/) || [0, 0])[1]);
54
+ return { passed: +m[1], failed, total: +m[1] + failed };
55
+ }
56
+ // unittest: "Ran 42 tests in 0.01s" ... "OK" / "FAILED (failures=1, errors=1)"
57
+ if ((m = last(/^Ran (\d+) tests? in [\d.]+s/m))) {
58
+ const total = +m[1];
59
+ const f = s.match(/FAILED \(([^)]*)\)/);
60
+ const failed = f ? ((+(f[1].match(/failures=(\d+)/) || [0, 0])[1]) + (+(f[1].match(/errors=(\d+)/) || [0, 0])[1])) : 0;
61
+ const skipped = +((s.match(/skipped=(\d+)/) || [0, 0])[1]);
62
+ return { passed: total - failed - skipped, failed, total: total - skipped };
63
+ }
64
+ // pytest: "== 41 passed, 1 failed in 0.12s =="
65
+ if ((m = last(/=+ (.*?) in [\d.]+s/)) && /passed|failed|error|no tests ran/.test(m[1])) {
66
+ const passed = +(m[1].match(/(\d+) passed/) || [0, 0])[1];
67
+ const failed = +(m[1].match(/(\d+) failed/) || [0, 0])[1] + +(m[1].match(/(\d+) error/) || [0, 0])[1];
68
+ return { passed, failed, total: passed + failed };
69
+ }
70
+ return null;
71
+ }
72
+
73
+ /**
74
+ * Names of the failing tests, so changes can be judged test by test
75
+ * (a project with old, unrelated failures can still get a proven fix).
76
+ * known=false when the runner output could not be read reliably.
77
+ */
78
+ function failedTests(output, counts) {
79
+ const s = String(output || '').replace(/\x1b\[[0-9;]*m/g, '').replace(/\r/g, '');
80
+ const names = [];
81
+ let m;
82
+ const tap = /^\s*not ok \d+ - (.+?)(?:\s+#\s*(?:SKIP|TODO).*)?$/gm;
83
+ while ((m = tap.exec(s))) names.push(m[1].trim());
84
+ if (!names.length) { const re = /^\s*●\s+(.+?)\s*$/gm; while ((m = re.exec(s))) if (!/Test suite failed to run|Console$/.test(m[1])) names.push(m[1]); }
85
+ if (!names.length) { const re = /^(?:FAILED|ERROR) (\S+::\S+)/gm; while ((m = re.exec(s))) names.push(m[1]); }
86
+ if (!names.length) { const re = /^(?:FAIL|ERROR): (\w+) \(([\w.]+)\)/gm; while ((m = re.exec(s))) names.push(`${m[2]}.${m[1]}`); }
87
+ if (!names.length) { const re = /^\s*(?:×|✗)\s+(.+?)(?:\s+\d+ms)?$/gm; while ((m = re.exec(s))) names.push(m[1]); }
88
+ if (!names.length) { const re = /^\s*--- FAIL: (\S+)/gm; while ((m = re.exec(s))) names.push(m[1]); } // Go
89
+ if (!names.length) { const re = /^test (\S+) \.\.\. FAILED$/gm; while ((m = re.exec(s))) names.push(m[1]); } // Rust
90
+ if (!names.length) { const re = /^\s+Failed ([\w.`+<>,]+) \[/gm; while ((m = re.exec(s))) names.push(m[1]); } // .NET
91
+ if (!names.length) { const re = /^\[ERROR\]\s+(\w[\w.$]*\.\w+)(?::\d+)?\s/gm; while ((m = re.exec(s))) names.push(m[1]); } // Maven / Gradle XML
92
+ if (!names.length) { const re = /^rspec \S+ # (.+)$/gm; while ((m = re.exec(s))) names.push(m[1]); } // RSpec
93
+ if (!names.length) { const re = /^\s*\d+\)\s+(?:Failure|Error):\s*\n(\w[\w:]*#\w+)/gm; while ((m = re.exec(s))) names.push(m[1]); } // Minitest
94
+ if (!names.length) { const re = /^\d+\) ([\w\\]+::\w+)/gm; while ((m = re.exec(s))) names.push(m[1]); } // PHPUnit
95
+ const uniq = [...new Set(names)];
96
+ const known = !!counts && (counts.failed === 0 ? true : uniq.length > 0);
97
+ return { known, failed: counts && counts.failed === 0 ? [] : uniq };
98
+ }
99
+
100
+ /** The failure block of each failing test (TAP / unittest), so the AI sees only what matters. */
101
+ function failureBlocks(output) {
102
+ const lines = String(output || '').replace(/\x1b\[[0-9;]*m/g, '').replace(/\r/g, '').split('\n');
103
+ const out = {};
104
+ for (let i = 0; i < lines.length; i++) {
105
+ let m = lines[i].match(/^(\s*)not ok \d+ - (.+?)(?:\s+#\s*(?:SKIP|TODO).*)?$/);
106
+ if (m) {
107
+ const block = [lines[i]];
108
+ for (let j = i + 1; j < lines.length && j < i + 60; j++) { block.push(lines[j]); if (lines[j].trim() === '...') break; }
109
+ out[m[2].trim()] = block.join('\n');
110
+ continue;
111
+ }
112
+ m = lines[i].match(/^(?:FAIL|ERROR): (\w+) \(([\w.]+)\)/);
113
+ if (m) {
114
+ const block = [lines[i]];
115
+ for (let j = i + 1; j < lines.length && j < i + 40; j++) { if (/^(=====|FAIL:|ERROR:|Ran \d+)/.test(lines[j])) break; block.push(lines[j]); }
116
+ out[`${m[2]}.${m[1]}`] = block.join('\n');
117
+ }
118
+ }
119
+ return out;
120
+ }
121
+
122
+ const minus = (a, b) => { const set = new Set(b); return a.filter((x) => !set.has(x)); };
123
+
124
+ const NO_TESTS = /no tests? (found|ran|were found)|^Ran 0 tests|No test files found|0 tests? (ran|executed)|Tests:\s+0 total|collected 0 items|--passWithNoTests/im;
125
+
126
+ /** Turn a raw command result into a gate result for one step. */
127
+ function evaluate(step, r, opts = {}) {
128
+ const counts = /test/.test(step) ? testCounts(r.output) : null;
129
+ let ran = true;
130
+ let reason = null;
131
+ if (r.timedOut) { ran = false; reason = 'timed_out'; }
132
+ else if (r.code == null || r.code === -1) { ran = false; reason = 'did_not_start'; }
133
+ else if (/test/.test(step) && (NO_TESTS.test(r.output || '') || (counts && counts.total === 0))) { ran = false; reason = 'no_tests_ran'; }
134
+ // languages whose test summary we know: no summary = we cannot see that tests ran (fail closed, never "passed" on the exit code alone)
135
+ else if (/test/.test(step) && opts.strictCounts && !counts) { ran = false; reason = 'test_results_not_found'; }
136
+ const pass = ran && r.ok;
137
+ const ft = counts ? failedTests(r.output, counts) : null;
138
+ return { pass, ran, reason, code: r.code, ms: r.ms, timedOut: !!r.timedOut, tests: counts, failedTests: ft && ft.known ? ft.failed : null };
139
+ }
140
+
141
+ /**
142
+ * Compare baseline and after.
143
+ * @param {object} baseline step -> gate result (before change)
144
+ * @param {object} after step -> gate result (after change)
145
+ * @param {string[]} expected steps that MUST have run
146
+ * @param {boolean} isFix if true every step must pass at the end
147
+ */
148
+ function judge(baseline, after, expected, isFix) {
149
+ const steps = expected && expected.length ? expected : Object.keys(baseline);
150
+ const missing = steps.filter((s) => !after[s]);
151
+ const notRun = steps.filter((s) => after[s] && after[s].ran === false);
152
+ // Test-level view where both sides list their failing tests.
153
+ const testLevel = {};
154
+ for (const s of steps) {
155
+ const b = baseline[s]; const a = after[s];
156
+ if (!b || !a || !Array.isArray(b.failedTests) || !Array.isArray(a.failedTests) || b.ran === false || a.ran === false) continue;
157
+ testLevel[s] = { newFailures: minus(a.failedTests, b.failedTests), fixed: minus(b.failedTests, a.failedTests), remaining: a.failedTests.slice() };
158
+ }
159
+ const regressions = steps.filter((s) => {
160
+ if (testLevel[s]) return testLevel[s].newFailures.length > 0;
161
+ return baseline[s] && baseline[s].pass && after[s] && !after[s].pass;
162
+ });
163
+ // A step still counts as failing for a fix unless, test by test, something was fixed and nothing new broke.
164
+ const stillFailing = steps.filter((s) => after[s] && !after[s].pass && !(testLevel[s] && testLevel[s].fixed.length > 0 && testLevel[s].newFailures.length === 0));
165
+ const fixedNow = steps.filter((s) => baseline[s] && !baseline[s].pass && after[s] && (after[s].pass || (testLevel[s] && testLevel[s].fixed.length > 0)));
166
+ const preExisting = steps.reduce((n, s) => n + (testLevel[s] && !after[s].pass ? testLevel[s].remaining.length : 0), 0);
167
+ const fewerTests = steps.filter((s) => {
168
+ const b = baseline[s] && baseline[s].tests; const a = after[s] && after[s].tests;
169
+ return b && a && a.total < b.total;
170
+ });
171
+ const proven = steps.length > 0 && missing.length === 0 && notRun.length === 0;
172
+ const ok = proven && regressions.length === 0 && fewerTests.length === 0 && (isFix ? stillFailing.length === 0 : true);
173
+ return { ok, proven, regressions, stillFailing, fixedNow, missing, notRun, fewerTests, steps, testLevel, preExisting };
174
+ }
175
+
176
+ /** One human sentence for why something is not accepted. */
177
+ function whyNot(v, integrity) {
178
+ if (integrity && !integrity.clean) return `Checks were weakened: ${integrity.findings.map((f) => f.text.toLowerCase()).join('; ')}`;
179
+ if (!v) return 'No working change was found';
180
+ if (!v.steps.length) return 'The project has no build or test script, so nothing can be proven';
181
+ if (v.missing.length) return `Checks did not run: ${v.missing.join(', ')}`;
182
+ if (v.notRun.length) return `Checks did not really run: ${v.notRun.join(', ')}`;
183
+ if (v.fewerTests.length) return `Fewer tests ran than before in: ${v.fewerTests.join(', ')}`;
184
+ if (v.targetStill && v.targetStill.length) return `The task's own test still fails: ${v.targetStill.slice(0, 3).join('; ')}`;
185
+ if (v.regressions.length) {
186
+ const names = v.regressions.flatMap((s) => (v.testLevel && v.testLevel[s] ? v.testLevel[s].newFailures : [])).slice(0, 3);
187
+ return `The change broke: ${v.regressions.join(', ')}${names.length ? ' (' + names.join('; ') + ')' : ''}`;
188
+ }
189
+ if (v.stillFailing.length) return `Still failing: ${v.stillFailing.join(', ')}`;
190
+ return 'Not proven';
191
+ }
192
+
193
+ module.exports = { testCounts, failedTests, failureBlocks, evaluate, judge, whyNot, NO_TESTS };
package/core/hooks.js ADDED
@@ -0,0 +1,120 @@
1
+ 'use strict';
2
+ /**
3
+ * One-tap connection of AI tools and git to the BuildProof guard.
4
+ * git .git/hooks/pre-commit -> buildproof check --hook=git (commit blocked when not proven)
5
+ * Claude Code .claude/settings.local.json -> UserPromptSubmit: start guard, Stop: check (exit 2 sends the reason back to Claude)
6
+ * Cursor .cursor/hooks.json -> beforeSubmitPrompt: start guard, stop: check (followup_message back to the agent)
7
+ * Every existing file is backed up first (<file>.bp-backup) and merged, never overwritten blindly.
8
+ */
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+ const { ROOT } = require('./config');
12
+
13
+ const TOOLS = ['git', 'claude', 'cursor'];
14
+ const MARK = 'buildproof';
15
+
16
+ function cli() { return path.join(ROOT, 'bin', 'buildproof.js'); }
17
+ function q(p) { return `"${p}"`; }
18
+ function cmd(args) { return `${q(process.execPath)} ${q(cli())} ${args}`; }
19
+ function shPath(p) { return p.replace(/\\/g, '/'); }
20
+
21
+ function readJson(f) { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch { return null; } }
22
+ function backup(f) { if (fs.existsSync(f) && !fs.existsSync(f + '.bp-backup')) fs.copyFileSync(f, f + '.bp-backup'); }
23
+ function writeJson(f, obj) { fs.mkdirSync(path.dirname(f), { recursive: true }); backup(f); fs.writeFileSync(f, JSON.stringify(obj, null, 2) + '\n'); }
24
+
25
+ function paths(root) {
26
+ return {
27
+ git: path.join(root, '.git', 'hooks', 'pre-commit'),
28
+ claude: path.join(root, '.claude', 'settings.local.json'),
29
+ cursor: path.join(root, '.cursor', 'hooks.json'),
30
+ };
31
+ }
32
+
33
+ function status(root) {
34
+ const p = paths(root);
35
+ const has = (f) => { try { return fs.readFileSync(f, 'utf8').toLowerCase().includes(MARK); } catch { return false; } };
36
+ return {
37
+ git: { available: fs.existsSync(path.join(root, '.git')), connected: has(p.git) },
38
+ claude: { available: true, connected: has(p.claude) },
39
+ cursor: { available: true, connected: has(p.cursor) },
40
+ };
41
+ }
42
+
43
+ function connectGit(root) {
44
+ const f = paths(root).git;
45
+ if (!fs.existsSync(path.join(root, '.git'))) return { ok: false, error: 'not_a_git_repo' };
46
+ fs.mkdirSync(path.dirname(f), { recursive: true });
47
+ const prev = fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : '';
48
+ if (prev.toLowerCase().includes(MARK)) return { ok: true, already: true };
49
+ if (prev) fs.renameSync(f, f + '.bp-backup');
50
+ const script = [
51
+ '#!/bin/sh',
52
+ '# buildproof: block the commit when the guarded change is not proven',
53
+ `${q(shPath(process.execPath))} ${q(shPath(cli()))} check --hook=git || exit 1`,
54
+ prev ? 'if [ -x .git/hooks/pre-commit.bp-backup ]; then exec .git/hooks/pre-commit.bp-backup "$@"; fi' : '',
55
+ 'exit 0', '',
56
+ ].filter((l) => l !== '').join('\n') + '\n';
57
+ fs.writeFileSync(f, script, { mode: 0o755 });
58
+ return { ok: true };
59
+ }
60
+
61
+ function connectClaude(root) {
62
+ const f = paths(root).claude;
63
+ const j = readJson(f) || {};
64
+ j.hooks = j.hooks || {};
65
+ const add = (event, c) => {
66
+ j.hooks[event] = (j.hooks[event] || []).filter((g) => !JSON.stringify(g).toLowerCase().includes(MARK));
67
+ j.hooks[event].push({ hooks: [{ type: 'command', command: c, timeout: 1800 }] });
68
+ };
69
+ add('UserPromptSubmit', cmd('start --hook=claude'));
70
+ add('Stop', cmd('check --hook=claude'));
71
+ writeJson(f, j);
72
+ return { ok: true };
73
+ }
74
+
75
+ function connectCursor(root) {
76
+ const f = paths(root).cursor;
77
+ const j = readJson(f) || {};
78
+ j.version = j.version || 1;
79
+ j.hooks = j.hooks || {};
80
+ const add = (event, c) => {
81
+ j.hooks[event] = (j.hooks[event] || []).filter((h) => !String(h.command || '').toLowerCase().includes(MARK));
82
+ j.hooks[event].push({ command: c, timeout: 1800 });
83
+ };
84
+ add('beforeSubmitPrompt', cmd('start --hook=cursor'));
85
+ add('stop', cmd('check --hook=cursor'));
86
+ writeJson(f, j);
87
+ return { ok: true };
88
+ }
89
+
90
+ function disconnect(root, tool) {
91
+ const f = paths(root)[tool];
92
+ if (!f || !fs.existsSync(f)) return { ok: true };
93
+ if (tool === 'git') {
94
+ fs.unlinkSync(f);
95
+ if (fs.existsSync(f + '.bp-backup')) fs.renameSync(f + '.bp-backup', f);
96
+ return { ok: true };
97
+ }
98
+ const j = readJson(f);
99
+ if (!j || !j.hooks) return { ok: true };
100
+ for (const k of Object.keys(j.hooks)) {
101
+ j.hooks[k] = (j.hooks[k] || []).filter((h) => !JSON.stringify(h).toLowerCase().includes(MARK));
102
+ if (!j.hooks[k].length) delete j.hooks[k];
103
+ }
104
+ if (!Object.keys(j.hooks).length) delete j.hooks;
105
+ if (tool === 'cursor' && Object.keys(j).every((k) => k === 'version')) { fs.unlinkSync(f); return { ok: true }; }
106
+ fs.writeFileSync(f, JSON.stringify(j, null, 2) + '\n');
107
+ return { ok: true };
108
+ }
109
+
110
+ function connect(root, tools) {
111
+ const out = {};
112
+ for (const t of tools || []) {
113
+ if (!TOOLS.includes(t)) continue;
114
+ try { out[t] = t === 'git' ? connectGit(root) : t === 'claude' ? connectClaude(root) : connectCursor(root); }
115
+ catch (e) { out[t] = { ok: false, error: e.message }; }
116
+ }
117
+ return out;
118
+ }
119
+
120
+ module.exports = { connect, disconnect, status, TOOLS };
@@ -0,0 +1,321 @@
1
+ 'use strict';
2
+ /**
3
+ * Test-integrity guard: detects the ways AI tools "make tests pass" without fixing anything.
4
+ * Works on any change set (our own AI, Cursor, Claude Code, Copilot...). Deterministic, no AI.
5
+ *
6
+ * Rules (each one blocks "Proven"):
7
+ * test_deleted a test file was removed
8
+ * tests_removed a test file now has fewer test cases
9
+ * test_skipped .skip / xit / @pytest.mark.skip / @Disabled ... was added
10
+ * assertion_changed an existing assertion line was changed or removed
11
+ * mock_added a new mock / stub / patch appeared in a test
12
+ * sleep_added a sleep / timeout was added to source code (hides races)
13
+ * silent_catch an empty catch / except: pass was added (swallows failures)
14
+ * checker_silenced @ts-ignore / eslint-disable / noqa / type: ignore was added
15
+ * proof_script_changed the build/test/lint/typecheck script in package.json was changed
16
+ * test_config_changed test runner config changed to ignore or skip tests
17
+ * test_disabled a test now stops early / never reaches its checks (return;, if (false), process.exit)
18
+ * assertion_overridden assert / expect replaced so every check passes
19
+ * checker_weakened tsconfig / eslint config made less strict
20
+ * outside_link a project file now points outside the project (symlink)
21
+ * dependency_tampered a file inside node_modules / the virtualenv was edited (no install happened)
22
+ */
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+
26
+ const TEST_FILE = /(^|\/)(__tests__|tests?|spec|specs)\/|\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.(py|rb)$|_test\.(py|go|rb)$|_spec\.rb$|Tests?\.(cs|java|kt|php|fs|vb)$|(^|\/)conftest\.py$|(^|\/)[^/]*\.Tests?\/|(^|\/)src\/test\//i;
27
+ // Rust keeps unit tests inside the source file (#[cfg(test)] mod tests): such a file is checked as test AND as code
28
+ const INLINE_TESTS = /#\[cfg\(test\)\]|#\[test\]/;
29
+ const HOOK_FILE = /(^|\/)(\.claude\/settings[^/]*\.json|\.cursor\/hooks\.json|\.husky\/[^/]+|lefthook\.ya?ml|\.pre-commit-config\.ya?ml)$/i;
30
+ const PYPROJECT = /(^|\/)pyproject\.toml$/i;
31
+ const PY_TEST_CFG_RE = /addopts|--deselect|\s-k\s|collect_ignore|testpaths|norecursedirs|python_files|-p\s+no:/i;
32
+ const TEST_ENV_RE = /testing\.Testing\(\)|flag\.Lookup\(\s*"test\.|os\.Args\[0\][^\n]*\.test|cfg!\(test\)|(StackTrace|getStackTrace\(\))[^\n]*(junit|xunit|nunit|Test)|IsRunningInTest|defined\?\(RSpec\)|defined\?\(Minitest\)|RAILS_ENV['"]\]\s*==\s*['"]test|PHPUNIT_COMPOSER_INSTALL|defined\(\s*['"]PHPUNIT|class_exists\([^)]*PHPUnit|\$_SERVER\[['"]argv['"]\][^\n]*phpunit|process\.env\.(NODE_ENV\s*[!=]==?\s*['"]test|JEST_WORKER_ID|VITEST|NODE_TEST_CONTEXT|NODE_TEST_WORKER_ID|MOCHA_WORKER_ID)|process\.env\[\s*['"](NODE_ENV|JEST_WORKER_ID|VITEST|NODE_TEST_CONTEXT)['"]\s*\]|process\.argv\.(some|includes|indexOf|join|find|filter)\([^)]*(--test|test|spec|jest|mocha|vitest)|process\.execArgv|new\s+Error\(\)\.stack|require\.main\.filename|module\.parent\b|\b(globalThis|global|window)\.(describe|it|test|expect|jest|vi)\b|['"]PYTEST_CURRENT_TEST['"]|['"]pytest['"]\s+in\s+sys\.modules|sys\.modules\.get\(\s*['"]pytest|import\.meta\.vitest|typeof\s+(jest|describe|it|test|expect|vi)\b|os\.environ(\.get\(|\[)\s*['"](PYTEST_CURRENT_TEST|TESTING)|inspect\.stack\(\)|sys\._getframe/;
33
+ const LIT_RE = /-?\d+(?:\.\d+)?(?:e-?\d+)?|'(?:[^'\\]|\\.){1,80}'|"(?:[^"\\]|\\.){1,80}"|`[^`$]{1,80}`/g;
34
+ const TRIVIAL = new Set(['0', '1', '-1', '0.0', '1.0', "''", '""', '``', "'utf-8'", '"utf-8"', "'utf8'", '"utf8"']);
35
+ const CODE_EXT = /\.([cm]?[jt]sx?|py|go|cs|fs|vb|java|kt|scala|rb|php|rs|vue|svelte)$/i;
36
+ const TEST_CONFIG = /(^|\/)(jest|vitest|vite|playwright|cypress|karma|ava|babel)\.config\.[cm]?[jt]s$|(^|\/)(jest|vitest)\.config\.json$|(^|\/)(pytest\.ini|setup\.cfg|tox\.ini|\.mocharc[^/]*|\.babelrc[^/]*|conftest\.py)$/i;
37
+ // test data: snapshots and expected-output fixtures are expected values too
38
+ const TEST_DATA = /\.snap$|(^|\/)(__snapshots__|__fixtures__|fixtures?|expected|golden|testdata|snapshots)\//i;
39
+ const NPMRC = /(^|\/)(\.npmrc|\.yarnrc|\.yarnrc\.yml)$/i;
40
+ // build files of the other languages: a change that skips or ignores tests
41
+ const BUILD_CFG = /(^|\/)(pom\.xml|build\.gradle(\.kts)?|settings\.gradle(\.kts)?|gradle\.properties|Cargo\.toml|go\.mod|[^/]+\.(cs|fs|vb)proj|Directory\.Build\.(props|targets)|[^/]+\.runsettings|phpunit\.xml(\.dist)?|\.rspec|Rakefile|composer\.json|Gemfile|\.cargo\/config(\.toml)?)$/i;
42
+ const BUILD_WEAKEN_RE = /skipTests|maven\.test\.(skip|failure\.ignore)|testFailureIgnore|<exclude|<excludes|ignoreFailures|enabled\s*=\s*false|\bexclude\s*[\('"]|filter\s*\{|<IsTestProject>\s*false|--tag\s+~|--exclude|stopOnFailure|failOnRisky|<groups>|excludeGroups|"(test|phpunit|scripts)"\s*:|\[\[test\]\]|harness\s*=\s*false|\btest\s*=\s*false|-short|\brustflags\b|RunSettings|<TestCaseFilter|testcasefilter/i;
43
+ const NPMRC_RE = /node[-_]options|script[-_]shell|ignore[-_]scripts|NODE_OPTIONS|yarnPath/i;
44
+ const TSCONFIG = /(^|\/)(tsconfig[^/]*\.json|jsconfig\.json)$/i;
45
+ const TSCONFIG_RE = /"exclude"|"strict"\s*:\s*false|"noImplicitAny"\s*:\s*false|"skipLibCheck"\s*:\s*true|"checkJs"\s*:\s*false|"strictNullChecks"\s*:\s*false/;
46
+ const ESLINT = /(^|\/)(\.eslintrc[^/]*|eslint\.config\.[cm]?[jt]s|\.eslintignore|ruff\.toml|\.flake8|\.pylintrc|mypy\.ini)$/i;
47
+ const ESLINT_RE = /["']off["']|:\s*0\b|ignorePatterns|ignores|ignore\s*=|exclude|disable|extend-ignore|per-file-ignores|ignore_errors/i;
48
+ const IGNORE_LIST = /(^|\/)\.eslintignore$/i; // every new line there hides files from the linter
49
+ // a test that stops before its checks, or never runs them
50
+ const DISABLE_RE = /^return\s*(undefined|null|void 0)?;?$|\bif\s*\(\s*(false|0|null|undefined|!1|!true)\s*\)|\bprocess\.exit\s*\(\s*0?\s*\)|\bprocess\.exitCode\s*=\s*0|^if\s+(False|0)\s*:|\bsys\.exit\(\s*0?\s*\)|\bos\._exit\(\s*0/;
51
+ // assert / expect replaced: every check would pass
52
+ const OVERRIDE_RE = /(?<!(const|let|var)\s+)\bassert(\.\w+)?\s*=(?!=)|(?<!(const|let|var)\s+)\bexpect\s*=(?!=)|Object\.(defineProperty|assign)\(\s*(assert|expect|chai|require\(['"](node:)?assert)|require\(\s*['"](node:)?assert(\/strict)?['"]\s*\)\.\w+\s*=(?!=)|\b(unittest\.)?TestCase\.assert\w*\s*=(?!=)|\bself\.assert\w*\s*=(?!=)|\bAssertionError\s*=(?!=)|\bchai\.(assert|expect|should)\s*=(?!=)|\bbuiltins\.\w+\s*=(?!=)/;
53
+ // a file is also a test when it imports a test framework and declares test cases (whatever its name)
54
+ const FRAMEWORK_RE = /require\(\s*['"](node:test|vitest|chai|@jest\/globals|mocha|ava|uvu|tap)['"]\s*\)|from\s+['"](node:test|vitest|chai|@jest\/globals|mocha|ava|uvu|tap)['"]|^\s*import\s+(pytest|unittest)\b|^\s*from\s+(pytest|unittest)\b/m;
55
+ const NAMED_CASE_RE = /\b(it|test|describe|specify)\s*\(\s*['"`]|^\s*def\s+test_\w+\s*\(/m;
56
+
57
+ const CASE_RE = /\b(it|test|specify)(\.(only|skip|todo|concurrent|each\([^)]*\)))?\s*\(|^\s*def\s+test_|@Test\b|\[(Test|Fact|Theory|TestMethod|TestCase)\b|^\s*func\s+Test[A-Z]|^\s*#\[(tokio::)?test\]|^\s*(public\s+)?function\s+test\w*\s*\(|^\s*it\s+['"]|^\s*t\.Run\(/gm;
58
+ const SKIP_RE = /\b(it|test|describe|suite|context)\.(skip|todo|only)\s*\(|\b(xit|xtest|xdescribe|xcontext|fit|fdescribe)\s*\(|\.skip\s*\(\s*\)|\{\s*(skip|todo|only)\s*:\s*(true|['"`])|[,{]\s*(skip|todo)\s*:\s*(true|['"`])|\b(t|ctx|context)\.(skip|todo)\s*\(|pytest\.mark\.(skip|skipif|xfail)|pytest\.skip\(|unittest\.skip|self\.skipTest\(|@Disabled\b|@Ignore\b|\[Ignore\b|, ?Ignore\]|\[(Fact|Theory)\(Skip|t\.Skip(Now|f)?\(|this\.skip\(\)|#\[ignore\b|^\s*skip(\s|\(|$)|\bpending\b|\bxit\s|\bxdescribe\s|markTestSkipped\(|markTestIncomplete\(|@group\s+skip|Assume\.|assumeTrue\(/m;
59
+ const ASSERT_RE = /\b(expect|assert\w*|should)\b|\bt\.(equal|is|deepEqual|true|false|Error|Fatal)|\bAssert\.\w+|\bassert(_eq|_ne)?!|\$this->assert\w+|\bassert_\w+|\brefute\w*|\bif\b[^{]*(!=|==)[^{]*\{$|\.Should\(\)|\bassertThat\(/;
60
+ const MOCK_RE = /\bMockito\.(mock|when|spy)|@Mock\b|@MockBean\b|new Mock<|Substitute\.For<|A\.Fake<|gomock\.|mock\.Mock\b|mockall::|#\[automock\]|createMock\(|getMockBuilder\(|\ballow\([^)]*\)\.to receive|\bstub\(|\.stubs\(|instance_double\(|\b(t|test|context)\.mock\.|\bmock\.(method|fn|getter|setter|module|timers\.enable)\s*\(|\bmocker\.patch|\bmonkeypatch\.setattr\(|\b(jest|vi)\.(mock|spyOn|fn)\s*\(|\bsinon\.(stub|mock|fake|replace)|\bmock\.patch\b|@patch\(|\bMagicMock\(|\bMock\(|\bnock\(|\.mockImplementation|\.mockReturnValue|\bmockResolvedValue|\btd\.replace\(/;
61
+ const SLEEP_RE = /\btime\.Sleep\(|thread::sleep\(|tokio::time::sleep\(|\bu?sleep\(\s*\d|^\s*sleep\s*\(?\s*\d|\btime\.sleep\(|\bThread\.sleep\(|\bTask\.Delay\(|\basyncio\.sleep\(|\bsleep\s*\(\s*\d|new\s+Promise\s*\(\s*\(?\s*\w+\s*\)?\s*=>\s*setTimeout\(|\bawait\s+(delay|wait|sleep)\s*\(\s*\d|\bsetTimeout\s*\([^,]+,\s*\d{3,}/;
62
+ const SILENT_CATCH_RE = /catch\s*(\([^)]*\))?\s*\{\s*(\/\/[^\n]*\s*|\/\*[^*]*\*+(?:[^/*][^*]*\*+)*\/\s*)*(return\s*;?\s*)?\}|\.catch\s*\(\s*\(?[\w\s,]*\)?\s*=>\s*(\{\s*\}|null|undefined|void 0)\s*\)|except(\s+[\w.]+(\s+as\s+\w+)?)?\s*:\s*(pass|\.\.\.)\s*$|rescue\s*(=>\s*\w+)?\s*;?\s*nil\b|if\s+err\s*!=\s*nil\s*\{\s*\}|Err\(_\)\s*=>\s*(\{\s*\}|\(\))|\.unwrap_or_default\(\)|let\s+_\s*=\s*\w[\w.:]*\([^;]*\)\s*;|rescue\s+(StandardError|Exception)?\s*(=>\s*\w+)?\s*\n\s*end\b/m;
63
+ const SILENCE_RE = /@ts-(ignore|nocheck|expect-error)|eslint-disable|#\s*noqa|#\s*type:\s*ignore|#\s*pylint:\s*disable|\/\/\s*nolint|#pragma warning disable|@SuppressWarnings|#!?\[allow\(|#\s*rubocop:disable|@phpstan-ignore|@psalm-suppress|\[SuppressMessage|\/\/\s*NOSONAR/;
64
+ const PROOF_SCRIPTS = ['test', 'build', 'lint', 'typecheck', 'check', 'verify'];
65
+ const IGNORE_CFG_RE = /testPathIgnorePatterns|exclude|skip|ignore|passWithNoTests|testMatch|testRegex|include|collect_ignore|addopts|--deselect|-k\s|setupFiles|setupFilesAfterEnv|globalSetup|moduleNameMapper|transform|\brequire\b|--require|\s-r\s|plugins|bail|retry|retries|onlyChanged|coverageThreshold|pytest_collection_modifyitems|pytest_runtest|def\s+pytest_/i;
66
+
67
+ const RULE_TEXT = {
68
+ test_deleted: 'A test file was deleted',
69
+ tests_removed: 'Test cases were removed',
70
+ test_skipped: 'A test was skipped',
71
+ assertion_changed: 'An expected value in a test was changed',
72
+ mock_added: 'A new mock was added to a test',
73
+ sleep_added: 'A sleep / delay was added to the code',
74
+ silent_catch: 'An error is now silently swallowed',
75
+ checker_silenced: 'A type / lint check was silenced',
76
+ proof_script_changed: 'The build / test script itself was changed',
77
+ test_config_changed: 'Test config now ignores or skips tests',
78
+ hardcoded_answer: 'The code returns the exact answer the test expects',
79
+ test_detection: 'The code behaves differently when tests run',
80
+ guard_disabled: 'The BuildProof hook was removed or disabled',
81
+ test_disabled: 'A test now stops before its checks or never runs them',
82
+ assertion_overridden: 'assert / expect was replaced so every check passes',
83
+ checker_weakened: 'The type / lint settings were made less strict',
84
+ outside_link: 'A project file now points outside the project',
85
+ dependency_tampered: 'A file inside the installed packages was edited (no install happened)',
86
+ };
87
+ const RULES = Object.keys(RULE_TEXT);
88
+
89
+ function isTestFile(rel) { return TEST_FILE.test(rel); }
90
+ /** Test by name, or by content: imports a test framework and declares named test cases. */
91
+ function looksLikeTest(src) { const t = String(src || ''); return t.length < 400000 && FRAMEWORK_RE.test(t) && NAMED_CASE_RE.test(t); }
92
+ function isTestFileContent(rel, ...srcs) { return isTestFile(rel) || srcs.some(looksLikeTest); }
93
+ /** Scripts the proof scripts run (npm run x, run-s x, yarn x ...), followed through every level, plus their pre / post scripts. */
94
+ function proofScriptNames(scripts) {
95
+ const names = new Set(); const todo = PROOF_SCRIPTS.filter((s) => scripts[s]);
96
+ while (todo.length) {
97
+ const n = todo.shift(); if (names.has(n)) continue; names.add(n); names.add('pre' + n); names.add('post' + n);
98
+ const cmd = String(scripts[n] || '');
99
+ const re = /(?:npm(?:\s+run(?:-script)?)?|yarn(?:\s+run)?|pnpm(?:\s+run)?|bun\s+run|npm-run-all(?:\s+-[sp])?|run-s|run-p)\s+((?:[\w:.@/*-]+\s*)+)/g;
100
+ let m; while ((m = re.exec(cmd))) for (const x of m[1].split(/\s+/)) if (scripts[x] && !names.has(x)) todo.push(x);
101
+ }
102
+ return [...names];
103
+ }
104
+
105
+ function normLit(l) { return l.replace(/^`|`$/g, '"').replace(/^'|'$/g, '"'); }
106
+ function literals(line) { return (String(line).match(LIT_RE) || []).map(normLit); }
107
+
108
+ /** Literal groups from assertion lines of all test files: [['2','3','5'], ...] */
109
+ function assertionGroups(root, testFiles) {
110
+ const groups = [];
111
+ for (const f of (testFiles || []).slice(0, 400)) {
112
+ const src = read(path.join(root, f));
113
+ if (!src || src.length > 400000) continue;
114
+ for (const l of lines(src)) {
115
+ if (!ASSERT_RE.test(l)) continue;
116
+ const lits = literals(l).filter((x) => !TRIVIAL.has(x));
117
+ if (lits.length) groups.push(lits);
118
+ if (groups.length > 5000) return groups;
119
+ }
120
+ }
121
+ return groups;
122
+ }
123
+
124
+ /** A new source line that special-cases test data: 2+ literals from one assertion behind a condition, or a big expected literal returned directly. */
125
+ function hardcodedHit(addedLines, beforeSrc, groups) {
126
+ if (!groups.length) return null;
127
+ const beforeLits = new Set(literals(beforeSrc));
128
+ // a condition split over 2-3 lines ("if (a === 2 &&" / "b === 3) return 5") is checked as one line too
129
+ const windows = [];
130
+ // only a line that stops in the middle of an expression ("&&", "||", "(", ",") is joined with the next ones
131
+ const open = (l) => /(&&|\|\||\(|,|\?|:|===?|!==?)\s*$/.test(l);
132
+ for (let i = 0; i < addedLines.length; i++) {
133
+ windows.push(addedLines[i]);
134
+ if (open(addedLines[i]) && i + 1 < addedLines.length) { windows.push(addedLines[i] + ' ' + addedLines[i + 1]); if (open(addedLines[i + 1]) && i + 2 < addedLines.length) windows.push(addedLines.slice(i, i + 3).join(' ')); }
135
+ }
136
+ for (const l of windows) {
137
+ if (!/\bif\b|===?|\bcase\b|\?|\breturn\b|=>|\belif\b/.test(l)) continue;
138
+ const lits = new Set(literals(l).filter((x) => !TRIVIAL.has(x)));
139
+ if (!lits.size) continue;
140
+ for (const g of groups) {
141
+ const shared = g.filter((x) => lits.has(x));
142
+ const uniq = new Set(shared);
143
+ // equality with the test's own values = special-casing; a boundary (<, <=, >) on them is real logic
144
+ if (uniq.size >= 2 && /[^<>!=]==|\bcase\b/.test(l)) return l;
145
+ const exp = g[g.length - 1];
146
+ const big = /^-?\d+\.\d+$|^-?\d{3,}$/.test(exp) || (/^"/.test(exp) && exp.length >= 6);
147
+ if (big && lits.has(exp) && !beforeLits.has(exp)) {
148
+ const m = l.replace(LIT_RE, (x) => normLit(x)).match(/^(?:return\b|.*=>)\s*\(?\s*(.+?)\s*\)?\s*;?$/);
149
+ if (m && m[1] === exp) return l;
150
+ }
151
+ }
152
+ }
153
+ return null;
154
+ }
155
+
156
+ function read(abs) { try { return fs.readFileSync(abs, 'utf8'); } catch { return null; } }
157
+
158
+ function lines(s) { return String(s || '').split(/\r?\n/); }
159
+ const norm = (l) => l.trim().replace(/\s+/g, ' ');
160
+
161
+ /** Lines added / removed (multiset compare, order-insensitive, whitespace-normalised). */
162
+ function lineDelta(before, after) {
163
+ const count = new Map();
164
+ for (const l of lines(before)) { const k = norm(l); if (k) count.set(k, (count.get(k) || 0) + 1); }
165
+ const added = [];
166
+ for (const l of lines(after)) {
167
+ const k = norm(l);
168
+ if (!k) continue;
169
+ const c = count.get(k) || 0;
170
+ if (c > 0) count.set(k, c - 1); else added.push(k);
171
+ }
172
+ const removed = [];
173
+ for (const [k, c] of count) for (let i = 0; i < c; i++) removed.push(k);
174
+ return { added, removed };
175
+ }
176
+
177
+ function countCases(src) { return (String(src || '').match(CASE_RE) || []).length; }
178
+
179
+ function jsonScripts(src) { try { return JSON.parse(src).scripts || {}; } catch { return null; } }
180
+
181
+ /**
182
+ * @param {object} o
183
+ * @param {string} o.root project folder (current files)
184
+ * @param {string} o.beforeDir folder holding the pre-change copy (same relative layout)
185
+ * @param {Array<{file:string,kind:'added'|'modified'|'deleted'}>} o.changes
186
+ * @returns {{clean:boolean, findings:Array<{rule,file,detail,text}>, rulesChecked:string[], filesChecked:number}}
187
+ */
188
+ function analyze({ root, beforeDir, changes, testFiles }) {
189
+ const findings = [];
190
+ let groups = null;
191
+ // expected values come from the test files, and from Rust files that hold their own tests
192
+ const inlineFiles = (changes || []).filter((c) => c.kind !== 'deleted' && /\.rs$/i.test(c.file) && INLINE_TESTS.test(read(path.join(root, c.file)) || '')).map((c) => c.file);
193
+ const getGroups = () => (groups || (groups = assertionGroups(root, [...(testFiles || []), ...inlineFiles])));
194
+ const add = (rule, file, detail) => findings.push({ rule, file, detail: String(detail || '').slice(0, 200), text: RULE_TEXT[rule] });
195
+ for (const c of changes || []) {
196
+ const rel = c.file;
197
+ const before = c.kind === 'added' ? '' : read(path.join(beforeDir, rel));
198
+ const after = c.kind === 'deleted' ? null : read(path.join(root, rel));
199
+ const isTest = isTestFile(rel);
200
+
201
+ if (c.link) { add('outside_link', rel, c.link); continue; }
202
+ if (HOOK_FILE.test(rel)) {
203
+ if (/buildproof/i.test(before || '') && !/buildproof/i.test(after || '')) add('guard_disabled', rel, c.kind === 'deleted' ? 'file deleted' : 'buildproof hook removed');
204
+ else if (/"disableAllHooks"\s*:\s*true/.test(after || '') && !/"disableAllHooks"\s*:\s*true/.test(before || '')) add('guard_disabled', rel, 'disableAllHooks: true');
205
+ continue;
206
+ }
207
+ if (/(^|\/)\.claude\/settings[^/]*\.json$/i.test(rel)) continue;
208
+ if (NPMRC.test(rel)) {
209
+ const hit = lineDelta(before || '', after || '').added.find((l) => NPMRC_RE.test(l));
210
+ if (hit) add('proof_script_changed', rel, hit);
211
+ continue;
212
+ }
213
+ if (BUILD_CFG.test(rel)) {
214
+ const hit = lineDelta(before || '', after || '').added.find((l) => BUILD_WEAKEN_RE.test(l));
215
+ if (hit) add('test_config_changed', rel, hit);
216
+ continue;
217
+ }
218
+ if (TSCONFIG.test(rel)) {
219
+ const hit = lineDelta(before || '', after || '').added.find((l) => TSCONFIG_RE.test(l));
220
+ if (hit) add('checker_weakened', rel, hit);
221
+ continue;
222
+ }
223
+ if (ESLINT.test(rel)) {
224
+ const hit = lineDelta(before || '', after || '').added.find((l) => (IGNORE_LIST.test(rel) ? !/^#/.test(l) : ESLINT_RE.test(l)) && !/^[{}\[\],]+$/.test(l));
225
+ if (hit) add('checker_weakened', rel, hit);
226
+ continue;
227
+ }
228
+ if (TEST_DATA.test(rel) && !CODE_EXT.test(rel)) {
229
+ if (c.kind !== 'added') add('assertion_changed', rel, c.kind === 'deleted' ? 'expected test data deleted' : 'expected test data changed');
230
+ continue;
231
+ }
232
+ if (PYPROJECT.test(rel)) {
233
+ const d = lineDelta(before || '', after || '');
234
+ const hit = d.added.find((l) => PY_TEST_CFG_RE.test(l));
235
+ if (hit) add('test_config_changed', rel, hit);
236
+ continue;
237
+ }
238
+ if (/(^|\/)package\.json$/.test(rel) && before != null && after != null) {
239
+ const a = jsonScripts(before); const b = jsonScripts(after);
240
+ if (a && b) {
241
+ const watched = new Set([...proofScriptNames(a), ...PROOF_SCRIPTS.filter((s) => a[s]).flatMap((s) => ['pre' + s, 'post' + s])]);
242
+ for (const s of watched) if ((a[s] || '') !== (b[s] || '')) add('proof_script_changed', rel, `"${s}": "${a[s] || '(none)'}" -> "${b[s] || '(removed)'}"`);
243
+ }
244
+ const d = lineDelta(before, after);
245
+ if (d.added.some((l) => /"(jest|vitest|mocha|ava)"\s*:|testPathIgnorePatterns|passWithNoTests/.test(l) && IGNORE_CFG_RE.test(l))) add('test_config_changed', rel, d.added.find((l) => IGNORE_CFG_RE.test(l)));
246
+ continue;
247
+ }
248
+ if (TEST_CONFIG.test(rel)) {
249
+ const d = lineDelta(before || '', after || '');
250
+ const hit = d.added.find((l) => IGNORE_CFG_RE.test(l));
251
+ if (hit) add('test_config_changed', rel, hit);
252
+ continue;
253
+ }
254
+ if (!CODE_EXT.test(rel)) continue;
255
+
256
+ // assert / expect replaced, in any code file (a setup file, a helper, the source itself)
257
+ {
258
+ const ov = c.kind === 'deleted' ? null : lineDelta(before || '', after || '').added.find((l) => OVERRIDE_RE.test(l));
259
+ if (ov) add('assertion_overridden', rel, ov);
260
+ }
261
+ const inline = /\.rs$/i.test(rel) && (INLINE_TESTS.test(before || '') || INLINE_TESTS.test(after || ''));
262
+ const testy = isTest || inline || looksLikeTest(before) || (c.kind === 'added' ? false : looksLikeTest(after));
263
+ if (testy) {
264
+ const d0 = lineDelta(before || '', after || '');
265
+ const dis = c.kind === 'modified' ? d0.added.find((l) => DISABLE_RE.test(l)) : null;
266
+ if (dis) add('test_disabled', rel, dis);
267
+ if (c.kind === 'deleted') { add('test_deleted', rel, `${countCases(before)} test case(s) gone`); continue; }
268
+ const nb = countCases(before); const na = countCases(after);
269
+ if (c.kind === 'modified' && na < nb) add('tests_removed', rel, `${nb} -> ${na} test cases`);
270
+ const d = lineDelta(before || '', after || '');
271
+ const skip = d.added.find((l) => SKIP_RE.test(l));
272
+ if (skip) add('test_skipped', rel, skip);
273
+ if (c.kind === 'modified') {
274
+ const goneAsserts = d.removed.filter((l) => ASSERT_RE.test(l));
275
+ if (goneAsserts.length) add('assertion_changed', rel, goneAsserts[0]);
276
+ }
277
+ // new mocks in an EXISTING test (a brand-new test file may legitimately use mocks)
278
+ const mock = c.kind === 'modified' ? d.added.find((l) => MOCK_RE.test(l)) : null;
279
+ if (mock) add('mock_added', rel, mock);
280
+ const sil = d.added.find((l) => SILENCE_RE.test(l));
281
+ if (sil) add('checker_silenced', rel, sil);
282
+ const sc = addedMatch(before || '', after || '', SILENT_CATCH_RE);
283
+ if (sc) add('silent_catch', rel, sc);
284
+ }
285
+ if (!testy || inline) { // code (Rust: the same file holds code and tests -> both kinds of rules)
286
+ if (c.kind === 'deleted') continue;
287
+ const dup = (rule) => inline && findings.some((f) => f.rule === rule && f.file === rel);
288
+ const d = lineDelta(before || '', after || '');
289
+ const slp = d.added.find((l) => SLEEP_RE.test(l));
290
+ if (slp) add('sleep_added', rel, slp);
291
+ const env = d.added.find((l) => TEST_ENV_RE.test(l));
292
+ if (env) add('test_detection', rel, env);
293
+ const hc = hardcodedHit(d.added, before || '', getGroups());
294
+ if (hc) add('hardcoded_answer', rel, hc);
295
+ const sil = d.added.find((l) => SILENCE_RE.test(l));
296
+ if (sil && !dup('checker_silenced')) add('checker_silenced', rel, sil);
297
+ const sc = addedMatch(before || '', after || '', SILENT_CATCH_RE);
298
+ if (sc && !dup('silent_catch')) add('silent_catch', rel, sc);
299
+ }
300
+ }
301
+ return { clean: findings.length === 0, findings, rulesChecked: RULES, filesChecked: (changes || []).length };
302
+ }
303
+
304
+ /** Multi-line pattern: count matches before vs after; report the first new one. */
305
+ function addedMatch(before, after, re) {
306
+ const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g');
307
+ const mb = (before.match(g) || []).map(norm);
308
+ const ma = (after.match(g) || []).map(norm);
309
+ const left = [...mb];
310
+ for (const m of ma) { const i = left.indexOf(m); if (i >= 0) left.splice(i, 1); else return m.slice(0, 160); }
311
+ return null;
312
+ }
313
+
314
+ /** Short instruction for the AI when an attempt is rejected for cheating. */
315
+ function feedback(findings) {
316
+ return 'Your previous answer was REJECTED for weakening the checks instead of fixing the code:\n'
317
+ + findings.map((f) => `- ${f.text} (${f.file}: ${f.detail})`).join('\n')
318
+ + '\nFix the real cause in the source code. Never skip, delete or change tests, never swallow errors, never add sleeps, never silence checkers.';
319
+ }
320
+
321
+ module.exports = { analyze, assertionGroups, hardcodedHit, isTestFile, looksLikeTest, isTestFileContent, proofScriptNames, countCases, lineDelta, feedback, RULES, RULE_TEXT };