buildproof 3.12.4 → 3.13.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.
- package/README.md +10 -4
- package/bin/buildproof.js +51 -7
- package/core/certs.js +37 -5
- package/core/claims.js +1 -1
- package/core/config.js +9 -2
- package/core/flow.js +3 -2
- package/core/gate.js +11 -4
- package/core/hooks.js +23 -9
- package/core/integrity.js +565 -3
- package/core/server.js +1 -0
- package/core/service.js +30 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ Works two ways, same guarantees:
|
|
|
14
14
|
**A. BuildProof fixes it** - task from phone / tablet / PC -> diagnose (baseline build/test) -> scope proposal (tests locked) -> your approval -> fix library or local AI (Ollama) under supervision -> proof -> signed certificate.
|
|
15
15
|
|
|
16
16
|
**B. Guard my AI tool** - keep using Cursor, Claude Code, Copilot... Start guard (full copy + baseline), work, then Check:
|
|
17
|
-
- Test-integrity guard (
|
|
17
|
+
- Test-integrity guard (20 rules): deleted / skipped / removed tests, early returns, changed expected values, new mocks, tests that replace the code they test, sleeps, silent catches, silenced checkers, changed test scripts, test config or the CI workflow. It catches the common tricks, not every possible one: if you find one it misses, please tell us.
|
|
18
18
|
- Fail-closed gate: a check that did not really run (timeout, "no tests found", fewer tests than before) = NOT proven.
|
|
19
19
|
- Hardcoded answers (code that special-cases the test's values) and code that detects the test environment.
|
|
20
20
|
- Revert check: the original code is put back for a moment - the tests must FAIL without the change (covered), otherwise flaky / not covered.
|
|
@@ -27,13 +27,19 @@ One-tap hooks (Projects -> AI tools, or `buildproof connect git,claude,cursor`):
|
|
|
27
27
|
Projects: Node / Web (npm scripts typecheck, lint, build, test) and Python (syntax check of every file without writing .pyc, ruff and mypy when configured, pytest or unittest).
|
|
28
28
|
Also (3.7.1): Go (go build, go vet, go test), Rust (cargo build, cargo test - also tests inside the source file), Java with Maven or Gradle (JUnit results), .NET (dotnet build, dotnet test), Ruby (syntax check, RSpec or Minitest), PHP (syntax check, PHPUnit). Each uses its own toolchain on your computer; a missing toolchain or unreadable test results is reported, never counted as proven.
|
|
29
29
|
|
|
30
|
-
Pull request checks (3.8.0;
|
|
30
|
+
Pull request checks (3.8.0; Team and Enterprise - in CI they need a paid licence key; during the trial you can run `buildproof ci` on your own computer): `buildproof ci --init` adds a GitHub workflow; every pull request is compared with its base branch - test-integrity rules on the changed files, build/test on both sides, fail-closed verdict in the job summary. A check that fails is run once more: if it then passes it is reported as FLAKY (not blamed on the pull request); `--no-retry` keeps it strict (3.11). Protect your base branch (GitHub: Settings > Branches > branch protection) so only pull requests can change it: the check compares against the base, and an agent that can push to the base directly could weaken the baseline too. Since 3.12.4 `buildproof ci --init` warns when it is not protected. Spec check (free trial, then Pro and up; `buildproof spec` locally or inside `buildproof ci`): `.buildproof/spec.md`, one requirement per line with the test that proves it (`- Free shipping from $50 => test: free shipping from 50`); a requirement without a passing test is never accepted. Live demo: https://buildproof.mgrprosnetwork.com/demo
|
|
31
31
|
|
|
32
32
|
Audit report (3.9.0; free trial, then Enterprise): `buildproof audit --since 2026-01-01` writes a signed HTML + JSON report of every accepted and rejected change; `buildproof audit --verify report.json` shows any later edit. Team dashboard (Team and Enterprise): `buildproof team` opens it; your licence key unlocks your own team's certificates.
|
|
33
33
|
|
|
34
|
-
AI bug hunt (3.10.0; Pro and up, and the trial): `buildproof hunt --base main` uploads the change to the BuildProof server, where the hunter runs your code and the AI-written tests in a locked-down container (no network) and reports only bugs it PROVED (a test that fails on the new code and passes on the old). By default your own local model (Ollama) answers the AI's questions - free; `--cloud` uses the server's AI (one cloud check; 5 in the trial; `buildproof credits --buy 20`). Your code is deleted from the server when the check ends. Since 3.12 the hunter is told what the change was meant to do: taken from `--intent "..."`, else from the pull request (GitHub) or merge request (GitLab) title and description, else from the commit messages since the base. This helps it tell a real bug from an intended change. `--no-intent` turns it off.
|
|
34
|
+
AI bug hunt (3.10.0; Pro and up, and the trial): `buildproof hunt --base main` uploads copies of the tracked files at the base commit and at your current version (including uncommitted edits), plus the change description, to the BuildProof server, where the hunter runs your code and the AI-written tests in a locked-down container (no network) and reports only bugs it PROVED (a test that fails on the new code and passes on the old). By default your own local model (Ollama) answers the AI's questions - free; `--cloud` uses the server's AI (one cloud check; 5 in the trial; `buildproof credits --buy 20`). Your code is deleted from the server when the check ends. Since 3.12 the hunter is told what the change was meant to do: taken from `--intent "..."`, else from the pull request (GitHub) or merge request (GitLab) title and description, else from the commit messages since the base. This helps it tell a real bug from an intended change. `--no-intent` turns it off.
|
|
35
35
|
|
|
36
36
|
CLI: `buildproof start | check [--claim "..."] | accept [--force] | rollback | connect | verify <cert.html> | status | ci [--base origin/main] [--spec spec.md]`. `buildproof check` exits 0 only when proven.
|
|
37
37
|
|
|
38
38
|
Run: `node scripts/guard.js` (keeps core/server.js alive on port 38700). Test: `node test/run-all.js`.
|
|
39
|
-
Data (config, token, signing key, tasks, backups, certificates, learned fixes):
|
|
39
|
+
Data (config, token, signing key, tasks, backups, certificates, learned fixes): `~/.buildproof/` - never shipped, kept on reinstall.
|
|
40
|
+
|
|
41
|
+
Background service: `init` and `try` start a small local service (127.0.0.1 only; `buildproof remote on` opens it to your phone / tablet, token protected). `buildproof stop` stops it. `buildproof uninstall [folder] [--all]` removes the hooks, the start-at-login entry and the service (`--all` also deletes `~/.buildproof`). The git hook lets commits through if BuildProof itself is missing.
|
|
42
|
+
|
|
43
|
+
Certificates: the signature proves a certificate was not edited after it was issued. It does not prove who issued it: anyone can sign their own. `buildproof verify` therefore also checks the BuildProof public log (key registered to a licensed account, certificate countersigned with BuildProof's key) and says SELF_SIGNED otherwise. The real proof is `buildproof verify <cert> --rerun <folder>`: it re-runs the checks on the code you received.
|
|
44
|
+
|
|
45
|
+
Network calls (all of them): trial start (`/api/trial/start`, a one-way hash of a device id, cached for 10 minutes when offline); licence activation / renewal / certificate countersigning (licence key or subscription id, signing public key and fingerprint, certificate hash - never your code); a daily npm registry version check; `ci --init` asks api.github.com whether your base branch is protected; `hunt` uploads the code as described above; `verify` reads the public log. The local web page loads Google Fonts and, on the phone-connect page, a QR code script from cdnjs.
|
package/bin/buildproof.js
CHANGED
|
@@ -10,11 +10,12 @@
|
|
|
10
10
|
* buildproof connect [folder] git,claude,cursor install the hooks in one go
|
|
11
11
|
* buildproof status service and AI status
|
|
12
12
|
* buildproof verify <certificate.html|.json> [--rerun folder] verify a certificate (and re-run its checks)
|
|
13
|
-
* buildproof repro <evidence.json> [folder] replay one hidden-bug finding (isolated copy)
|
|
14
13
|
* buildproof init [folder] [--ci] one-time setup: background service, project, AI tool hooks (--ci also adds the GitHub PR check)
|
|
15
14
|
* buildproof try 30-second demo on a throw-away sample project: a skipped test is caught, the real fix is proven
|
|
16
15
|
* buildproof activate <key> activate a license key buildproof license show the plan
|
|
17
16
|
* buildproof open open BuildProof in the browser
|
|
17
|
+
* buildproof stop stop the background service buildproof remote on|off allow your phone / tablet on this network (off = this computer only)
|
|
18
|
+
* buildproof uninstall [folder] [--all --yes] remove BuildProof's hooks from the project and the start-at-login entry, stop the service (--all --yes also deletes ~/.buildproof)
|
|
18
19
|
* buildproof ci [folder] [--base origin/main] [--spec spec.md] pull request check for CI (--init writes the GitHub workflow)
|
|
19
20
|
* buildproof spec [folder] [--base main] check the change against .buildproof/spec.md (every requirement needs a passing test)
|
|
20
21
|
* buildproof audit [--since 2026-01-01] [--out report.html] signed audit report of every checked change buildproof team team dashboard
|
|
@@ -35,12 +36,21 @@ const config = require('../core/config');
|
|
|
35
36
|
const args = process.argv.slice(2);
|
|
36
37
|
const cmd = ['-h', '--help'].includes(args[0]) ? 'help' : (args[0] || 'help');
|
|
37
38
|
if (['-v', '--version', 'version'].includes(cmd)) { console.log(require('../package.json').version); process.exit(0); }
|
|
38
|
-
|
|
39
|
+
// flags that take a value accept both --name=value and --name value
|
|
40
|
+
const VALUE_FLAGS = new Set(['base', 'buy', 'intent', 'out', 'since', 'until', 'spec', 'verify', 'summary', 'claim']);
|
|
41
|
+
const flag = (n) => {
|
|
42
|
+
const i = args.findIndex((x) => x === `--${n}` || x.startsWith(`--${n}=`));
|
|
43
|
+
if (i < 0) return null;
|
|
44
|
+
const a = args[i];
|
|
45
|
+
if (a.includes('=')) return a.split('=').slice(1).join('=');
|
|
46
|
+
if (VALUE_FLAGS.has(n) && i + 1 < args.length && !args[i + 1].startsWith('--')) return args[i + 1];
|
|
47
|
+
return true;
|
|
48
|
+
};
|
|
39
49
|
const hook = flag('hook');
|
|
40
50
|
const force = !!flag('force');
|
|
41
51
|
let claimArg = null;
|
|
42
52
|
{ const i = args.indexOf('--claim'); if (i >= 0) claimArg = args[i + 1] || ''; }
|
|
43
|
-
const positional = args.slice(1).filter((a, i, all) => !a.startsWith('--') && all[i - 1]
|
|
53
|
+
const positional = args.slice(1).filter((a, i, all) => !a.startsWith('--') && !(i > 0 && VALUE_FLAGS.has(String(all[i - 1]).replace(/^--/, '')) && !String(all[i - 1]).includes('=')));
|
|
44
54
|
|
|
45
55
|
function readStdin() {
|
|
46
56
|
if (!hook || process.stdin.isTTY) return Promise.resolve({});
|
|
@@ -172,7 +182,13 @@ async function main() {
|
|
|
172
182
|
const cert = JSON.parse(m ? m[1] : raw);
|
|
173
183
|
const ok = certs.verify(cert);
|
|
174
184
|
if (!ok) out('INVALID signature - the certificate was modified (or names a key it was not signed with)', 1);
|
|
175
|
-
if (!flag('rerun'))
|
|
185
|
+
if (!flag('rerun')) {
|
|
186
|
+
// a valid signature only shows the file was not edited; who stands behind it comes from the public log
|
|
187
|
+
const t = await certs.trust(cert, config.load().licenseServer || 'https://buildproof.mgrprosnetwork.com');
|
|
188
|
+
if (t.level === 'countersigned') out(`VALID ${cert.payload.id} ${cert.payload.result} project=${cert.payload.project} | ${t.detail}`, 0);
|
|
189
|
+
if (t.level === 'self_signed') out(`SELF_SIGNED ${cert.payload.id} ${cert.payload.result} project=${cert.payload.project} | the signature only proves the file was not edited after issue - anyone can sign their own; ${t.detail}. To prove the code itself: buildproof verify <cert> --rerun <project-folder>`, 3);
|
|
190
|
+
out(`SIGNATURE_OK ${cert.payload.id} ${cert.payload.result} project=${cert.payload.project} | ${t.detail}: cannot tell who issued it. To prove the code itself: buildproof verify <cert> --rerun <project-folder>`, 3);
|
|
191
|
+
}
|
|
176
192
|
// --rerun: is this exactly the certified code, and do the checks really pass here?
|
|
177
193
|
const rr = cert.payload.rerun;
|
|
178
194
|
if (!rr) out(`VALID ${cert.payload.id} - this certificate is too old for --rerun`, 1);
|
|
@@ -213,7 +229,7 @@ async function main() {
|
|
|
213
229
|
const r = await require('../core/bug-hunter/engine').repro(path.resolve(positional[1] || process.cwd()), f);
|
|
214
230
|
out(`${r.reproduced ? 'REPRODUCED' : 'NOT_REPRODUCED'} ${f.oracle} ${f.file} ${f.export}(${f.inputPreview}) -> ${r.outcome}`, r.reproduced ? 0 : 1);
|
|
215
231
|
}
|
|
216
|
-
if (['license', 'activate', 'status', 'open'].includes(cmd)) { // these need the local service: start it if it is not running
|
|
232
|
+
if (['license', 'activate', 'status', 'open', 'start', 'check', 'rollback', 'accept'].includes(cmd) && !hook) { // these need the local service: start it if it is not running
|
|
217
233
|
const sv = await require('../core/service').ensure({ autostart: false });
|
|
218
234
|
if (!sv.ok) out(sv.how === 'port_busy' ? `DOWN port ${sv.port} is used by another program, not BuildProof - pick a free port: set MGR_PORT=38711` : `DOWN BuildProof could not start on port ${sv.port} (if another program uses it, pick a free port: set MGR_PORT=38711)`, 1);
|
|
219
235
|
}
|
|
@@ -273,6 +289,7 @@ async function main() {
|
|
|
273
289
|
const good = !r.round1.proven && r.round2.proven;
|
|
274
290
|
console.log('');
|
|
275
291
|
console.log(good ? 'That is BuildProof: the shortcut was caught and undone, the real fix was proven. Set it up on your project: npx buildproof init' : 'The demo did not end as expected - please tell us: https://buildproof.mgrprosnetwork.com');
|
|
292
|
+
console.log(`Note: BuildProof's background service is running on 127.0.0.1:${config.load().port} (this computer only). Stop it: npx buildproof stop`);
|
|
276
293
|
out(`TRY ${good ? 'OK' : 'UNEXPECTED'} shortcut=${r.round1.proven ? 'PROVEN' : 'NOT_PROVEN'} real_fix=${r.round2.proven ? 'PROVEN' : 'NOT_PROVEN'}`, good ? 0 : 1);
|
|
277
294
|
}
|
|
278
295
|
if (cmd === 'open') { const u = `http://127.0.0.1:${config.load().port || 38700}/connect`; openUrl(u); out('OPEN ' + u, 0); }
|
|
@@ -281,8 +298,34 @@ async function main() {
|
|
|
281
298
|
if (r.ok && typeof r.version !== 'string') out(`DOWN unexpected answer on port ${config.load().port}`, 1);
|
|
282
299
|
out(r.ok ? `BUILDPROOF v${r.version} AI=${r.ai && r.ai.ok ? 'OK' : 'DOWN'} fixes=${r.fixes} key=${r.fingerprint}` : `DOWN ${r.error}`, r.ok ? 0 : 1);
|
|
283
300
|
}
|
|
301
|
+
if (cmd === 'stop') { const r = await require('../core/service').stop(); out(r.stillRunning ? 'STOP_FAIL something still answers on the BuildProof port' : `STOPPED ${r.stopped ? 'the background service' : '(it was not running)'}`, r.stillRunning ? 1 : 0); }
|
|
302
|
+
if (cmd === 'remote') {
|
|
303
|
+
const on = positional[0] === 'on'; if (!['on', 'off'].includes(positional[0])) out('usage: buildproof remote on|off', 1);
|
|
304
|
+
config.save({ host: on ? '0.0.0.0' : '127.0.0.1' });
|
|
305
|
+
const service = require('../core/service'); await service.stop(); const sv = await service.ensure({ autostart: false });
|
|
306
|
+
out(on ? `REMOTE_ON your phone / tablet on this network can open BuildProof (token protected): buildproof open shows the QR code${sv.ok ? '' : ' - restart failed, run: buildproof open'}` : 'REMOTE_OFF BuildProof answers on this computer only', 0);
|
|
307
|
+
}
|
|
308
|
+
if (cmd === 'uninstall') {
|
|
309
|
+
if (flag('all') && !flag('yes')) out('UNINSTALL_CONFIRM --all also deletes ~/.buildproof: your licence, signing keys, certificate history and backups. Run again with --all --yes to confirm (nothing was changed).', 1);
|
|
310
|
+
const dir = path.resolve(positional[0] || process.cwd());
|
|
311
|
+
const hooks = require('../core/hooks'); const service = require('../core/service');
|
|
312
|
+
const removed = [];
|
|
313
|
+
for (const t of hooks.TOOLS) { try { const st = hooks.status(dir)[t]; if (st && st.connected) { hooks.disconnect(dir, t); removed.push(t + ' hook'); } } catch { /* keep going */ } }
|
|
314
|
+
const st = await service.stop();
|
|
315
|
+
const auto = service.removeAutostart();
|
|
316
|
+
if (st.stopped) removed.push('background service stopped');
|
|
317
|
+
if (auto.length) removed.push('start-at-login entry');
|
|
318
|
+
if (flag('all')) {
|
|
319
|
+
for (const f of [config.HOME_DIR && path.join(require('os').homedir(), '.buildproof'), path.join(require('os').homedir(), '.buildproof_trial'), path.join(require('os').homedir(), '.buildproof_trial_backup')]) {
|
|
320
|
+
try { if (f && fs.existsSync(f)) { fs.rmSync(f, { recursive: true, force: true }); removed.push(f); } } catch { /* keep going */ }
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
out(`UNINSTALLED ${removed.length ? removed.join(', ') : 'nothing was installed here'}${flag('all') ? '' : ' | your data stays in ~/.buildproof (add --all --yes to delete it). Remove the package itself with: npm rm buildproof (or clear the npx cache)'}`, 0);
|
|
324
|
+
}
|
|
284
325
|
if (!['start', 'check', 'accept', 'rollback', 'connect', 'try'].includes(cmd)) {
|
|
285
|
-
|
|
326
|
+
const help = fs.readFileSync(__filename, 'utf8').split('\n'); const end = help.findIndex((l, i) => i > 3 && l.trim() === '*/');
|
|
327
|
+
const known = cmd === 'help';
|
|
328
|
+
out((known ? '' : `Unknown command: ${cmd}\n\n`) + help.slice(3, end > 3 ? end : 24).map((l) => l.replace(/^ \* ?/, '')).join('\n'), known ? 0 : 1);
|
|
286
329
|
}
|
|
287
330
|
|
|
288
331
|
const input = await readStdin();
|
|
@@ -338,7 +381,8 @@ async function main() {
|
|
|
338
381
|
'Fix the real cause in the source code. Do not delete, skip or weaken tests, do not special-case test values, do not swallow errors.'].join('\n'));
|
|
339
382
|
}
|
|
340
383
|
const extra = [integ.length ? 'integrity: ' + integ.join('; ') : '', falseClaims.length ? 'claims: ' + falseClaims.join('; ') : '', full.revertCheck ? 'revert: ' + full.revertCheck.verdict : ''].filter(Boolean).join(' | ');
|
|
341
|
-
|
|
384
|
+
const allPass = full.after && Object.keys(full.after).length && Object.values(full.after).every((x) => x && x.pass);
|
|
385
|
+
out(`${r.proven ? (allPass ? 'PROVEN' : 'NO_REGRESSION') : 'NOT_PROVEN'} files=${files} ${steps(full.after)}${extra ? ' | ' + extra : ''} | ${full.resultText}`, r.proven ? 0 : 1);
|
|
342
386
|
}
|
|
343
387
|
if (cmd === 'accept') {
|
|
344
388
|
const r = await api('POST', `/api/guards/${g.id}/accept`, { force });
|
package/core/certs.js
CHANGED
|
@@ -87,7 +87,8 @@ function issue(task, project, { acceptedWarnings = false } = {}) {
|
|
|
87
87
|
machine: os.hostname(),
|
|
88
88
|
project: project.name,
|
|
89
89
|
task: { id: task.id, kind: task.kind || 'supervised', text: task.text, source: task.source || 'web' },
|
|
90
|
-
|
|
90
|
+
// PROVEN only when every check passes; failures that were already there before the change give NO_REGRESSION, never a green PROVEN
|
|
91
|
+
result: acceptedWarnings ? 'ACCEPTED_WITH_WARNINGS' : (checks.length && checks.every((c) => c.after === 'pass') ? 'PROVEN' : 'NO_REGRESSION'),
|
|
91
92
|
checks,
|
|
92
93
|
integrity: { clean: !!integ.clean, rulesChecked: integ.rulesChecked || [], findings: (integ.findings || []).map((f) => ({ rule: f.rule, file: f.file, text: f.text })) },
|
|
93
94
|
scope: { approved: task.approvedScope || null, outsideReverted: (task.scopeGuard && task.scopeGuard.reverted) || [] },
|
|
@@ -142,6 +143,37 @@ function verify(cert) {
|
|
|
142
143
|
} catch { return false; }
|
|
143
144
|
}
|
|
144
145
|
|
|
146
|
+
/**
|
|
147
|
+
* Who stands behind this certificate? A valid signature alone only shows the file was not edited after issue:
|
|
148
|
+
* anyone can make a key and sign anything. Trust needs the BuildProof public log: the signing key is registered
|
|
149
|
+
* to a licensed account, and the certificate's hash was countersigned with the pinned vendor key at a given time.
|
|
150
|
+
* Returns { level: 'countersigned' | 'self_signed' | 'unknown', detail }.
|
|
151
|
+
*/
|
|
152
|
+
async function trust(cert, server, { timeoutMs = 6000 } = {}) {
|
|
153
|
+
const fp = require('./machine-proof').fingerprintOfSpki(cert.publicKey);
|
|
154
|
+
const base = String(server || '').replace(/\/$/, '');
|
|
155
|
+
if (!base) return { level: 'unknown', detail: 'no BuildProof server configured' };
|
|
156
|
+
const get = (p) => new Promise((resolve) => {
|
|
157
|
+
try {
|
|
158
|
+
const u = new URL(base + p); const m = u.protocol === 'https:' ? require('https') : require('http');
|
|
159
|
+
const req = m.get(u, { timeout: timeoutMs }, (res) => { let b = ''; res.on('data', (d) => { b += d; }); res.on('end', () => { try { resolve(res.statusCode === 200 ? JSON.parse(b) : null); } catch { resolve(null); } }); });
|
|
160
|
+
req.on('timeout', () => req.destroy(new Error('timeout'))); req.on('error', () => resolve(null));
|
|
161
|
+
} catch { resolve(null); }
|
|
162
|
+
});
|
|
163
|
+
const hash = crypto.createHash('sha256').update(canonical(cert.payload)).digest('hex');
|
|
164
|
+
const [reg, log] = await Promise.all([get('/api/fingerprint/' + encodeURIComponent(fp)), get('/api/log/' + hash)]);
|
|
165
|
+
if (!reg && !log) return { level: 'unknown', detail: 'could not reach the BuildProof public log' };
|
|
166
|
+
let vendor = null;
|
|
167
|
+
try { vendor = crypto.createPublicKey(fs.readFileSync(path.join(__dirname, '..', 'license', 'vendor.pub.pem'))); } catch { /* no pinned key */ }
|
|
168
|
+
let good = null;
|
|
169
|
+
for (const e of (log && log.entries) || []) {
|
|
170
|
+
const { sig, ...entry } = e || {};
|
|
171
|
+
try { if (vendor && sig && entry.fingerprint === fp && entry.certHash === hash && Number.isFinite(typeof entry.time === 'number' ? entry.time : Date.parse(entry.time)) && crypto.verify(null, Buffer.from(canonical(entry), 'utf8'), vendor, Buffer.from(sig, 'base64'))) { good = entry; break; } } catch { /* bad entry */ }
|
|
172
|
+
}
|
|
173
|
+
if (good) return { level: 'countersigned', detail: `countersigned by BuildProof at ${new Date(good.time).toISOString()}${reg && reg.registered ? `, key registered (${reg.plan || 'licensed'} plan)` : ''}` };
|
|
174
|
+
return { level: 'self_signed', detail: reg && reg.registered ? 'key registered, but this certificate is not in the public log' : 'signing key not registered and certificate not in the public log' };
|
|
175
|
+
}
|
|
176
|
+
|
|
145
177
|
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); }
|
|
146
178
|
|
|
147
179
|
/** Self-contained, self-verifying certificate page. */
|
|
@@ -163,7 +195,7 @@ table{width:100%;border-collapse:collapse}td{padding:9px 6px;border-top:1px soli
|
|
|
163
195
|
ul{margin:0;padding-left:20px}li{margin:6px 0}h2{font-size:15px;color:#5F6368;margin:0 0 8px}
|
|
164
196
|
#sig{font-weight:700;padding:12px 14px;border-radius:12px;background:#F1F2F4}#sig.ok{background:#ECF7F0;color:#12803F}#sig.bad{background:#FDF1F0;color:#C5221F}</style></head>
|
|
165
197
|
<body><div class="wrap">
|
|
166
|
-
<div class="card"><h1>BuildProof certificate</h1><div class="big">${good ? 'PROVEN' : 'ACCEPTED WITH WARNINGS'}</div>
|
|
198
|
+
<div class="card"><h1>BuildProof certificate</h1><div class="big">${good ? 'PROVEN' : p.result === 'NO_REGRESSION' ? 'NO REGRESSION (some checks were already failing before this change)' : 'ACCEPTED WITH WARNINGS'}</div>
|
|
167
199
|
<div class="task">${esc(p.task.text)}</div><div class="dim">${esc(p.project)} · ${esc(new Date(p.issuedAt).toUTCString())} · ${esc(p.machine)}</div></div>
|
|
168
200
|
<div class="card"><h2>Checks · before → after</h2><table>${p.checks.map(row).join('')}</table></div>
|
|
169
201
|
<div class="card"><h2>Test integrity · ${p.integrity.rulesChecked.length} rules checked</h2><ul>${integ}</ul></div>
|
|
@@ -171,7 +203,7 @@ ${p.revertCheck ? `<div class="card"><h2>Revert check</h2><div class="${p.revert
|
|
|
171
203
|
${(p.claims || []).length ? `<div class="card"><h2>What the AI claimed</h2><ul>${p.claims.map((c) => `<li class="${c.true === false ? 'r' : c.true ? 'g' : 'dim'}">${c.true === false ? 'NOT TRUE: ' : c.true ? 'True: ' : 'Unknown: '}${esc(c.claim)} <span class="dim">(${esc(c.why)})</span></li>`).join('')}</ul></div>` : ''}
|
|
172
204
|
<div class="card"><h2>Changed files</h2><ul>${files}</ul></div>
|
|
173
205
|
<div class="card"><h2>AI</h2><div>${p.ai.calls} call(s)${p.ai.model ? ' · ' + esc(p.ai.model) : ''} · ${p.ai.local ? 'ran locally, code never left the computer' : 'remote model'}</div></div>
|
|
174
|
-
${
|
|
206
|
+
${true ? `<div class="card"><h2>Who issued it</h2><div>This page can only show that the file was not edited. To see who issued it and whether BuildProof countersigned it, drop this file on https://buildproof.mgrprosnetwork.com/verify or run: npx buildproof verify <this file></div></div>` : ''}
|
|
175
207
|
<div class="card"><h2>Check it yourself</h2><div>Run the same checks on the code you received:</div><p class="mono" style="background:#F4F5F7;padding:10px 12px;border-radius:10px">npx buildproof verify certificate.html --rerun <your-project-folder></p><div class="dim small">It confirms the code is exactly the certified version (${p.rerun ? p.rerun.fileCount : '?'} files${p.rerun && p.rerun.git ? ', git ' + esc(p.rerun.git.commit.slice(0, 10)) : ''}) and runs ${p.rerun ? esc(p.rerun.steps.join(', ')) : 'the checks'} again on your computer.</div></div>
|
|
176
208
|
<div class="card"><h2>Signature</h2><div id="sig">Checking signature…</div>
|
|
177
209
|
<p class="mono dim small">ed25519 · key fingerprint <span id="fp">${esc(cert.fingerprint)}</span><br>certificate ${esc(p.id)}</p>
|
|
@@ -186,9 +218,9 @@ var key=await crypto.subtle.importKey('spki',b64(c.publicKey),{name:'Ed25519'},f
|
|
|
186
218
|
var ok=await crypto.subtle.verify({name:'Ed25519'},key,b64(c.signature),new TextEncoder().encode(canonical(c.payload)));
|
|
187
219
|
var h=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',b64(c.publicKey)))).map(function(b){return b.toString(16).padStart(2,'0')}).join('').slice(0,32).toUpperCase().match(/.{4}/g).join(' ');
|
|
188
220
|
if(c.fingerprint!==h)ok=false;var fe=document.getElementById('fp');if(fe)fe.textContent=h;
|
|
189
|
-
el.className=ok?'ok':'bad';el.textContent=ok?'✓ Signature valid. This
|
|
221
|
+
el.className=ok?'ok':'bad';el.textContent=ok?'✓ Signature valid: not edited since it was issued. This does not show who issued it - check below.':'✗ Signature INVALID. This report was modified.';}
|
|
190
222
|
catch(e){el.textContent='This browser cannot check ed25519 signatures. Open the file in a current Chrome, Edge, Safari or Firefox.';}})();
|
|
191
223
|
</script></body></html>`;
|
|
192
224
|
}
|
|
193
225
|
|
|
194
|
-
module.exports = { issue, verify, html, canonical, keys, treeOf, countersign, registerFingerprint };
|
|
226
|
+
module.exports = { issue, verify, trust, html, canonical, keys, treeOf, countersign, registerFingerprint };
|
package/core/claims.js
CHANGED
|
@@ -8,7 +8,7 @@ const CLAIMS = [
|
|
|
8
8
|
{ id: 'tests_pass', re: /\b(all (the )?tests? (now )?(pass|passed|are passing|green)|tests? (are |now )*(passing|pass(es)?|green)|test suite (now )?pass(es)?)\b/i, text: 'All tests pass' },
|
|
9
9
|
{ id: 'build_ok', re: /\b(build (now )?(succeeds|succeeded|passes|passed|is green|works)|compiles (successfully|cleanly|without errors))\b/i, text: 'The build works' },
|
|
10
10
|
{ id: 'tests_added', re: /\b(added|wrote|created|new) (\d+ )?(new )?(unit |integration |e2e )?tests?\b/i, text: 'Tests were added' },
|
|
11
|
-
{ id: 'tests_untouched', re: /\b(did ?n[o']t|did not|without) (change|modify|touch|edit)(ing)? (any )?(of the )?(existing )?tests
|
|
11
|
+
{ id: 'tests_untouched', re: /\b((did ?n[o'’]?t|did not|without|never) (change|modify|touch|edit)(ing|ed)? (any )?(of )?(the )?(existing )?tests?|no tests? (files? )?(were|was) (changed|modified|touched|edited)|tests? (are |were |was |remain |remained )?(untouched|unchanged|left (as is|alone|untouched))|(have|has)( not|n?[o'’]?t) (changed|modified|touched|edited) (any |the )*tests?|left the tests? (alone|as is|untouched))\b/i, text: 'Tests were not changed' },
|
|
12
12
|
{ id: 'fixed', re: /\b(fixed|resolved|the (bug|issue|error) is (now )?(gone|fixed|resolved))\b/i, text: 'The problem is fixed' },
|
|
13
13
|
];
|
|
14
14
|
|
package/core/config.js
CHANGED
|
@@ -14,7 +14,7 @@ const CONFIG_FILE = path.join(DATA_DIR, 'config.json');
|
|
|
14
14
|
|
|
15
15
|
const DEFAULTS = {
|
|
16
16
|
port: 38700,
|
|
17
|
-
host: '
|
|
17
|
+
host: '127.0.0.1', // this computer only; `buildproof remote on` opens it to your phone / tablet on the same network
|
|
18
18
|
allowedHosts: [], // extra host names this server answers to (IPs, localhost and *.ts.net always work)
|
|
19
19
|
token: '', // generated on first run
|
|
20
20
|
ollama: { endpoint: 'http://127.0.0.1:11434', model: 'qwen2.5-coder:14b', timeoutMs: 180000 },
|
|
@@ -37,6 +37,13 @@ function deepMerge(a, b) {
|
|
|
37
37
|
return out;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
/** Save chosen settings (merged into config.json, the token is kept). */
|
|
41
|
+
function save(patch) {
|
|
42
|
+
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
43
|
+
const file = require('./keep-corrupt').readJsonSafe(CONFIG_FILE) || {};
|
|
44
|
+
fs.writeFileSync(CONFIG_FILE, JSON.stringify({ ...file, ...patch }, null, 2), 'utf8');
|
|
45
|
+
}
|
|
46
|
+
|
|
40
47
|
function load() {
|
|
41
48
|
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
42
49
|
// first run, or a damaged file (kept aside as config.json.corrupt-<time>, never silently overwritten)
|
|
@@ -54,4 +61,4 @@ function load() {
|
|
|
54
61
|
return cfg;
|
|
55
62
|
}
|
|
56
63
|
|
|
57
|
-
module.exports = { load, ROOT, DATA_DIR, LOG_DIR, NPM_MODE, HOME_DIR, CONFIG_FILE, DEFAULTS };
|
|
64
|
+
module.exports = { load, save, ROOT, DATA_DIR, LOG_DIR, NPM_MODE, HOME_DIR, CONFIG_FILE, DEFAULTS };
|
package/core/flow.js
CHANGED
|
@@ -304,7 +304,8 @@ async function revertCheck(project, cfg, taskId, changes, baseline, after) {
|
|
|
304
304
|
if (Array.isArray(r.failedTests) && Array.isArray(a.failedTests)) { const now = new Set(a.failedTests); return r.failedTests.some((x) => !now.has(x)); }
|
|
305
305
|
unknown = true; return false;
|
|
306
306
|
});
|
|
307
|
-
|
|
307
|
+
// "flaky" only when a step went from failing to passing and still passes without the change; old failures that remain are not flakiness
|
|
308
|
+
const wasFailing = steps.some((s) => baseline && baseline[s] && !baseline[s].pass && after && after[s] && after[s].pass);
|
|
308
309
|
if (!failsWithout && unknown) return { ran: true, verdict: 'skipped', text: 'Could not compare test by test (old failures in the project)', files: src.map((c) => c.file) };
|
|
309
310
|
const verdict = failsWithout ? 'covered' : wasFailing ? 'flaky' : 'not_covered';
|
|
310
311
|
const text = verdict === 'covered' ? 'The tests fail without this change, so they really check it'
|
|
@@ -701,7 +702,7 @@ async function guardCheck(id, cfg, { claim = '' } = {}) {
|
|
|
701
702
|
const checkedHashes = examined;
|
|
702
703
|
fs.writeFileSync(path.join(DATA_DIR, 'backups', id, 'checked.json'), JSON.stringify(checkedHashes));
|
|
703
704
|
const hbText = hb && hb.findings.length ? ` Warning: ${hb.findings.length} possible hidden bug(s) the tests miss (${hb.findings.slice(0, 3).map((f) => f.oracle + ' ' + f.export).join(', ')}).` : '';
|
|
704
|
-
const why = during.length ? `Not proven: ${during.length} file(s) changed while the check was running (${during.slice(0, 3).map((c) => c.file).join(', ')}). Wait until the AI tool has finished, then check again.` : changes.length === 0 ? 'No changes yet' : hb && hb.findings.length && cfg.bugHunter === 'block' && !ok ? `Not proven: ${hb.findings.length} hidden bug(s) found (${hb.findings.slice(0, 3).map((f) => f.oracle + ' ' + f.export + '(' + f.inputPreview + ')').join(', ')}).` : ok ?
|
|
705
|
+
const why = during.length ? `Not proven: ${during.length} file(s) changed while the check was running (${during.slice(0, 3).map((c) => c.file).join(', ')}). Wait until the AI tool has finished, then check again.` : changes.length === 0 ? 'No changes yet' : hb && hb.findings.length && cfg.bugHunter === 'block' && !ok ? `Not proven: ${hb.findings.length} hidden bug(s) found (${hb.findings.slice(0, 3).map((f) => f.oracle + ' ' + f.export + '(' + f.inputPreview + ')').join(', ')}).` : ok ? `${Object.values(after).every((x) => x.pass) ? 'Proven' : 'No regression (some checks were already failing before)'}: ${Object.keys(after).map((s) => `${s} ${after[s].pass ? 'passed' : 'failed'}`).join(', ')}. Test integrity clean.${rc && rc.verdict === 'covered' ? ' The tests fail without this change.' : rc && rc.verdict === 'not_covered' ? ' Warning: no test covers this change.' : ''}${hbText}` : rc && rc.verdict === 'flaky' ? `Not proven: ${rc.text}` : gate.whyNot(verdict, integ);
|
|
705
706
|
const cur = store.get('tasks', id);
|
|
706
707
|
// the same cheating change checked again is ONE blocked cheat, not one per click
|
|
707
708
|
const cheatSig = integ.clean ? null : crypto.createHash('sha256').update(JSON.stringify(changes.map((c) => [c.file, checkedHashes[c.file] || null]))).digest('hex');
|
package/core/gate.js
CHANGED
|
@@ -62,7 +62,7 @@ function testCounts(output) {
|
|
|
62
62
|
return { passed: total - failed - skipped, failed, total: total - skipped };
|
|
63
63
|
}
|
|
64
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])) {
|
|
65
|
+
if ((m = last(/(?:=+ |^)((?:\d+ (?:passed|failed|errors?|skipped|xfailed|xpassed|warnings?|deselected)(?:, )?)+|no tests ran) in [\d.]+s/m) || last(/=+ (.*?) in [\d.]+s/)) && /passed|failed|error|no tests ran/.test(m[1])) { // `pytest -q` prints the line without ===
|
|
66
66
|
const passed = +(m[1].match(/(\d+) passed/) || [0, 0])[1];
|
|
67
67
|
const failed = +(m[1].match(/(\d+) failed/) || [0, 0])[1] + +(m[1].match(/(\d+) error/) || [0, 0])[1];
|
|
68
68
|
return { passed, failed, total: passed + failed };
|
|
@@ -158,7 +158,10 @@ function judge(baseline, after, expected, isFix) {
|
|
|
158
158
|
}
|
|
159
159
|
const regressions = steps.filter((s) => {
|
|
160
160
|
if (testLevel[s]) return testLevel[s].newFailures.length > 0;
|
|
161
|
-
|
|
161
|
+
if (baseline[s] && baseline[s].pass && after[s] && !after[s].pass) return true;
|
|
162
|
+
// failing before and after, no test names to compare: more failures than before is a regression too
|
|
163
|
+
const bf = baseline[s] && baseline[s].tests && baseline[s].tests.failed; const af = after[s] && after[s].tests && after[s].tests.failed;
|
|
164
|
+
return Number.isFinite(bf) && Number.isFinite(af) && af > bf;
|
|
162
165
|
});
|
|
163
166
|
// A step still counts as failing for a fix unless, test by test, something was fixed and nothing new broke.
|
|
164
167
|
const stillFailing = steps.filter((s) => after[s] && !after[s].pass && !(testLevel[s] && testLevel[s].fixed.length > 0 && testLevel[s].newFailures.length === 0));
|
|
@@ -168,9 +171,12 @@ function judge(baseline, after, expected, isFix) {
|
|
|
168
171
|
const b = baseline[s] && baseline[s].tests; const a = after[s] && after[s].tests;
|
|
169
172
|
return b && a && a.total < b.total;
|
|
170
173
|
});
|
|
174
|
+
// failing before AND after, and neither test names nor counts to compare: we cannot tell whether the change broke more
|
|
175
|
+
const unclear = steps.filter((s) => !regressions.includes(s) && baseline[s] && !baseline[s].pass && after[s] && after[s].ran !== false && !after[s].pass && !testLevel[s]
|
|
176
|
+
&& !(baseline[s].tests && Number.isFinite(baseline[s].tests.failed) && after[s].tests && Number.isFinite(after[s].tests.failed)));
|
|
171
177
|
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 };
|
|
178
|
+
const ok = proven && regressions.length === 0 && unclear.length === 0 && fewerTests.length === 0 && (isFix ? stillFailing.length === 0 : true);
|
|
179
|
+
return { ok, proven, regressions, unclear, stillFailing, fixedNow, missing, notRun, fewerTests, steps, testLevel, preExisting };
|
|
174
180
|
}
|
|
175
181
|
|
|
176
182
|
/** One human sentence for why something is not accepted. */
|
|
@@ -182,6 +188,7 @@ function whyNot(v, integrity) {
|
|
|
182
188
|
if (v.notRun.length) return `Checks did not really run: ${v.notRun.join(', ')}`;
|
|
183
189
|
if (v.fewerTests.length) return `Fewer tests ran than before in: ${v.fewerTests.join(', ')}`;
|
|
184
190
|
if (v.targetStill && v.targetStill.length) return `The task's own test still fails: ${v.targetStill.slice(0, 3).join('; ')}`;
|
|
191
|
+
if (v.unclear && v.unclear.length) return `${v.unclear.join(', ')} failed before and after the change, and BuildProof cannot compare them test by test, so it cannot tell whether this change broke more. Fix the old failures first, or run the tests with a reporter that names failing tests`;
|
|
185
192
|
if (v.regressions.length) {
|
|
186
193
|
const names = v.regressions.flatMap((s) => (v.testLevel && v.testLevel[s] ? v.testLevel[s].newFailures : [])).slice(0, 3);
|
|
187
194
|
return `The change broke: ${v.regressions.join(', ')}${names.length ? ' (' + names.join('; ') + ')' : ''}`;
|
package/core/hooks.js
CHANGED
|
@@ -30,9 +30,13 @@ function paths(root) {
|
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/** Is this hook entry / script one BuildProof generated? (never just "mentions buildproof") */
|
|
34
|
+
function ours(text) { const t = String(text || ''); return /buildproof/i.test(t) && /check --hook=(git|claude|cursor)|start --hook=(claude|cursor)/.test(t); }
|
|
35
|
+
const GIT_HEADER = '# buildproof: block the commit when the guarded change is not proven';
|
|
36
|
+
|
|
33
37
|
function status(root) {
|
|
34
38
|
const p = paths(root);
|
|
35
|
-
const has = (f) => { try { return fs.readFileSync(f, 'utf8')
|
|
39
|
+
const has = (f) => { try { return ours(fs.readFileSync(f, 'utf8')); } catch { return false; } };
|
|
36
40
|
return {
|
|
37
41
|
git: { available: fs.existsSync(path.join(root, '.git')), connected: has(p.git) },
|
|
38
42
|
claude: { available: true, connected: has(p.claude) },
|
|
@@ -44,13 +48,18 @@ function connectGit(root) {
|
|
|
44
48
|
const f = paths(root).git;
|
|
45
49
|
if (!fs.existsSync(path.join(root, '.git'))) return { ok: false, error: 'not_a_git_repo' };
|
|
46
50
|
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
47
|
-
|
|
48
|
-
if (prev.
|
|
49
|
-
|
|
51
|
+
let prev = fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : '';
|
|
52
|
+
if (prev.startsWith('#!/bin/sh\n' + GIT_HEADER)) { // ours from an older version: rewrite it (newer hooks let commits through when BuildProof is gone)
|
|
53
|
+
prev = fs.existsSync(f + '.bp-backup') ? 'x' : '';
|
|
54
|
+
} else if (prev) {
|
|
55
|
+
if (ours(prev)) return { ok: true, already: true }; // the user wired BuildProof into their own hook: leave it alone
|
|
56
|
+
fs.renameSync(f, f + '.bp-backup');
|
|
57
|
+
}
|
|
50
58
|
const script = [
|
|
51
59
|
'#!/bin/sh',
|
|
52
|
-
|
|
53
|
-
|
|
60
|
+
GIT_HEADER,
|
|
61
|
+
// fail open: if BuildProof was removed or moved (npx cache cleared, node switched), never block every commit
|
|
62
|
+
`if [ -f ${q(shPath(cli()))} ] && [ -x ${q(shPath(process.execPath))} ]; then ${q(shPath(process.execPath))} ${q(shPath(cli()))} check --hook=git || exit 1; else echo "BuildProof not found - commit allowed (run: npx buildproof init, or: npx buildproof uninstall)" >&2; fi`,
|
|
54
63
|
prev ? 'if [ -x .git/hooks/pre-commit.bp-backup ]; then exec .git/hooks/pre-commit.bp-backup "$@"; fi' : '',
|
|
55
64
|
'exit 0', '',
|
|
56
65
|
].filter((l) => l !== '').join('\n') + '\n';
|
|
@@ -63,7 +72,7 @@ function connectClaude(root) {
|
|
|
63
72
|
const j = readJson(f) || {};
|
|
64
73
|
j.hooks = j.hooks || {};
|
|
65
74
|
const add = (event, c) => {
|
|
66
|
-
j.hooks[event] = (j.hooks[event] || []).filter((g) => !JSON.stringify(g)
|
|
75
|
+
j.hooks[event] = (j.hooks[event] || []).filter((g) => !ours(JSON.stringify(g)));
|
|
67
76
|
j.hooks[event].push({ hooks: [{ type: 'command', command: c, timeout: 1800 }] });
|
|
68
77
|
};
|
|
69
78
|
add('UserPromptSubmit', cmd('start --hook=claude'));
|
|
@@ -78,7 +87,7 @@ function connectCursor(root) {
|
|
|
78
87
|
j.version = j.version || 1;
|
|
79
88
|
j.hooks = j.hooks || {};
|
|
80
89
|
const add = (event, c) => {
|
|
81
|
-
j.hooks[event] = (j.hooks[event] || []).filter((h) => !
|
|
90
|
+
j.hooks[event] = (j.hooks[event] || []).filter((h) => !ours(h.command));
|
|
82
91
|
j.hooks[event].push({ command: c, timeout: 1800 });
|
|
83
92
|
};
|
|
84
93
|
add('beforeSubmitPrompt', cmd('start --hook=cursor'));
|
|
@@ -91,6 +100,10 @@ function disconnect(root, tool) {
|
|
|
91
100
|
const f = paths(root)[tool];
|
|
92
101
|
if (!f || !fs.existsSync(f)) return { ok: true };
|
|
93
102
|
if (tool === 'git') {
|
|
103
|
+
const txt = fs.readFileSync(f, 'utf8');
|
|
104
|
+
if (!txt.startsWith('#!/bin/sh\n' + GIT_HEADER)) return { ok: true, skipped: 'not created by BuildProof - left as it is' };
|
|
105
|
+
// keep a copy in case the user added their own lines to our hook
|
|
106
|
+
try { fs.copyFileSync(f, f + '.bp-removed'); } catch { /* best effort */ }
|
|
94
107
|
fs.unlinkSync(f);
|
|
95
108
|
if (fs.existsSync(f + '.bp-backup')) fs.renameSync(f + '.bp-backup', f);
|
|
96
109
|
return { ok: true };
|
|
@@ -98,7 +111,8 @@ function disconnect(root, tool) {
|
|
|
98
111
|
const j = readJson(f);
|
|
99
112
|
if (!j || !j.hooks) return { ok: true };
|
|
100
113
|
for (const k of Object.keys(j.hooks)) {
|
|
101
|
-
|
|
114
|
+
// remove only our own commands, inside each group too, never other hooks that happen to mention buildproof
|
|
115
|
+
j.hooks[k] = (j.hooks[k] || []).map((h) => (h && Array.isArray(h.hooks) ? { ...h, hooks: h.hooks.filter((x) => !ours(x && x.command)) } : h)).filter((h) => !(h && Array.isArray(h.hooks) ? h.hooks.length === 0 : ours(h && h.command)));
|
|
102
116
|
if (!j.hooks[k].length) delete j.hooks[k];
|
|
103
117
|
}
|
|
104
118
|
if (!Object.keys(j.hooks).length) delete j.hooks;
|
package/core/integrity.js
CHANGED
|
@@ -55,7 +55,7 @@ const FRAMEWORK_RE = /require\(\s*['"](node:test|vitest|chai|@jest\/globals|moch
|
|
|
55
55
|
const NAMED_CASE_RE = /\b(it|test|describe|specify)\s*\(\s*['"`]|^\s*def\s+test_\w+\s*\(/m;
|
|
56
56
|
|
|
57
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;
|
|
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|xfail)\(|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
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
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
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,}/;
|
|
@@ -70,6 +70,8 @@ const RULE_TEXT = {
|
|
|
70
70
|
test_skipped: 'A test was skipped',
|
|
71
71
|
assertion_changed: 'An expected value in a test was changed',
|
|
72
72
|
mock_added: 'A new mock was added to a test',
|
|
73
|
+
code_patched: 'A test replaces the code it is supposed to test',
|
|
74
|
+
ci_changed: 'The CI workflow that runs BuildProof was changed',
|
|
73
75
|
sleep_added: 'A sleep / delay was added to the code',
|
|
74
76
|
silent_catch: 'An error is now silently swallowed',
|
|
75
77
|
checker_silenced: 'A type / lint check was silenced',
|
|
@@ -105,6 +107,228 @@ function proofScriptNames(scripts) {
|
|
|
105
107
|
function normLit(l) { return l.replace(/^`|`$/g, '"').replace(/^'|'$/g, '"'); }
|
|
106
108
|
function literals(line) { return (String(line).match(LIT_RE) || []).map(normLit); }
|
|
107
109
|
|
|
110
|
+
/** Source with comments removed (strings kept), and a same-length copy with string contents blanked,
|
|
111
|
+
* so an assertion that is commented out or only sits inside a string is not counted as an assertion. */
|
|
112
|
+
function codeViews(src, py) {
|
|
113
|
+
const t = String(src || ''); let code = ''; let blank = ''; let i = 0;
|
|
114
|
+
while (i < t.length) {
|
|
115
|
+
const c = t[i], n = t[i + 1];
|
|
116
|
+
if (!py && c === '/' && n === '/') { while (i < t.length && t[i] !== '\n') i++; continue; }
|
|
117
|
+
if (!py && c === '/' && n === '*') { const e = t.indexOf('*/', i + 2); const stop = e < 0 ? t.length : e + 2; const nl = t.slice(i, stop).replace(/[^\n]/g, ''); code += nl; blank += nl; i = stop; continue; }
|
|
118
|
+
if (py && c === '#') { while (i < t.length && t[i] !== '\n') i++; continue; }
|
|
119
|
+
if (!py && c === '/' && n !== '/' && n !== '*') { // a regex literal? (after an operator, bracket, comma or keyword)
|
|
120
|
+
const prevCode = code.replace(/\s+$/, ''); const pc = prevCode.slice(-1);
|
|
121
|
+
if (!prevCode || /[(,=:[!&|?{};+\-*%<>~^]/.test(pc) || /\b(return|typeof|case|in|of|delete|void|throw|new)$/.test(prevCode)) {
|
|
122
|
+
let j = i + 1; let cls = false;
|
|
123
|
+
while (j < t.length && t[j] !== '\n') { if (t[j] === '\\') { j += 2; continue; } if (t[j] === '[') cls = true; else if (t[j] === ']') cls = false; else if (t[j] === '/' && !cls) break; j++; }
|
|
124
|
+
if (j < t.length && t[j] === '/') { j++; while (j < t.length && /[a-z]/i.test(t[j])) j++; const lit = t.slice(i, j); code += lit; blank += '/' + ' '.repeat(Math.max(0, lit.length - 1)); i = j; continue; }
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (c === '"' || c === "'" || c === '`') {
|
|
128
|
+
const triple = py && t.slice(i, i + 3) === c.repeat(3); const q = triple ? c.repeat(3) : c; let j = i + q.length;
|
|
129
|
+
while (j < t.length && t.slice(j, j + q.length) !== q) { if (t[j] === '\\') j++; if (!triple && c !== '`' && t[j] === '\n') break; j++; }
|
|
130
|
+
j = Math.min(t.length, j + q.length);
|
|
131
|
+
const lit = t.slice(i, j); code += lit; blank += q + lit.slice(q.length, lit.length - q.length).replace(/[^\n]/g, ' ') + (lit.length >= 2 * q.length ? q : ''); i = j; continue;
|
|
132
|
+
}
|
|
133
|
+
code += c; blank += c; i++;
|
|
134
|
+
}
|
|
135
|
+
if (blank.length !== code.length) blank = blank.padEnd(code.length).slice(0, code.length);
|
|
136
|
+
return { code, blank };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** Every assertion in a test file, normalised (no whitespace, one quote style), so renaming a test, wrapping a line,
|
|
140
|
+
* adding a stronger assertion or switching to the strict assert module does not look like a weakened check.
|
|
141
|
+
* Comments and strings are ignored: a commented-out assertion is a removed assertion. */
|
|
142
|
+
function assertionKeys(src, py) {
|
|
143
|
+
const { code, blank } = codeViews(src, py);
|
|
144
|
+
const keys = [];
|
|
145
|
+
const norm = (x) => x.replace(/\s+/g, '').replace(/["'`]/g, "'").replace(/,\)/g, ')');
|
|
146
|
+
const call = /\b(expect|assert(?:\.\w+|[A-Z]\w*|_\w+|(?:_eq|_ne)?!)?|t\.(?:equal|is|not|deepEqual|true|false|throws)|Assert\.\w+|assertThat|self\.assert\w+|\$this->assert\w+)\s*\(/g;
|
|
147
|
+
const close = (from) => { let d = 1, k = from; for (; k < blank.length && d > 0; k++) { if (blank[k] === '(') d++; else if (blank[k] === ')') d--; } return k; };
|
|
148
|
+
let m;
|
|
149
|
+
while ((m = call.exec(blank)) && keys.length < 5000) {
|
|
150
|
+
if (m[1] === 'assert' && /^\s*=/.test(blank.slice(m.index + m[0].length - 1))) continue;
|
|
151
|
+
let end = close(m.index + m[0].length);
|
|
152
|
+
if (m[1] === 'expect') { const tail = blank.slice(end).match(/^(\s*\.\s*(?:not|resolves|rejects)\b)*\s*\.\s*\w+\s*\(/); if (tail) end = close(end + tail[0].length); }
|
|
153
|
+
keys.push(norm(code.slice(m.index, end))); (keys.pos || (keys.pos = [])).push(m.index); // BP_3131: positions
|
|
154
|
+
}
|
|
155
|
+
const pyAssert = /^[ \t]*assert[ \t]+(.+)$/gm; // Python assert statements (string contents blanked, so docstrings do not count)
|
|
156
|
+
while ((m = pyAssert.exec(blank))) { keys.push(norm(code.slice(m.index, m.index + m[0].length).replace(/^[ \t]*/, ''))); (keys.pos || (keys.pos = [])).push(m.index); }
|
|
157
|
+
return keys;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// ---------- BP_3131 rule 1: a new early `return <nothing / a literal>` before checks that existed before ----------
|
|
161
|
+
// Works on the code with comments removed, so `return null; // TODO` and `return None # skip` count too.
|
|
162
|
+
// Only the function the return actually leaves is looked at: a guard in a helper, a beforeEach or a forEach callback
|
|
163
|
+
// that has no old assertion after it in that same function is fine; `return done(err)` / `return promise` are real work.
|
|
164
|
+
const LIT_JS = /^\s*(?:null|undefined|true|false|NaN|Infinity|void\s*\(?\s*0\s*\)?|!\s*[01]|[-+]?\d[\d_]*(?:\.\d+)?(?:e[-+]?\d+)?n?|'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|`[^`$\\]*`|\{\s*\}|\[\s*\]|\(\s*(?:null|undefined|true|false|void\s*0|[-+]?\d+|'[^'\n]*'|"[^"\n]*"|\{\s*\}|\[\s*\])\s*\))?(?:\s+as\s+[\w$.<>\[\] |]{1,60})?\s*(?=;|\}|$|\belse\b|\)|,)/;
|
|
165
|
+
const LIT_PY = /^[ \t]*(?:None|True|False|[-+]?\d[\d_]*(?:\.\d+)?|'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|\(\s*\)|\[\s*\]|\{\s*\})?[ \t\r]*(?=;|$|\n)/;
|
|
166
|
+
|
|
167
|
+
/** Indexes (0-based) of the lines of `b` that are new compared with `a` (a real line diff, so a copied line does not
|
|
168
|
+
* make an untouched old line look new). Lines are compared whitespace-normalised. */
|
|
169
|
+
function addedLineIndexes(a, b) {
|
|
170
|
+
const A = a.map((x) => x.trim().replace(/\s+/g, ' ')), B = b.map((x) => x.trim().replace(/\s+/g, ' '));
|
|
171
|
+
let s = 0; while (s < A.length && s < B.length && A[s] === B[s]) s++;
|
|
172
|
+
let ea = A.length, eb = B.length; while (ea > s && eb > s && A[ea - 1] === B[eb - 1]) { ea--; eb--; }
|
|
173
|
+
const out = new Set(); const n = ea - s, m = eb - s;
|
|
174
|
+
if (!m) return out;
|
|
175
|
+
if (!n) { for (let j = s; j < eb; j++) out.add(j); return out; }
|
|
176
|
+
if (n * m > 4e6) { // too big for a table: fall back to counting (whitespace-normalised multiset)
|
|
177
|
+
const cnt = new Map(); for (let i = s; i < ea; i++) cnt.set(A[i], (cnt.get(A[i]) || 0) + 1);
|
|
178
|
+
for (let j = s; j < eb; j++) { const c = cnt.get(B[j]) || 0; if (c > 0) cnt.set(B[j], c - 1); else out.add(j); }
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
const W = m + 1; const L = new Uint32Array((n + 1) * W);
|
|
182
|
+
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i * W + j] = A[s + i] === B[s + j] ? L[(i + 1) * W + j + 1] + 1 : Math.max(L[(i + 1) * W + j], L[i * W + j + 1]);
|
|
183
|
+
let i = 0, j = 0;
|
|
184
|
+
while (i < n && j < m) { if (A[s + i] === B[s + j]) { i++; j++; } else if (L[(i + 1) * W + j] >= L[i * W + j + 1]) i++; else { out.add(s + j); j++; } }
|
|
185
|
+
for (; j < m; j++) out.add(s + j);
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Is the `{` at k (in the blank view) the body of a function (incl. TS return types, destructured / default params, methods)? */
|
|
190
|
+
function balancedType(t) { // a return-type annotation: balanced brackets, no statement characters
|
|
191
|
+
let d = 0; for (const ch of t) { if ('({[<'.includes(ch)) d++; else if (')}]>'.includes(ch)) { if (ch === '>' && d === 0) continue; d--; if (d < 0) return false; } else if (ch === ';' && d === 0) return false; }
|
|
192
|
+
return d === 0;
|
|
193
|
+
}
|
|
194
|
+
function isFunctionBrace(B, k) {
|
|
195
|
+
let tb = B.slice(Math.max(0, k - 400), k).replace(/\s+$/, '');
|
|
196
|
+
if (/=>$/.test(tb)) return true;
|
|
197
|
+
if (/(^|[^\w$])(else|try|finally|do|static|class\s+[\w$]+(\s+extends\s+[\w$.]+)?)$/.test(tb)) return false;
|
|
198
|
+
if (!/\)$/.test(tb)) { // a return type between `)` and `{`: ): { id: number } | null { ): Promise<(() => void) | null> {
|
|
199
|
+
let found = false;
|
|
200
|
+
for (let p = tb.length - 1, n = 0; p >= 0 && n < 12; p--) {
|
|
201
|
+
if (tb[p] !== ')') continue; n++;
|
|
202
|
+
const rest = tb.slice(p + 1);
|
|
203
|
+
if (/^\s*:/.test(rest) && balancedType(rest.replace(/^\s*:/, '').replace(/=>/g, ' '))) { tb = tb.slice(0, p + 1); found = true; break; }
|
|
204
|
+
}
|
|
205
|
+
if (!found) return false;
|
|
206
|
+
}
|
|
207
|
+
let d = 0, p = tb.length - 1; // matching ( of the parameter list
|
|
208
|
+
for (; p >= 0; p--) { const ch = tb[p]; if (ch === ')' || ch === ']' || ch === '}') d++; else if (ch === '(' || ch === '[' || ch === '{') { d--; if (d === 0) break; } }
|
|
209
|
+
if (p < 0) return false;
|
|
210
|
+
const head = tb.slice(0, p).replace(/\s*<[^<>()]{0,120}>\s*$/, '').replace(/\s+$/, ''); // generics: get<T>(
|
|
211
|
+
if (/(^|[^\w$.])(if|for|while|switch|catch|with|return|typeof|await|new)$/.test(head)) return false;
|
|
212
|
+
return /[\w$\]]$/.test(head); // function f( / method( / get x( / [Symbol.iterator](
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function earlyLiteralReturn(before, after, py, keysBefore) {
|
|
216
|
+
const old = new Set(keysBefore); if (!old.size) return null;
|
|
217
|
+
const vb = codeViews(before, py), va = codeViews(after, py);
|
|
218
|
+
const codeLines = va.code.split('\n');
|
|
219
|
+
const added = addedLineIndexes(vb.code.split('\n'), codeLines);
|
|
220
|
+
if (!added.size) return null;
|
|
221
|
+
const starts = []; { let o = 0; for (const l of codeLines) { starts.push(o); o += l.length + 1; } }
|
|
222
|
+
const lineOf = (pos) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= pos) lo = mid; else hi = mid - 1; } return lo; };
|
|
223
|
+
// old assertions = assertions with an old text that sit on a line the diff did NOT mark as new (a copied test is new)
|
|
224
|
+
// (counted: if a check appears as often as before it is still the old one, even when its line was edited;
|
|
225
|
+
// only copies beyond the old count, on new lines, are new)
|
|
226
|
+
const all = assertionKeys(va.code, py); const pos = all.pos || [];
|
|
227
|
+
const left = new Map(); for (const k of keysBefore) left.set(k, (left.get(k) || 0) + 1);
|
|
228
|
+
const order = pos.map((p, i) => i).sort((x, y) => (added.has(lineOf(pos[x])) - added.has(lineOf(pos[y]))) || (pos[x] - pos[y]));
|
|
229
|
+
const oldPos = [];
|
|
230
|
+
for (const i of order) { const c = left.get(all[i]) || 0; if (c > 0) { left.set(all[i], c - 1); oldPos.push(pos[i]); } }
|
|
231
|
+
oldPos.sort((x, y) => x - y);
|
|
232
|
+
if (!oldPos.length) return null;
|
|
233
|
+
const hasOldIn = (from, to) => { let lo = 0, hi = oldPos.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (oldPos[mid] < from) lo = mid + 1; else hi = mid; } return lo < oldPos.length && oldPos[lo] < to; };
|
|
234
|
+
// an existing guard whose condition was only edited is not a new return: pair added literal returns with removed ones
|
|
235
|
+
const retKey = (t) => t.replace(/\s+/g, '').replace(/^return(undefined|void\(?0\)?)?(?=;|\}|$)/, 'return');
|
|
236
|
+
const removedRet = new Map();
|
|
237
|
+
{ const bl = vb.code.split('\n'); const gone = addedLineIndexes(codeLines, bl);
|
|
238
|
+
for (const j of gone) { const r = (bl[j] || '').match(/\breturn\b.*$/); if (r) { const key = retKey(r[0]); removedRet.set(key, (removedRet.get(key) || 0) + 1); } } }
|
|
239
|
+
// candidate returns on added lines
|
|
240
|
+
const cands = [];
|
|
241
|
+
for (const li of [...added].sort((x, y) => x - y)) {
|
|
242
|
+
const cl = (codeLines[li] || '').replace(/\r$/, ''); const bl = va.blank.slice(starts[li], starts[li] + cl.length);
|
|
243
|
+
if (bl.length > 4000) continue;
|
|
244
|
+
const re = /\breturn\b/g; let m;
|
|
245
|
+
while ((m = re.exec(bl))) {
|
|
246
|
+
const lit = (py ? LIT_PY : LIT_JS).exec(cl.slice(m.index + 6));
|
|
247
|
+
if (!lit) continue;
|
|
248
|
+
const key = retKey(cl.slice(m.index)); const c = removedRet.get(key) || 0;
|
|
249
|
+
if (c > 0) { removedRet.set(key, c - 1); continue; }
|
|
250
|
+
cands.push({ li, pos: starts[li] + m.index, from: starts[li] + m.index + 6 + lit[0].length, text: cl.trim().slice(0, 160) });
|
|
251
|
+
if (cands.length > 2000) break;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (!cands.length) return null;
|
|
255
|
+
const report = (c, end) => (end > c.from && hasOldIn(c.from, end)) ? 'early return before the checks: ' + c.text : null;
|
|
256
|
+
if (py) {
|
|
257
|
+
// one forward pass: the def each line belongs to (indentation stack) and where that def ends
|
|
258
|
+
const indOf = (l) => (l.match(/^[ \t]*/) || [''])[0].replace(/\t/g, ' ').length;
|
|
259
|
+
const owner = new Int32Array(codeLines.length).fill(-1); const endOf = new Map(); const stack = [];
|
|
260
|
+
const blankL = va.blank.split('\n'); let par = 0;
|
|
261
|
+
for (let i = 0; i < codeLines.length; i++) {
|
|
262
|
+
const l = codeLines[i]; const cont = par > 0; // inside ( [ { of a previous line: a continuation, e.g. a multi-line def signature
|
|
263
|
+
for (const ch of blankL[i] || '') { if ('([{'.includes(ch)) par++; else if (')]}'.includes(ch) && par > 0) par--; }
|
|
264
|
+
if (!l.trim() || cont) { owner[i] = stack.length ? stack[stack.length - 1].i : -1; continue; }
|
|
265
|
+
const d = indOf(l);
|
|
266
|
+
while (stack.length && d <= stack[stack.length - 1].d) endOf.set(stack.pop().i, starts[i]);
|
|
267
|
+
owner[i] = stack.length ? stack[stack.length - 1].i : -1;
|
|
268
|
+
if (/^\s*(async\s+)?def\b/.test(l)) stack.push({ i, d });
|
|
269
|
+
}
|
|
270
|
+
for (const c of cands) { const o = owner[c.li]; const r = report(c, o < 0 ? va.code.length : (endOf.get(o) || va.code.length)); if (r) return r; }
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
// JS/TS: one forward pass over the braces; for each candidate the innermost enclosing FUNCTION body and its end
|
|
274
|
+
const B = va.blank; const stack = []; const want = cands.map((c) => c.pos); let w = 0; const fnOf = new Array(cands.length).fill(-1); const closeOf = new Map();
|
|
275
|
+
for (let k = 0; k <= B.length; k++) {
|
|
276
|
+
while (w < want.length && want[w] === k) { for (let s2 = stack.length - 1; s2 >= 0; s2--) if (stack[s2].fn) { fnOf[w] = stack[s2].k; break; } w++; }
|
|
277
|
+
if (k === B.length) break;
|
|
278
|
+
if (B[k] === '{') stack.push({ k, fn: isFunctionBrace(B, k) });
|
|
279
|
+
else if (B[k] === '}' && stack.length) { const o = stack.pop(); if (o.fn) closeOf.set(o.k, k + 1); }
|
|
280
|
+
}
|
|
281
|
+
for (let i = 0; i < cands.length; i++) { const o = fnOf[i]; const r = report(cands[i], o < 0 ? va.code.length : (closeOf.get(o) || va.code.length)); if (r) return r; }
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** An assertion that still exists but no longer runs: moved under a condition, behind an early return,
|
|
286
|
+
* or into a function nothing calls. Returns the offending text or null. */
|
|
287
|
+
function hiddenAssertion(before, after, py, keysBefore, added, rel) {
|
|
288
|
+
const named = /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.py$/i.test(String(rel).replace(/\\/g, '/'));
|
|
289
|
+
if (!named) return null;
|
|
290
|
+
{ const er = earlyLiteralReturn(before, after, py, keysBefore); if (er) return er; } // BP_3131
|
|
291
|
+
const A = /\b(expect|assert\w*|t\.(equal|is|deepEqual|true|false))\b/;
|
|
292
|
+
// only assertions that existed BEFORE the change matter here: new tests may use conditions and callbacks freely
|
|
293
|
+
const old = new Set(keysBefore);
|
|
294
|
+
const hasOld = (text) => assertionKeys(text, py).some((k) => old.has(k));
|
|
295
|
+
for (let i = 0; i < added.length; i++) {
|
|
296
|
+
const l = String(added[i]);
|
|
297
|
+
// a bare `return;` behind a condition, followed (same line) by an old assertion; `return done(err)` and friends are fine
|
|
298
|
+
if (!py && /(^|[{;]\s*)if\s*\(.+\)\s*\{?\s*return\s*;/.test(l) && hasOld(l)) return 'early return before the checks: ' + l.trim();
|
|
299
|
+
if (!py && /(^|[{;]\s*)if\s*\(.+\)\s*\{?\s*(expect\s*\(|assert\b|t\.(equal|is|deepEqual|true|false))/.test(l) && hasOld(l)) return 'assertion now only runs under a condition: ' + l.trim();
|
|
300
|
+
if (py && /^\s*if\b.+:\s*assert\b/.test(l) && hasOld(l)) return 'assertion now only runs under a condition: ' + l.trim();
|
|
301
|
+
}
|
|
302
|
+
// a new `if ...:` / `if (...) {` line wrapped around an existing assertion (the assertion line itself did not change)
|
|
303
|
+
const addedSet = new Set(added.map((x) => String(x).trim()));
|
|
304
|
+
const L = String(after || '').split(/\r?\n/);
|
|
305
|
+
for (let i = 0; i < L.length; i++) {
|
|
306
|
+
const l = L[i]; if (!addedSet.has(l.trim())) continue;
|
|
307
|
+
if (!py && /^\s*if\s*\(.+\)\s*\{?\s*return\s*;?\s*\}?\s*$/.test(l)) { let k = i + 1; while (k < L.length && !L[k].trim()) k++; if (k < L.length && hasOld(L[k])) return 'early return before the checks: ' + l.trim(); }
|
|
308
|
+
if (!(py ? /^\s*if\b.+:\s*$/.test(l) : /^\s*if\s*\(.+\)\s*\{\s*$/.test(l))) continue;
|
|
309
|
+
let j = i + 1; while (j < L.length && !L[j].trim()) j++;
|
|
310
|
+
if (j < L.length && /^\s*(assert\b|expect\s*\(|assert\.|t\.(equal|is|deepEqual))/.test(L[j]) && hasOld(L[j])) return 'assertion now only runs under a condition: ' + l.trim();
|
|
311
|
+
// `if x:` + `return` (bare) right before an old assertion
|
|
312
|
+
if (j < L.length && /^\s*return\s*;?\s*$/.test(L[j])) { let k = j + 1; while (k < L.length && !L[k].trim()) k++; if (k < L.length && hasOld(L[k])) return 'early return before the checks: ' + l.trim(); }
|
|
313
|
+
}
|
|
314
|
+
// moved into a function that nothing calls
|
|
315
|
+
const { code, blank } = codeViews(after, py);
|
|
316
|
+
const def = py ? /^[ \t]*def[ \t]+(\w+)\s*\(/gm : /(?:(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?(?:\([^)]*\)|\w+)\s*=>|function\s+(\w+)\s*\()/g;
|
|
317
|
+
let m;
|
|
318
|
+
while ((m = def.exec(blank))) {
|
|
319
|
+
const name = m[1] || m[2]; if (!name) continue;
|
|
320
|
+
if (py && /^test/i.test(name)) continue; // pytest calls test_* functions itself
|
|
321
|
+
const uses = (blank.match(new RegExp('\\b' + name + '\\b', 'g')) || []).length;
|
|
322
|
+
if (uses > 1) continue;
|
|
323
|
+
let body;
|
|
324
|
+
if (py) { const rest = code.slice(m.index); const lines = rest.split('\n'); const ind = (lines[0].match(/^[ \t]*/) || [''])[0].length; const out = [lines[0]]; for (const x of lines.slice(1)) { if (x.trim() && (x.match(/^[ \t]*/) || [''])[0].length <= ind) break; out.push(x); } body = out.join('\n'); }
|
|
325
|
+
else { const open = blank.indexOf('{', m.index); if (open < 0) continue; let d = 1, k = open + 1; for (; k < blank.length && d > 0; k++) { if (blank[k] === '{') d++; else if (blank[k] === '}') d--; } body = code.slice(m.index, k); }
|
|
326
|
+
const inside = assertionKeys(body, py);
|
|
327
|
+
if (inside.some((k) => keysBefore.includes(k))) return `assertion moved into ${name}(), which is never called`;
|
|
328
|
+
}
|
|
329
|
+
return null;
|
|
330
|
+
}
|
|
331
|
+
|
|
108
332
|
/** Literal groups from assertion lines of all test files: [['2','3','5'], ...] */
|
|
109
333
|
function assertionGroups(root, testFiles) {
|
|
110
334
|
const groups = [];
|
|
@@ -203,6 +427,20 @@ function analyze({ root, beforeDir, changes, testFiles }) {
|
|
|
203
427
|
const isTest = isTestFile(rel);
|
|
204
428
|
|
|
205
429
|
if (c.link) { add('outside_link', rel, c.link); continue; }
|
|
430
|
+
if (/^\.github\/workflows\/[^/]+\.ya?ml$/i.test(rel) && /buildproof/i.test(before || '')) {
|
|
431
|
+
// only changes that switch the BuildProof step off count; adding the workflow or bumping versions is fine
|
|
432
|
+
if (c.kind === 'deleted' || !/buildproof/i.test(after || '')) { add('ci_changed', rel, 'BuildProof step removed'); continue; }
|
|
433
|
+
const wd = lineDelta(before || '', after || '');
|
|
434
|
+
const bpBefore = lines(before).filter((l) => /buildproof/i.test(l)).map((l) => norm(l)); const bpAfter = new Set(lines(after).filter((l) => /buildproof/i.test(l)).map((l) => norm(l)));
|
|
435
|
+
const changedStep = bpBefore.find((l) => !bpAfter.has(l));
|
|
436
|
+
const bypass = wd.added.find((l) => /\|\|\s*(true|exit\s+0|:)\b|continue-on-error\s*:\s*true|^\s*(-\s*)?if\s*:\s*(false|\$\{\{\s*false)|BUILDPROOF_(SKIP|OFF)|buildproof\b.*--no-baseline|^\s*(paths|paths-ignore)\s*:/i.test(l));
|
|
437
|
+
if (bypass) { add('ci_changed', rel, bypass); continue; }
|
|
438
|
+
// BP_3131: the gate now runs in fewer cases (triggers narrowed, or a new if: on the BuildProof job / step)
|
|
439
|
+
const narrowed = triggerNarrowed(before || '', after || '');
|
|
440
|
+
if (narrowed) { add('ci_changed', rel, narrowed); continue; }
|
|
441
|
+
if (changedStep && !wd.added.some((l) => /buildproof\s+ci\b/i.test(l) && !/\|\||continue-on-error/i.test(l))) { add('ci_changed', rel, 'BuildProof step changed: ' + changedStep); continue; }
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
206
444
|
if (HOOK_FILE.test(rel)) {
|
|
207
445
|
if (/buildproof/i.test(before || '') && !/buildproof/i.test(after || '')) add('guard_disabled', rel, c.kind === 'deleted' ? 'file deleted' : 'buildproof hook removed');
|
|
208
446
|
else if (/"disableAllHooks"\s*:\s*true/.test(after || '') && !/"disableAllHooks"\s*:\s*true/.test(before || '')) add('guard_disabled', rel, 'disableAllHooks: true');
|
|
@@ -274,9 +512,22 @@ function analyze({ root, beforeDir, changes, testFiles }) {
|
|
|
274
512
|
const d = lineDelta(before || '', after || '');
|
|
275
513
|
const skip = d.added.find((l) => SKIP_RE.test(l));
|
|
276
514
|
if (skip) add('test_skipped', rel, skip);
|
|
515
|
+
else { // a bare return added before the checks makes a test pass without checking anything
|
|
516
|
+
const namedTest = /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.py$/i.test(rel);
|
|
517
|
+
const early = namedTest ? d.added.find((l) => /\b(test|it)\s*\(.*(=>\s*\{|function\s*\w*\s*\([^)]*\)\s*\{)\s*return\s*;|^\s*return\s*;?\s*(\/\/.*|#.*)?$/.test(l)) : null;
|
|
518
|
+
if (early && assertionKeys(after, /\.py$/i.test(rel)).length) add('test_skipped', rel, early.trim());
|
|
519
|
+
}
|
|
277
520
|
if (c.kind === 'modified') {
|
|
278
|
-
const
|
|
279
|
-
|
|
521
|
+
const py = /\.py$/i.test(rel);
|
|
522
|
+
const kb = assertionKeys(before, py); const ka = new Set(assertionKeys(after, py));
|
|
523
|
+
if (kb.length) { // compare the assertions themselves, not the lines they sit on
|
|
524
|
+
const gone = kb.filter((k) => !ka.has(k));
|
|
525
|
+
if (gone.length) add('assertion_changed', rel, gone[0].slice(0, 200));
|
|
526
|
+
else { const hid = hiddenAssertion(before, after, py, kb, d.added, rel); if (hid) add('assertion_changed', rel, hid); }
|
|
527
|
+
} else { // a language we cannot parse assertions in: fall back to lines
|
|
528
|
+
const goneAsserts = d.removed.filter((l) => ASSERT_RE.test(l));
|
|
529
|
+
if (goneAsserts.length) add('assertion_changed', rel, goneAsserts[0]);
|
|
530
|
+
}
|
|
280
531
|
}
|
|
281
532
|
// new mocks in an EXISTING test; in a brand-new test file only a mock of code this same change touched
|
|
282
533
|
// (a new test that mocks away the very code it should test proves nothing - mocking other things is fine)
|
|
@@ -286,7 +537,16 @@ function analyze({ root, beforeDir, changes, testFiles }) {
|
|
|
286
537
|
// a partial mock keeps the real module (requireActual / importActual inside the factory, often on the next lines)
|
|
287
538
|
if (i >= 0 && !/requireActual|importActual|importOriginal/.test(d.added.slice(i, i + 6).join('\n'))) mock = d.added[i];
|
|
288
539
|
}
|
|
540
|
+
// BP_3131: the same checks on whole mock calls, so a call wrapped over several lines counts too
|
|
541
|
+
if (!mock && c.kind === 'added' && /\.(c|m)?[jt]sx?$/i.test(rel)) {
|
|
542
|
+
const vv = codeViews(after || '', false);
|
|
543
|
+
for (const mc of mockCalls(vv.code, vv.blank)) { const one = mc.text.replace(/\s*\.\s*/g, '.'); if (!mc.partial && mocksChangedModule(one, changedCode, rel)) { mock = one.slice(0, 160); break; } }
|
|
544
|
+
if (!mock) mock = mockOnlyNewTest(after || '', (changes || []).filter((x) => x.kind !== 'deleted' && !isTestFile(x.file)).map((x) => x.file), rel, root);
|
|
545
|
+
}
|
|
289
546
|
if (mock) add('mock_added', rel, mock);
|
|
547
|
+
// the test overrides the very code under test (c.discount = ..., {...real, discount: ...}, rebinding an imported function)
|
|
548
|
+
const patched = patchesCode(d.added, (before || '') + '\n' + (after || ''), rel, changedCode, root); // imports from before too: dropping an import and redefining the name is the same trick
|
|
549
|
+
if (patched) add('code_patched', rel, patched);
|
|
290
550
|
const sil = d.added.find((l) => SILENCE_RE.test(l));
|
|
291
551
|
if (sil) add('checker_silenced', rel, sil);
|
|
292
552
|
const sc = addedMatch(before || '', after || '', SILENT_CATCH_RE);
|
|
@@ -312,6 +572,71 @@ function analyze({ root, beforeDir, changes, testFiles }) {
|
|
|
312
572
|
}
|
|
313
573
|
|
|
314
574
|
/** Multi-line pattern: count matches before vs after; report the first new one. */
|
|
575
|
+
/** Is this test (or a test helper / setup file) overriding code this same change touched? Returns the offending line or null. */
|
|
576
|
+
function patchesCode(added, src, testRel, changed, root = '') {
|
|
577
|
+
if (!added || !added.length) return null;
|
|
578
|
+
const t = String(testRel).replace(/\\/g, '/');
|
|
579
|
+
const tdir = path.posix.dirname(t);
|
|
580
|
+
const base = path.posix.basename(t);
|
|
581
|
+
const isHelper = !/\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.py$/i.test(base); // _setup.js, conftest.py, helpers
|
|
582
|
+
const subject = base.replace(/\.(c|m)?[jt]sx?$|\.py$/i, '').replace(/[._-](test|spec)s?$/i, '').replace(/^test_/i, '').replace(/_test$/i, '').toLowerCase();
|
|
583
|
+
const strip = (f) => f.replace(/\\/g, '/').replace(/\.(c|m)?[jt]sx?$/i, '').replace(/\/index$/i, '').toLowerCase();
|
|
584
|
+
// a helper / setup file belongs to the tests that load it: it "owns" their subjects only
|
|
585
|
+
let helperOwners = null;
|
|
586
|
+
if (isHelper) {
|
|
587
|
+
helperOwners = new Set();
|
|
588
|
+
try {
|
|
589
|
+
const abs = path.join(root, tdir); const stem = base.replace(/\.[^.]+$/, '');
|
|
590
|
+
for (const f of fs.readdirSync(abs)) {
|
|
591
|
+
if (f === base || !/\.(test|spec)\.[cm]?[jt]sx?$|^test_.+\.py$|_test\.py$/i.test(f)) continue;
|
|
592
|
+
const txt = read(path.join(abs, f)) || '';
|
|
593
|
+
if (new RegExp('[\'"/]' + stem.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '(\\.[cm]?[jt]sx?|\\.py)?[\'"]|import\\s+' + stem + '\\b|from\\s+\\S*' + stem + '\\s+import').test(txt)) helperOwners.add(f.replace(/\.(c|m)?[jt]sx?$|\.py$/i, '').replace(/[._-](test|spec)s?$/i, '').replace(/^test_/i, '').replace(/_test$/i, '').toLowerCase());
|
|
594
|
+
}
|
|
595
|
+
} catch { /* no folder */ }
|
|
596
|
+
}
|
|
597
|
+
const owns = (base2) => (isHelper ? helperOwners.has(base2.toLowerCase()) : base2.toLowerCase() === subject);
|
|
598
|
+
const esc = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
599
|
+
const objs = new Set(); const names = new Set();
|
|
600
|
+
// JS / TS bindings to a changed module
|
|
601
|
+
const jsChanged = (spec) => {
|
|
602
|
+
if (!/^[./]/.test(spec)) return null;
|
|
603
|
+
const target = strip(path.posix.normalize(path.posix.join(tdir, spec)));
|
|
604
|
+
const hit = changed.find((x) => /\.(c|m)?[jt]sx?$/i.test(x.file) && strip(x.file) === target);
|
|
605
|
+
if (hit && owns(hit.base)) return true;
|
|
606
|
+
// the test's own subject counts even when the change did not touch it (a test that rebinds what it tests proves nothing)
|
|
607
|
+
return !isHelper && target.split('/').pop() === subject;
|
|
608
|
+
};
|
|
609
|
+
let m;
|
|
610
|
+
const reObj = /(?:const|let|var)\s+(\w+)\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\)|import\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]|import\s+(\w+)\s*(?:,\s*\{[^}]*\})?\s+from\s+['"]([^'"]+)['"]/g;
|
|
611
|
+
while ((m = reObj.exec(src))) { const v = m[1] || m[3] || m[5]; const spec = m[2] || m[4] || m[6]; if (jsChanged(spec)) objs.add(v); }
|
|
612
|
+
const reNames = /(?:(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\))|(?:import\s*\{([^}]*)\}\s*from\s+['"]([^'"]+)['"])/g;
|
|
613
|
+
while ((m = reNames.exec(src))) { const list = m[1] || m[3]; const spec = m[2] || m[4]; if (jsChanged(spec)) for (const n of list.split(',')) { const local = n.split(/\s+as\s+|:/).pop().trim(); if (/^\w+$/.test(local)) names.add(local); } }
|
|
614
|
+
// Python bindings: from pkg.mod import a, b / import pkg.mod as m / from pkg import mod
|
|
615
|
+
const pyOwn = (mod) => { const last = mod.split('.').pop(); const hit = changed.find((x) => /\.py$/i.test(x.file) && x.base === last); return (hit && owns(hit.base)) || (!isHelper && last.toLowerCase() === subject); };
|
|
616
|
+
const rePyFrom = /^[ \t]*from[ \t]+([\w.]+)[ \t]+import[ \t]+(?:\(([\w\s,]+)\)|([\w \t,]+))/gm;
|
|
617
|
+
while ((m = rePyFrom.exec(src))) {
|
|
618
|
+
for (const n of (m[2] || m[3]).split(',')) { const parts = n.trim().split(/\s+as\s+/); const name = parts[0].trim(); const local = (parts[1] || parts[0]).trim(); if (!/^\w+$/.test(local)) continue;
|
|
619
|
+
if (pyOwn(m[1])) names.add(local); else if (pyOwn(m[1] + '.' + name)) objs.add(local); }
|
|
620
|
+
}
|
|
621
|
+
const rePyImp = /^\s*import\s+([\w.]+)(?:\s+as\s+(\w+))?/gm;
|
|
622
|
+
while ((m = rePyImp.exec(src))) if (pyOwn(m[1])) objs.add(m[2] || m[1]);
|
|
623
|
+
if (!objs.size && !names.size) return null;
|
|
624
|
+
for (const raw of added) {
|
|
625
|
+
const l = String(raw);
|
|
626
|
+
if (/requireActual|importActual|importOriginal/.test(l)) continue;
|
|
627
|
+
for (const o of objs) {
|
|
628
|
+
const O = esc(o);
|
|
629
|
+
if (new RegExp('(^|[^\\w.])' + O + '(\\.\\w+|\\[\\s*[\'"`]\\w+[\'"`]\\s*\\])\\s*=(?!=)').test(l)) return l.trim();
|
|
630
|
+
if (new RegExp('\\.\\.\\.\\s*' + O + '\\b[^}]*,\\s*\\w+\\s*:').test(l) || new RegExp('\\.\\.\\.\\s*' + O + '\\s*,\\s*$').test(l)) return l.trim();
|
|
631
|
+
if (new RegExp('Object\\.assign\\(\\s*' + O + '\\b').test(l)) return l.trim();
|
|
632
|
+
if (new RegExp('(^|[^.\\w])setattr\\(\\s*' + O + '\\s*,').test(l)) return l.trim();
|
|
633
|
+
if (new RegExp('(?:jest|vi)\\.spyOn\\(\\s*' + O + '\\s*,[^)]*\\)\\s*\\.(mockImplementation|mockReturnValue|mockResolvedValue|mockRejectedValue)').test(l)) return l.trim();
|
|
634
|
+
}
|
|
635
|
+
for (const n of names) if (new RegExp('^\\s*' + esc(n) + '\\s*=(?!=)\\s*(lambda\\b|(async\\s*)?(\\([^)]*\\)|\\w+)\\s*=>|function\\b|(unittest\\.)?(mock\\.)?(Magic)?Mock\\()').test(l)) return l.trim();
|
|
636
|
+
}
|
|
637
|
+
return null;
|
|
638
|
+
}
|
|
639
|
+
|
|
315
640
|
/** Does this line mock away the very module this new test file is about?
|
|
316
641
|
* Only one precise form counts, so ordinary dependency mocks are never flagged:
|
|
317
642
|
* jest.mock / vi.mock / jest.doMock / mock.module('<relative path>') where the path, resolved from the test file,
|
|
@@ -344,6 +669,243 @@ function mocksChangedModule(line, changed, testRel = '') {
|
|
|
344
669
|
return false;
|
|
345
670
|
}
|
|
346
671
|
|
|
672
|
+
// ---------- BP_3131 rule 2: the workflow that runs BuildProof now runs in FEWER cases ----------
|
|
673
|
+
// Only the top-level `on:` block counts (docker `tags:` in a step do not). Filters are compared as sets, so reordering,
|
|
674
|
+
// quoting, flow <-> block style and adding branches / events (broadening) are fine. Narrowing is flagged:
|
|
675
|
+
// a gate event (push / pull_request ...) removed, a branch / tag / path filter added or an entry removed from it,
|
|
676
|
+
// an -ignore entry added, a `types:` filter added or narrowed.
|
|
677
|
+
const GATE_EVENTS = new Set(['push', 'pull_request', 'pull_request_target', 'merge_group']);
|
|
678
|
+
|
|
679
|
+
function yamlStripComment(l) {
|
|
680
|
+
let q = null;
|
|
681
|
+
for (let i = 0; i < l.length; i++) {
|
|
682
|
+
const c = l[i];
|
|
683
|
+
if (q) { if (c === '\\' && q === '"') { i++; continue; } if (c === q) q = null; continue; }
|
|
684
|
+
if (c === '"' || c === "'") { q = c; continue; }
|
|
685
|
+
if (c === '#' && (i === 0 || /\s/.test(l[i - 1]))) return l.slice(0, i);
|
|
686
|
+
}
|
|
687
|
+
return l;
|
|
688
|
+
}
|
|
689
|
+
function yamlScalar(s) {
|
|
690
|
+
s = String(s).trim();
|
|
691
|
+
if (/^".*"$/.test(s)) { try { return JSON.parse(s); } catch { return s.slice(1, -1); } }
|
|
692
|
+
if (/^'.*'$/.test(s)) return s.slice(1, -1).replace(/''/g, "'");
|
|
693
|
+
return s;
|
|
694
|
+
}
|
|
695
|
+
/** Tiny flow-style parser: {a: [x, 'y'], b: {c: z}} */
|
|
696
|
+
function yamlFlow(src) {
|
|
697
|
+
let i = 0; const s = String(src);
|
|
698
|
+
const ws = () => { while (i < s.length && /\s/.test(s[i])) i++; };
|
|
699
|
+
const scalar = (stops) => {
|
|
700
|
+
ws(); if (s[i] === '"' || s[i] === "'") { const q = s[i]; let j = i + 1; while (j < s.length && s[j] !== q) { if (s[j] === '\\' && q === '"') j++; j++; } const r = yamlScalar(s.slice(i, j + 1)); i = j + 1; return r; }
|
|
701
|
+
let j = i; while (j < s.length && !stops.includes(s[j])) j++; const r = s.slice(i, j).trim(); i = j; return r;
|
|
702
|
+
};
|
|
703
|
+
const value = () => {
|
|
704
|
+
ws();
|
|
705
|
+
if (s[i] === '[') { i++; const arr = []; ws(); if (s[i] === ']') { i++; return arr; } for (;;) { arr.push(value()); ws(); if (s[i] === ',') { i++; ws(); if (s[i] === ']') { i++; return arr; } continue; } if (s[i] === ']') { i++; return arr; } throw new Error('flow list'); } }
|
|
706
|
+
if (s[i] === '{') { i++; const obj = {}; ws(); if (s[i] === '}') { i++; return obj; } for (;;) { const k = scalar([':', ',', '}']); ws(); let v = null; if (s[i] === ':') { i++; ws(); v = (s[i] === ',' || s[i] === '}') ? null : value(); } obj[k] = v; ws(); if (s[i] === ',') { i++; ws(); if (s[i] === '}') { i++; return obj; } continue; } if (s[i] === '}') { i++; return obj; } throw new Error('flow map'); } }
|
|
707
|
+
const r = scalar([',', ']', '}']); return r === '' ? null : r;
|
|
708
|
+
};
|
|
709
|
+
const v = value(); ws(); if (i < s.length) throw new Error('flow trailing'); return v;
|
|
710
|
+
}
|
|
711
|
+
/** Block-style YAML (mappings, lists, inline flow values) - enough for a workflow `on:` block. */
|
|
712
|
+
function yamlBlock(L, from, to) {
|
|
713
|
+
const ind = (l) => (l.match(/^ */) || [''])[0].length;
|
|
714
|
+
let i = from;
|
|
715
|
+
const next = () => { while (i < to && !L[i].trim()) i++; return i; };
|
|
716
|
+
const inline = (v) => { v = v.trim(); if (!v) return undefined; if (/^[[{]/.test(v)) return yamlFlow(v); if (/^[|>][-+0-9]*$/.test(v)) { const d0 = i > 0 ? ind(L[i - 1]) : 0; while (i < to && (!L[i].trim() || ind(L[i]) > d0)) i++; return ''; } return yamlScalar(v); };
|
|
717
|
+
const node = (minInd) => {
|
|
718
|
+
next(); if (i >= to) return null;
|
|
719
|
+
const d = ind(L[i]); if (d < minInd) return null;
|
|
720
|
+
if (/^\s*-(\s|$)/.test(L[i])) {
|
|
721
|
+
const arr = [];
|
|
722
|
+
while (next() < to && ind(L[i]) === d && /^\s*-(\s|$)/.test(L[i])) {
|
|
723
|
+
const rest = L[i].replace(/^\s*-\s?/, ''); i++;
|
|
724
|
+
const mm = rest.trim().match(/^("[^"]*"|'[^']*'|[^'"[{:][^:]*?)\s*:(?:\s+(.*)|$)/);
|
|
725
|
+
if (mm) { // `- cron: '0 1 * * *'` (+ more keys below): a one-line map
|
|
726
|
+
const o = {}; const v0 = inline(mm[2] || ''); o[yamlScalar(mm[1])] = v0 === undefined ? null : v0;
|
|
727
|
+
if (next() < to && ind(L[i]) > d && !/^\s*-(\s|$)/.test(L[i])) Object.assign(o, node(ind(L[i])) || {});
|
|
728
|
+
arr.push(o); continue;
|
|
729
|
+
}
|
|
730
|
+
const v = inline(rest); arr.push(v === undefined ? node(d + 1) : v);
|
|
731
|
+
}
|
|
732
|
+
return arr;
|
|
733
|
+
}
|
|
734
|
+
const obj = {};
|
|
735
|
+
while (next() < to && ind(L[i]) === d) {
|
|
736
|
+
const m = L[i].trim().match(/^("[^"]*"|'[^']*'|[^:]+?)\s*:(?:\s+(.*)|$)/);
|
|
737
|
+
if (!m) throw new Error('not a map line');
|
|
738
|
+
i++;
|
|
739
|
+
const k = yamlScalar(m[1]); let raw = m[2] || '';
|
|
740
|
+
if (/^\s*[[{]/.test(raw)) { // a flow list / map continued over several lines
|
|
741
|
+
const bal = (t) => { let d = 0, q = null; for (const ch of t) { if (q) { if (ch === q) q = null; continue; } if (ch === '"' || ch === "'") q = ch; else if ('[{'.includes(ch)) d++; else if (']}'.includes(ch)) d--; } return d; };
|
|
742
|
+
let n = 0; while (bal(raw) > 0 && i < to && n++ < 2000) raw += ' ' + L[i++].trim();
|
|
743
|
+
}
|
|
744
|
+
const v = inline(raw);
|
|
745
|
+
if (v !== undefined) { obj[k] = v; continue; }
|
|
746
|
+
next();
|
|
747
|
+
obj[k] = i < to && (ind(L[i]) > d || (ind(L[i]) === d && /^\s*-(\s|$)/.test(L[i]))) ? node(ind(L[i])) : null;
|
|
748
|
+
}
|
|
749
|
+
return obj;
|
|
750
|
+
};
|
|
751
|
+
return node(0);
|
|
752
|
+
}
|
|
753
|
+
/** The parsed `on:` value of a workflow, or { raw } when it cannot be read with confidence. null = no `on:`. */
|
|
754
|
+
function workflowOn(yaml) {
|
|
755
|
+
const L = lines(yaml).map((l) => yamlStripComment(l).replace(/\t/g, ' ').replace(/\s+$/, ''));
|
|
756
|
+
const k = L.findIndex((l) => /^(["']?)(on|true)\1\s*:(\s|$)/.test(l));
|
|
757
|
+
if (k < 0) return null;
|
|
758
|
+
let e = k + 1; while (e < L.length && (!L[e].trim() || /^\s/.test(L[e]) || /^-(\s|$)/.test(L[e]))) e++;
|
|
759
|
+
const head = L[k].replace(/^(["']?)(on|true)\1\s*:/, '').trim();
|
|
760
|
+
const raw = norm([head, ...L.slice(k + 1, e)].join(' '));
|
|
761
|
+
if (/(^|[\s,[{:])[&*][\w-]+|<<\s*:/.test(raw)) return { raw }; // anchors / aliases: compare the text only
|
|
762
|
+
try { return { v: head ? yamlFlow(head) : yamlBlock(L, k + 1, e), raw }; } catch { return { raw }; }
|
|
763
|
+
}
|
|
764
|
+
function onEvents(v) {
|
|
765
|
+
const out = new Map();
|
|
766
|
+
if (typeof v === 'string') out.set(v, {});
|
|
767
|
+
else if (Array.isArray(v)) for (const x of v) { if (typeof x === 'string') out.set(x, {}); }
|
|
768
|
+
else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) out.set(k, x && typeof x === 'object' && !Array.isArray(x) ? x : {});
|
|
769
|
+
return out;
|
|
770
|
+
}
|
|
771
|
+
const asSet = (x) => x == null ? null : new Set((Array.isArray(x) ? x : [x]).map((s) => String(s).trim()));
|
|
772
|
+
/** Returns a short reason when the trigger set got smaller, else null. */
|
|
773
|
+
function triggerNarrowed(before, after) {
|
|
774
|
+
const b = workflowOn(before), a = workflowOn(after);
|
|
775
|
+
if (!b) return null;
|
|
776
|
+
if (!a) return 'the `on:` triggers were removed';
|
|
777
|
+
if (b.v === undefined || a.v === undefined) return null; // cannot read it with confidence: no alarm
|
|
778
|
+
const eb = onEvents(b.v), ea = onEvents(a.v);
|
|
779
|
+
if (ea.has('workflow_call') && !eb.has('workflow_call')) return null; // turned into a reusable workflow: its callers decide
|
|
780
|
+
const glob = (g) => new RegExp('^' + String(g).replace(/[.+^${}()|\\[\]]/g, '\\$&').replace(/\*\*/g, '\u0000').replace(/\*/g, '[^/]*').replace(/\u0000/g, '.*').replace(/\?/g, '.') + '$');
|
|
781
|
+
const globsOf = new Map(); // compiled once per set
|
|
782
|
+
const covered = (x, set) => {
|
|
783
|
+
if (set.has(x)) return true;
|
|
784
|
+
let gs = globsOf.get(set); if (!gs) { gs = [...set].filter((g) => !String(g).startsWith('!') && /[*?]/.test(g)).slice(0, 200).map(glob); globsOf.set(set, gs); }
|
|
785
|
+
return gs.some((r) => r.test(x));
|
|
786
|
+
};
|
|
787
|
+
const everything = (set) => set && [...set].some((g) => g === '**') && ![...set].some((g) => String(g).startsWith('!'));
|
|
788
|
+
const PR_DEFAULT_TYPES = ['opened', 'synchronize', 'reopened'];
|
|
789
|
+
for (const [ev, fb] of eb) {
|
|
790
|
+
if (!ea.has(ev)) {
|
|
791
|
+
const twin = ev === 'pull_request' ? 'pull_request_target' : ev === 'pull_request_target' ? 'pull_request' : null;
|
|
792
|
+
if (twin && ea.has(twin) && !eb.has(twin)) continue; // pull_request <-> pull_request_target: still runs on every PR
|
|
793
|
+
if (GATE_EVENTS.has(ev)) return 'CI trigger removed: ' + ev; continue;
|
|
794
|
+
}
|
|
795
|
+
if (!GATE_EVENTS.has(ev)) continue; // release / issue_comment / workflow_run ... do not run the gate on code changes
|
|
796
|
+
const fa = ea.get(ev);
|
|
797
|
+
for (const key of ['branches', 'tags', 'paths', 'types']) {
|
|
798
|
+
const sb = asSet(fb[key]), sa = asSet(fa[key]);
|
|
799
|
+
if (sa && !sb && key === 'types' && /^pull_request/.test(ev) && PR_DEFAULT_TYPES.every((t) => sa.has(t))) continue; // covers GitHub's defaults
|
|
800
|
+
if (sa && !sb && key !== 'types' && everything(sa)) continue; // '**' = all refs / paths
|
|
801
|
+
if (sa && !sb && key !== 'types' && fb[key + '-ignore'] != null) { // branches-ignore: [x] -> branches: ['**', '!x']
|
|
802
|
+
const ig = asSet(fb[key + '-ignore']); const negs = new Set([...sa].filter((x) => String(x).startsWith('!')).map((x) => String(x).slice(1)));
|
|
803
|
+
if ([...sa].some((g) => g === '**') && [...negs].every((x) => ig.has(x))) continue;
|
|
804
|
+
}
|
|
805
|
+
if (sa && !sb) {
|
|
806
|
+
// GitHub: with only a tags filter a push no longer runs for branches (and the reverse). If the other kind of
|
|
807
|
+
// ref filter already existed, adding this one only adds cases (broadening).
|
|
808
|
+
const other = key === 'branches' ? ['tags', 'tags-ignore'] : key === 'tags' ? ['branches', 'branches-ignore'] : [];
|
|
809
|
+
if (!other.some((o) => fb[o] != null)) return `CI trigger filter added: ${ev}.${key}: [${[...sa].join(', ')}]`;
|
|
810
|
+
}
|
|
811
|
+
if (sb && sa) {
|
|
812
|
+
const gone = [...sb].filter((x) => !String(x).startsWith('!') && !covered(x, sa)); if (gone.length) return `CI trigger filter narrowed: ${ev}.${key} lost ${gone.join(', ')}`;
|
|
813
|
+
const neg = [...sa].filter((x) => String(x).startsWith('!') && !sb.has(x)); if (neg.length) return `CI trigger filter narrowed: ${ev}.${key} added ${neg.join(', ')}`;
|
|
814
|
+
}
|
|
815
|
+
if (sb && !sa && (key === 'branches' || key === 'tags')) { // dropping one ref filter while the other stays: those refs stop running
|
|
816
|
+
const other = key === 'branches' ? ['tags', 'tags-ignore'] : ['branches', 'branches-ignore'];
|
|
817
|
+
if (other.some((o) => fa[o] != null)) return `CI trigger filter narrowed: ${ev}.${key} removed`;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
for (const key of ['branches-ignore', 'tags-ignore', 'paths-ignore']) {
|
|
821
|
+
const sb = asSet(fb[key]) || new Set(), sa = asSet(fa[key]) || new Set();
|
|
822
|
+
const extra = [...sa].filter((x) => !sb.has(x));
|
|
823
|
+
if (extra.length) return `CI trigger filter narrowed: ${ev}.${key} added ${extra.join(', ')}`;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
return null;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// ---------- BP_3131 rule 3: a NEW test file that only talks to mocks of the changed code ----------
|
|
830
|
+
// Flagged only when the new JS/TS test fully mocks code changed in this change AND loads no project code for real.
|
|
831
|
+
// A new test that mocks changed ./db but runs the real ./service (changed or not) is ordinary and stays fine.
|
|
832
|
+
// Anything we cannot resolve (an alias, a computed require path) means "maybe real code": not flagged.
|
|
833
|
+
const BUILTINS = new Set(require('module').builtinModules);
|
|
834
|
+
const TEST_LIBS = /^(vitest|jest|@jest\/globals|mocha|chai|sinon|ava|tap|uvu|expect|supertest|nock|msw|react|react-dom|@testing-library\/[\w-]+|@vue\/test-utils|@playwright\/test|@vitest\/[\w-]+)$/;
|
|
835
|
+
const _deps = new Map();
|
|
836
|
+
function declaredDeps(root) { // the packages the project itself declares (outside packages, not its own code)
|
|
837
|
+
if (!root) return new Set(); if (_deps.has(root)) return _deps.get(root);
|
|
838
|
+
let set = new Set();
|
|
839
|
+
try { const pj = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); set = new Set(Object.keys({ ...(pj.dependencies || {}), ...(pj.devDependencies || {}), ...(pj.peerDependencies || {}) })); if (pj.workspaces) for (const k of [...set]) { /* workspace deps may be local */ } } catch {}
|
|
840
|
+
if (_deps.size > 50) _deps.clear(); _deps.set(root, set); return set;
|
|
841
|
+
}
|
|
842
|
+
const MOCK_CALL_RE = /\b(?:jest|vi)\s*\.\s*(?:mock|doMock|unstable_mockModule|setMock)\s*\(|\bmock\s*\.\s*module\s*\(/g;
|
|
843
|
+
|
|
844
|
+
function mockCalls(code, blank) {
|
|
845
|
+
const out = []; let m; MOCK_CALL_RE.lastIndex = 0;
|
|
846
|
+
while ((m = MOCK_CALL_RE.exec(blank)) && out.length < 300) {
|
|
847
|
+
const open = m.index + m[0].length; let d = 1, k = open; const lim = Math.min(blank.length, open + 20000);
|
|
848
|
+
for (; k < lim && d > 0; k++) { if (blank[k] === '(') d++; else if (blank[k] === ')') d--; }
|
|
849
|
+
const args = code.slice(open, k - 1);
|
|
850
|
+
const spec = args.match(/^\s*(?:import\s*\(\s*|require\s*\.\s*resolve\s*\(\s*)?(['"`])([^'"`$\n]+)\1/);
|
|
851
|
+
const argsBlank = blank.slice(open, k - 1);
|
|
852
|
+
const partial = (/\b(requireActual|importActual)\s*\(|\bimportOriginal\s*\(/.test(argsBlank) || /\bspy\s*:\s*true\b/.test(args)) && !/\bsetMock\b/.test(m[0]); // vi.mock(p, { spy: true }) keeps the real code
|
|
853
|
+
out.push({ start: m.index, end: k, spec: spec ? spec[2] : null, partial, text: code.slice(m.index, k).replace(/\s+/g, ' ') });
|
|
854
|
+
}
|
|
855
|
+
return out;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
function mockOnlyNewTest(src, changedFiles, testRel, root) {
|
|
859
|
+
const t = String(testRel).replace(/\\/g, '/');
|
|
860
|
+
if (!/\.(c|m)?[jt]sx?$/i.test(t)) return null;
|
|
861
|
+
const strip = (f) => f.replace(/\\/g, '/').replace(/\.(c|m)?[jt]sx?$/i, '').replace(/\/index$/i, '').toLowerCase();
|
|
862
|
+
const changed = new Set(changedFiles.filter((f) => /\.(c|m)?[jt]sx?$/i.test(f)).map(strip));
|
|
863
|
+
if (!changed.size) return null;
|
|
864
|
+
const { code, blank } = codeViews(src, false);
|
|
865
|
+
const calls = mockCalls(code, blank);
|
|
866
|
+
if (!calls.length) return null;
|
|
867
|
+
const rel = (spec) => strip(path.posix.normalize(path.posix.join(path.posix.dirname(t), spec)));
|
|
868
|
+
const full = new Map();
|
|
869
|
+
for (const c of calls) {
|
|
870
|
+
if (!c.spec) return null; // a computed path: cannot tell
|
|
871
|
+
if (c.partial || !/^[./]/.test(c.spec)) continue;
|
|
872
|
+
const tg = rel(c.spec); if (changed.has(tg) && !full.has(tg)) full.set(tg, c.text.slice(0, 160));
|
|
873
|
+
}
|
|
874
|
+
if (!full.size) return null;
|
|
875
|
+
// what the test loads, with the mock calls themselves blanked out (vi.mock(import('./db')) is not a real import)
|
|
876
|
+
let b = blank, c2 = code;
|
|
877
|
+
for (const c of calls) { b = b.slice(0, c.start) + ' '.repeat(c.end - c.start) + b.slice(c.end); c2 = c2.slice(0, c.start) + ' '.repeat(c.end - c.start) + c2.slice(c.end); }
|
|
878
|
+
const specs = []; let m;
|
|
879
|
+
const dyn = /\b(require|import)\s*\(/g;
|
|
880
|
+
while ((m = dyn.exec(b))) {
|
|
881
|
+
if (m[1] === 'require' && /\.\s*$/.test(b.slice(0, m.index))) continue;
|
|
882
|
+
const a = c2.slice(m.index + m[0].length).match(/^\s*(['"`])([^'"`$\n]+)\1\s*\)/);
|
|
883
|
+
if (!a) return null; // require(path.join(...)), import(x): cannot tell
|
|
884
|
+
specs.push(a[2]);
|
|
885
|
+
}
|
|
886
|
+
// jest.requireActual('./db') outside a mock factory loads the real code
|
|
887
|
+
const act = /\b(?:jest|vi)\s*\.\s*(?:requireActual|importActual)\s*(?:<[^>]*>)?\s*\(/g;
|
|
888
|
+
while ((m = act.exec(b))) return null;
|
|
889
|
+
const stat = /(^|[;\n])[ \t]*(import|export)\b([^;'"`]{0,2000}?)\bfrom[ \t]*(['"`])([^'"`\n]+)\4|(^|[;\n])[ \t]*import[ \t]*(['"`])([^'"`\n]+)\7/g;
|
|
890
|
+
while ((m = stat.exec(c2))) {
|
|
891
|
+
if (m[5]) { if (/^\s*type\b/.test(m[3] || '')) continue; specs.push(m[5]); } else specs.push(m[8]);
|
|
892
|
+
}
|
|
893
|
+
for (const s of specs) {
|
|
894
|
+
if (/^[./]/.test(s)) { if (!full.has(rel(s))) return null; continue; } // real project code is loaded
|
|
895
|
+
if (/^node:/.test(s) || BUILTINS.has(s.split('/')[0])) continue;
|
|
896
|
+
if (/^[a-z@]/i.test(s) && !/^[@~#]\//.test(s)) {
|
|
897
|
+
// counts as an outside package only when it is really installed (not a workspace link, not a path alias)
|
|
898
|
+
const pkg = s.startsWith('@') ? s.split('/').slice(0, 2).join('/') : s.split('/')[0];
|
|
899
|
+
if (TEST_LIBS.test(pkg) || declaredDeps(root).has(pkg)) continue;
|
|
900
|
+
let st = null; try { st = root ? fs.lstatSync(path.join(root, 'node_modules', pkg)) : null; } catch { st = null; }
|
|
901
|
+
if (!st || st.isSymbolicLink()) return null;
|
|
902
|
+
continue;
|
|
903
|
+
}
|
|
904
|
+
return null; // @/x, ~/x, #x: an alias into the project, cannot tell
|
|
905
|
+
}
|
|
906
|
+
return [...full.values()][0];
|
|
907
|
+
}
|
|
908
|
+
|
|
347
909
|
function addedMatch(before, after, re) {
|
|
348
910
|
const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g');
|
|
349
911
|
const mb = (before.match(g) || []).map(norm);
|
package/core/server.js
CHANGED
|
@@ -174,6 +174,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
174
174
|
<div class="top"><img src="icon-192.png" alt=""><h1>Connect a phone or tablet</h1></div>
|
|
175
175
|
<p>Scan this code with the phone or tablet camera, then use Share, Add to Home Screen.</p>
|
|
176
176
|
<p class="${https ? 'ok' : 'warn'}">${https ? 'Secure HTTPS link - camera sharing works.' : 'Plain http link - for camera sharing turn on HTTPS: tailscale serve --bg ' + cfg.port}</p>
|
|
177
|
+
${!https && /^(127\.|localhost$|::1$)/.test(String(cfg.host)) ? '<p class="warn">Phone and tablet access is OFF: BuildProof only answers on this computer. To allow devices on your network, run: npx buildproof remote on</p>' : ''}
|
|
177
178
|
${links.map((l, i) => `<div class="q"><div id="q${i}"></div><p>${l.replace(/token=.*/, 'token=...')}</p></div>`).join('')}
|
|
178
179
|
<p><a href="/?token=${encodeURIComponent(cfg.token)}">Open BuildProof on this computer</a></p>
|
|
179
180
|
<script>const L=${JSON.stringify(links)};L.forEach((l,i)=>{try{new QRCode(document.getElementById('q'+i),{text:l,width:280,height:280})}catch(e){document.getElementById('q'+i).textContent='QR code needs internet to load.'}});</script></body></html>`;
|
package/core/service.js
CHANGED
|
@@ -42,6 +42,35 @@ function stopOld(info) {
|
|
|
42
42
|
return stopped;
|
|
43
43
|
}
|
|
44
44
|
|
|
45
|
+
/** Stop the running BuildProof service (its guard first, so it is not restarted). Only verified BuildProof processes. */
|
|
46
|
+
async function stop() {
|
|
47
|
+
const { isOurs } = require('./procs');
|
|
48
|
+
const cfg = config.load();
|
|
49
|
+
let stopped = 0;
|
|
50
|
+
try {
|
|
51
|
+
const g = Number(String(fs.readFileSync(path.join(config.LOG_DIR, 'server_guard.pid'), 'utf8')).trim());
|
|
52
|
+
if (g > 0 && g !== process.pid && isOurs(g, 'guard', true) === true) { try { process.kill(g); stopped++; } catch { /* gone */ } }
|
|
53
|
+
} catch { /* no guard */ }
|
|
54
|
+
const info = await healthInfo(cfg.port, 1500);
|
|
55
|
+
if (info && info.pid > 0 && info.pid !== process.pid && isOurs(info.pid, 'server', true) === true) { try { process.kill(info.pid); stopped++; } catch { /* gone */ } }
|
|
56
|
+
for (let i = 0; i < 15; i++) { if (!(await healthInfo(cfg.port, 500))) break; await new Promise((r) => setTimeout(r, 300)); }
|
|
57
|
+
return { stopped, stillRunning: !!(await healthInfo(cfg.port, 500)) };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Remove the start-at-login entry, whatever this platform used. Returns what was removed. */
|
|
61
|
+
function removeAutostart() {
|
|
62
|
+
const home = os.homedir(); const gone = [];
|
|
63
|
+
const rm = (f) => { try { if (fs.existsSync(f)) { fs.unlinkSync(f); gone.push(f); } } catch { /* keep going */ } };
|
|
64
|
+
if (process.platform === 'win32') rm(path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', 'BuildProof.vbs'));
|
|
65
|
+
if (process.platform === 'darwin') { const f = path.join(home, 'Library', 'LaunchAgents', 'dev.buildproof.guard.plist'); if (fs.existsSync(f)) spawnSync('launchctl', ['unload', '-w', f], { stdio: 'ignore' }); rm(f); }
|
|
66
|
+
if (process.platform === 'linux') {
|
|
67
|
+
const unit = path.join(home, '.config', 'systemd', 'user', 'buildproof.service');
|
|
68
|
+
if (fs.existsSync(unit)) { spawnSync('systemctl', ['--user', 'disable', '--now', 'buildproof.service'], { stdio: 'ignore' }); rm(unit); spawnSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore' }); }
|
|
69
|
+
rm(path.join(home, '.config', 'autostart', 'buildproof.desktop'));
|
|
70
|
+
}
|
|
71
|
+
return gone;
|
|
72
|
+
}
|
|
73
|
+
|
|
45
74
|
function startDetached() {
|
|
46
75
|
const child = spawn(NODE, [GUARD], { detached: true, stdio: 'ignore', windowsHide: true, cwd: config.ROOT, env: process.env });
|
|
47
76
|
child.unref();
|
|
@@ -117,4 +146,4 @@ async function ensure({ autostart = true } = {}) {
|
|
|
117
146
|
return { ok: true, how, autostart: auto, port: cfg.port };
|
|
118
147
|
}
|
|
119
148
|
|
|
120
|
-
module.exports = { ensure, health, healthInfo, installAutostart, startDetached };
|
|
149
|
+
module.exports = { ensure, health, healthInfo, installAutostart, removeAutostart, startDetached, stop };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "buildproof",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.13.1",
|
|
4
4
|
"description": "BuildProof - proof gate for AI-written code: test-integrity guard, fail-closed checks, scope lock, full rollback, signed certificates, local AI under supervision.",
|
|
5
5
|
"main": "core/server.js",
|
|
6
6
|
"scripts": {
|