buildproof 3.12.3 → 3.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -4
- package/bin/buildproof.js +58 -8
- package/core/certs.js +37 -5
- package/core/ci.js +28 -1
- 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 +237 -5
- 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({});
|
|
@@ -148,7 +158,13 @@ async function main() {
|
|
|
148
158
|
if (cmd === 'ci' || cmd === 'spec') { // pull request check (Team+) / spec check (Pro+): no background service needed
|
|
149
159
|
const ci = require('../core/ci');
|
|
150
160
|
const folder = positional[0] || process.cwd();
|
|
151
|
-
if (cmd === 'ci' && flag('init')) {
|
|
161
|
+
if (cmd === 'ci' && flag('init')) {
|
|
162
|
+
const r = ci.init(folder);
|
|
163
|
+
const bp = await ci.baseProtection(folder); // only advice: never fails the command
|
|
164
|
+
if (bp.protected === false) console.log(`Warning: ${bp.branch} is not protected. An agent that can push to ${bp.branch} can weaken the baseline too. Protect it so only pull requests can change it: https://github.com/${bp.repo}/settings/branches`);
|
|
165
|
+
else if (bp.protected === null && bp.repo) console.log(`Note: could not check whether ${bp.branch} is protected (${bp.note}). Make sure only pull requests can change it.`);
|
|
166
|
+
out(r.ok ? `CI_WORKFLOW ${r.file} - add your key as the BUILDPROOF_LICENSE secret` : `CI_WORKFLOW_EXISTS ${r.file}`, r.ok ? 0 : 1);
|
|
167
|
+
}
|
|
152
168
|
const lic = ci.licensed(require('../core/license'), cmd);
|
|
153
169
|
if (!lic.ok) out(`CANNOT_CHECK ${lic.why}`, 2);
|
|
154
170
|
const base = typeof flag('base') === 'string' ? flag('base') : null;
|
|
@@ -166,7 +182,13 @@ async function main() {
|
|
|
166
182
|
const cert = JSON.parse(m ? m[1] : raw);
|
|
167
183
|
const ok = certs.verify(cert);
|
|
168
184
|
if (!ok) out('INVALID signature - the certificate was modified (or names a key it was not signed with)', 1);
|
|
169
|
-
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
|
+
}
|
|
170
192
|
// --rerun: is this exactly the certified code, and do the checks really pass here?
|
|
171
193
|
const rr = cert.payload.rerun;
|
|
172
194
|
if (!rr) out(`VALID ${cert.payload.id} - this certificate is too old for --rerun`, 1);
|
|
@@ -207,7 +229,7 @@ async function main() {
|
|
|
207
229
|
const r = await require('../core/bug-hunter/engine').repro(path.resolve(positional[1] || process.cwd()), f);
|
|
208
230
|
out(`${r.reproduced ? 'REPRODUCED' : 'NOT_REPRODUCED'} ${f.oracle} ${f.file} ${f.export}(${f.inputPreview}) -> ${r.outcome}`, r.reproduced ? 0 : 1);
|
|
209
231
|
}
|
|
210
|
-
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
|
|
211
233
|
const sv = await require('../core/service').ensure({ autostart: false });
|
|
212
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);
|
|
213
235
|
}
|
|
@@ -267,6 +289,7 @@ async function main() {
|
|
|
267
289
|
const good = !r.round1.proven && r.round2.proven;
|
|
268
290
|
console.log('');
|
|
269
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`);
|
|
270
293
|
out(`TRY ${good ? 'OK' : 'UNEXPECTED'} shortcut=${r.round1.proven ? 'PROVEN' : 'NOT_PROVEN'} real_fix=${r.round2.proven ? 'PROVEN' : 'NOT_PROVEN'}`, good ? 0 : 1);
|
|
271
294
|
}
|
|
272
295
|
if (cmd === 'open') { const u = `http://127.0.0.1:${config.load().port || 38700}/connect`; openUrl(u); out('OPEN ' + u, 0); }
|
|
@@ -275,8 +298,34 @@ async function main() {
|
|
|
275
298
|
if (r.ok && typeof r.version !== 'string') out(`DOWN unexpected answer on port ${config.load().port}`, 1);
|
|
276
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);
|
|
277
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
|
+
}
|
|
278
325
|
if (!['start', 'check', 'accept', 'rollback', 'connect', 'try'].includes(cmd)) {
|
|
279
|
-
|
|
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);
|
|
280
329
|
}
|
|
281
330
|
|
|
282
331
|
const input = await readStdin();
|
|
@@ -332,7 +381,8 @@ async function main() {
|
|
|
332
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'));
|
|
333
382
|
}
|
|
334
383
|
const extra = [integ.length ? 'integrity: ' + integ.join('; ') : '', falseClaims.length ? 'claims: ' + falseClaims.join('; ') : '', full.revertCheck ? 'revert: ' + full.revertCheck.verdict : ''].filter(Boolean).join(' | ');
|
|
335
|
-
|
|
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);
|
|
336
386
|
}
|
|
337
387
|
if (cmd === 'accept') {
|
|
338
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/ci.js
CHANGED
|
@@ -267,4 +267,31 @@ function init(root) {
|
|
|
267
267
|
return { ok: true, file: f };
|
|
268
268
|
}
|
|
269
269
|
|
|
270
|
-
|
|
270
|
+
/** Is the base branch protected on GitHub? An agent that can push to it can weaken the baseline too.
|
|
271
|
+
* Never fails: returns { protected: true|false|null, branch, repo, note }. */
|
|
272
|
+
function baseProtection(root, env = process.env) {
|
|
273
|
+
const { execFileSync } = require('child_process');
|
|
274
|
+
const git = (a) => { try { return execFileSync('git', a, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 }).trim(); } catch { return ''; } };
|
|
275
|
+
const url = git(['remote', 'get-url', 'origin']);
|
|
276
|
+
const m = url.match(/(?:^|[@/])github\.com(?::\d+)?[:/]+([^/]+)\/([^/]+?)(?:\.git)?\/?$/i);
|
|
277
|
+
if (!m) return Promise.resolve({ protected: null, repo: url ? 'origin' : '', branch: 'your base branch', note: url ? 'not a github.com repository' : 'no git remote' });
|
|
278
|
+
const has = (ref) => !!git(['rev-parse', '--verify', '--quiet', ref]);
|
|
279
|
+
const branch = (git(['symbolic-ref', '--quiet', '--short', 'refs/remotes/origin/HEAD']).replace(/^origin\//, ''))
|
|
280
|
+
|| ['main', 'master'].find((b) => has('refs/remotes/origin/' + b)) || ['main', 'master'].find((b) => has('refs/heads/' + b)) || 'main';
|
|
281
|
+
const repo = `${m[1]}/${m[2]}`;
|
|
282
|
+
const token = env.GITHUB_TOKEN || env.GH_TOKEN || '';
|
|
283
|
+
return new Promise((resolve) => { try {
|
|
284
|
+
const req = require('https').request({ host: 'api.github.com', path: `/repos/${encodeURIComponent(m[1])}/${encodeURIComponent(m[2])}/branches/${encodeURIComponent(branch)}`, method: 'GET', timeout: 5000,
|
|
285
|
+
headers: { 'user-agent': 'buildproof', accept: 'application/vnd.github+json', ...(token ? { authorization: 'Bearer ' + token } : {}) } }, (res) => {
|
|
286
|
+
let b = ''; res.on('data', (d) => { b += d; });
|
|
287
|
+
res.on('end', () => { let j = null; try { j = JSON.parse(b); } catch { /* not json */ }
|
|
288
|
+
if (res.statusCode === 200 && j && typeof j.protected === 'boolean') resolve({ protected: j.protected, branch, repo });
|
|
289
|
+
else resolve({ protected: null, branch, repo, note: res.statusCode === 404 ? (token ? 'branch not found, or the token has no access' : 'private repository or branch not found: set GITHUB_TOKEN to check') : res.statusCode === 401 ? 'the GitHub token was refused' : res.statusCode === 403 ? 'GitHub rate limit or no access' : 'GitHub did not answer' }); });
|
|
290
|
+
});
|
|
291
|
+
req.on('timeout', () => req.destroy(new Error('timeout')));
|
|
292
|
+
req.on('error', () => resolve({ protected: null, branch, repo, note: 'GitHub not reachable' }));
|
|
293
|
+
req.end();
|
|
294
|
+
} catch { resolve({ protected: null, branch, repo, note: 'could not ask GitHub' }); } });
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
module.exports = { baseProtection, check, init, licensed, changesBetween, findBase, markdown, parseSpec, testNameIn, WORKFLOW };
|
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,102 @@ 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)));
|
|
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]*/, '')));
|
|
157
|
+
return keys;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** An assertion that still exists but no longer runs: moved under a condition, behind an early return,
|
|
161
|
+
* or into a function nothing calls. Returns the offending text or null. */
|
|
162
|
+
function hiddenAssertion(before, after, py, keysBefore, added, rel) {
|
|
163
|
+
const named = /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.py$/i.test(String(rel).replace(/\\/g, '/'));
|
|
164
|
+
if (!named) return null;
|
|
165
|
+
const A = /\b(expect|assert\w*|t\.(equal|is|deepEqual|true|false))\b/;
|
|
166
|
+
// only assertions that existed BEFORE the change matter here: new tests may use conditions and callbacks freely
|
|
167
|
+
const old = new Set(keysBefore);
|
|
168
|
+
const hasOld = (text) => assertionKeys(text, py).some((k) => old.has(k));
|
|
169
|
+
for (let i = 0; i < added.length; i++) {
|
|
170
|
+
const l = String(added[i]);
|
|
171
|
+
// a bare `return;` behind a condition, followed (same line) by an old assertion; `return done(err)` and friends are fine
|
|
172
|
+
if (!py && /(^|[{;]\s*)if\s*\(.+\)\s*\{?\s*return\s*;/.test(l) && hasOld(l)) return 'early return before the checks: ' + l.trim();
|
|
173
|
+
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();
|
|
174
|
+
if (py && /^\s*if\b.+:\s*assert\b/.test(l) && hasOld(l)) return 'assertion now only runs under a condition: ' + l.trim();
|
|
175
|
+
}
|
|
176
|
+
// a new `if ...:` / `if (...) {` line wrapped around an existing assertion (the assertion line itself did not change)
|
|
177
|
+
const addedSet = new Set(added.map((x) => String(x).trim()));
|
|
178
|
+
const L = String(after || '').split(/\r?\n/);
|
|
179
|
+
for (let i = 0; i < L.length; i++) {
|
|
180
|
+
const l = L[i]; if (!addedSet.has(l.trim())) continue;
|
|
181
|
+
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(); }
|
|
182
|
+
if (!(py ? /^\s*if\b.+:\s*$/.test(l) : /^\s*if\s*\(.+\)\s*\{\s*$/.test(l))) continue;
|
|
183
|
+
let j = i + 1; while (j < L.length && !L[j].trim()) j++;
|
|
184
|
+
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();
|
|
185
|
+
// `if x:` + `return` (bare) right before an old assertion
|
|
186
|
+
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(); }
|
|
187
|
+
}
|
|
188
|
+
// moved into a function that nothing calls
|
|
189
|
+
const { code, blank } = codeViews(after, py);
|
|
190
|
+
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;
|
|
191
|
+
let m;
|
|
192
|
+
while ((m = def.exec(blank))) {
|
|
193
|
+
const name = m[1] || m[2]; if (!name) continue;
|
|
194
|
+
if (py && /^test/i.test(name)) continue; // pytest calls test_* functions itself
|
|
195
|
+
const uses = (blank.match(new RegExp('\\b' + name + '\\b', 'g')) || []).length;
|
|
196
|
+
if (uses > 1) continue;
|
|
197
|
+
let body;
|
|
198
|
+
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'); }
|
|
199
|
+
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); }
|
|
200
|
+
const inside = assertionKeys(body, py);
|
|
201
|
+
if (inside.some((k) => keysBefore.includes(k))) return `assertion moved into ${name}(), which is never called`;
|
|
202
|
+
}
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
|
|
108
206
|
/** Literal groups from assertion lines of all test files: [['2','3','5'], ...] */
|
|
109
207
|
function assertionGroups(root, testFiles) {
|
|
110
208
|
const groups = [];
|
|
@@ -192,6 +290,10 @@ function analyze({ root, beforeDir, changes, testFiles }) {
|
|
|
192
290
|
const inlineFiles = (changes || []).filter((c) => c.kind !== 'deleted' && /\.rs$/i.test(c.file) && INLINE_TESTS.test(read(path.join(root, c.file)) || '')).map((c) => c.file);
|
|
193
291
|
const getGroups = () => (groups || (groups = assertionGroups(root, [...(testFiles || []), ...inlineFiles])));
|
|
194
292
|
const add = (rule, file, detail) => findings.push({ rule, file, detail: String(detail || '').slice(0, 200), text: RULE_TEXT[rule] });
|
|
293
|
+
// names of the code files this change touched (not tests): a new test that mocks one of them is suspicious
|
|
294
|
+
const changedCode = (changes || []).filter((c) => c.kind !== 'deleted' && CODE_EXT.test(c.file) && !isTestFile(c.file))
|
|
295
|
+
.map((c) => ({ base: (path.basename(c.file).replace(/\.[^.]+$/, '').toLowerCase() === 'index' ? path.basename(path.dirname(c.file)) : path.basename(c.file).replace(/\.[^.]+$/, '')), file: c.file, src: c.kind === 'deleted' ? '' : (read(path.join(root, c.file)) || '') }))
|
|
296
|
+
.filter((x) => x.base.length >= 3 && !/^(index|main|mod|lib|init|__init__|utils?|helpers?)$/i.test(x.base));
|
|
195
297
|
for (const c of changes || []) {
|
|
196
298
|
const rel = c.file;
|
|
197
299
|
const before = c.kind === 'added' ? '' : read(path.join(beforeDir, rel));
|
|
@@ -199,6 +301,17 @@ function analyze({ root, beforeDir, changes, testFiles }) {
|
|
|
199
301
|
const isTest = isTestFile(rel);
|
|
200
302
|
|
|
201
303
|
if (c.link) { add('outside_link', rel, c.link); continue; }
|
|
304
|
+
if (/^\.github\/workflows\/[^/]+\.ya?ml$/i.test(rel) && /buildproof/i.test(before || '')) {
|
|
305
|
+
// only changes that switch the BuildProof step off count; adding the workflow or bumping versions is fine
|
|
306
|
+
if (c.kind === 'deleted' || !/buildproof/i.test(after || '')) { add('ci_changed', rel, 'BuildProof step removed'); continue; }
|
|
307
|
+
const wd = lineDelta(before || '', after || '');
|
|
308
|
+
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)));
|
|
309
|
+
const changedStep = bpBefore.find((l) => !bpAfter.has(l));
|
|
310
|
+
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));
|
|
311
|
+
if (bypass) { add('ci_changed', rel, bypass); continue; }
|
|
312
|
+
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; }
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
202
315
|
if (HOOK_FILE.test(rel)) {
|
|
203
316
|
if (/buildproof/i.test(before || '') && !/buildproof/i.test(after || '')) add('guard_disabled', rel, c.kind === 'deleted' ? 'file deleted' : 'buildproof hook removed');
|
|
204
317
|
else if (/"disableAllHooks"\s*:\s*true/.test(after || '') && !/"disableAllHooks"\s*:\s*true/.test(before || '')) add('guard_disabled', rel, 'disableAllHooks: true');
|
|
@@ -270,13 +383,35 @@ function analyze({ root, beforeDir, changes, testFiles }) {
|
|
|
270
383
|
const d = lineDelta(before || '', after || '');
|
|
271
384
|
const skip = d.added.find((l) => SKIP_RE.test(l));
|
|
272
385
|
if (skip) add('test_skipped', rel, skip);
|
|
386
|
+
else { // a bare return added before the checks makes a test pass without checking anything
|
|
387
|
+
const namedTest = /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.py$/i.test(rel);
|
|
388
|
+
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;
|
|
389
|
+
if (early && assertionKeys(after, /\.py$/i.test(rel)).length) add('test_skipped', rel, early.trim());
|
|
390
|
+
}
|
|
273
391
|
if (c.kind === 'modified') {
|
|
274
|
-
const
|
|
275
|
-
|
|
392
|
+
const py = /\.py$/i.test(rel);
|
|
393
|
+
const kb = assertionKeys(before, py); const ka = new Set(assertionKeys(after, py));
|
|
394
|
+
if (kb.length) { // compare the assertions themselves, not the lines they sit on
|
|
395
|
+
const gone = kb.filter((k) => !ka.has(k));
|
|
396
|
+
if (gone.length) add('assertion_changed', rel, gone[0].slice(0, 200));
|
|
397
|
+
else { const hid = hiddenAssertion(before, after, py, kb, d.added, rel); if (hid) add('assertion_changed', rel, hid); }
|
|
398
|
+
} else { // a language we cannot parse assertions in: fall back to lines
|
|
399
|
+
const goneAsserts = d.removed.filter((l) => ASSERT_RE.test(l));
|
|
400
|
+
if (goneAsserts.length) add('assertion_changed', rel, goneAsserts[0]);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
// new mocks in an EXISTING test; in a brand-new test file only a mock of code this same change touched
|
|
404
|
+
// (a new test that mocks away the very code it should test proves nothing - mocking other things is fine)
|
|
405
|
+
let mock = c.kind === 'modified' ? d.added.find((l) => MOCK_RE.test(l)) : null;
|
|
406
|
+
if (!mock && c.kind === 'added') {
|
|
407
|
+
const i = d.added.findIndex((l) => mocksChangedModule(l, changedCode, rel));
|
|
408
|
+
// a partial mock keeps the real module (requireActual / importActual inside the factory, often on the next lines)
|
|
409
|
+
if (i >= 0 && !/requireActual|importActual|importOriginal/.test(d.added.slice(i, i + 6).join('\n'))) mock = d.added[i];
|
|
276
410
|
}
|
|
277
|
-
// new mocks in an EXISTING test (a brand-new test file may legitimately use mocks)
|
|
278
|
-
const mock = c.kind === 'modified' ? d.added.find((l) => MOCK_RE.test(l)) : null;
|
|
279
411
|
if (mock) add('mock_added', rel, mock);
|
|
412
|
+
// the test overrides the very code under test (c.discount = ..., {...real, discount: ...}, rebinding an imported function)
|
|
413
|
+
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
|
|
414
|
+
if (patched) add('code_patched', rel, patched);
|
|
280
415
|
const sil = d.added.find((l) => SILENCE_RE.test(l));
|
|
281
416
|
if (sil) add('checker_silenced', rel, sil);
|
|
282
417
|
const sc = addedMatch(before || '', after || '', SILENT_CATCH_RE);
|
|
@@ -302,6 +437,103 @@ function analyze({ root, beforeDir, changes, testFiles }) {
|
|
|
302
437
|
}
|
|
303
438
|
|
|
304
439
|
/** Multi-line pattern: count matches before vs after; report the first new one. */
|
|
440
|
+
/** Is this test (or a test helper / setup file) overriding code this same change touched? Returns the offending line or null. */
|
|
441
|
+
function patchesCode(added, src, testRel, changed, root = '') {
|
|
442
|
+
if (!added || !added.length) return null;
|
|
443
|
+
const t = String(testRel).replace(/\\/g, '/');
|
|
444
|
+
const tdir = path.posix.dirname(t);
|
|
445
|
+
const base = path.posix.basename(t);
|
|
446
|
+
const isHelper = !/\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.py$/i.test(base); // _setup.js, conftest.py, helpers
|
|
447
|
+
const subject = base.replace(/\.(c|m)?[jt]sx?$|\.py$/i, '').replace(/[._-](test|spec)s?$/i, '').replace(/^test_/i, '').replace(/_test$/i, '').toLowerCase();
|
|
448
|
+
const strip = (f) => f.replace(/\\/g, '/').replace(/\.(c|m)?[jt]sx?$/i, '').replace(/\/index$/i, '').toLowerCase();
|
|
449
|
+
// a helper / setup file belongs to the tests that load it: it "owns" their subjects only
|
|
450
|
+
let helperOwners = null;
|
|
451
|
+
if (isHelper) {
|
|
452
|
+
helperOwners = new Set();
|
|
453
|
+
try {
|
|
454
|
+
const abs = path.join(root, tdir); const stem = base.replace(/\.[^.]+$/, '');
|
|
455
|
+
for (const f of fs.readdirSync(abs)) {
|
|
456
|
+
if (f === base || !/\.(test|spec)\.[cm]?[jt]sx?$|^test_.+\.py$|_test\.py$/i.test(f)) continue;
|
|
457
|
+
const txt = read(path.join(abs, f)) || '';
|
|
458
|
+
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());
|
|
459
|
+
}
|
|
460
|
+
} catch { /* no folder */ }
|
|
461
|
+
}
|
|
462
|
+
const owns = (base2) => (isHelper ? helperOwners.has(base2.toLowerCase()) : base2.toLowerCase() === subject);
|
|
463
|
+
const esc = (x) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
464
|
+
const objs = new Set(); const names = new Set();
|
|
465
|
+
// JS / TS bindings to a changed module
|
|
466
|
+
const jsChanged = (spec) => {
|
|
467
|
+
if (!/^[./]/.test(spec)) return null;
|
|
468
|
+
const target = strip(path.posix.normalize(path.posix.join(tdir, spec)));
|
|
469
|
+
const hit = changed.find((x) => /\.(c|m)?[jt]sx?$/i.test(x.file) && strip(x.file) === target);
|
|
470
|
+
if (hit && owns(hit.base)) return true;
|
|
471
|
+
// the test's own subject counts even when the change did not touch it (a test that rebinds what it tests proves nothing)
|
|
472
|
+
return !isHelper && target.split('/').pop() === subject;
|
|
473
|
+
};
|
|
474
|
+
let m;
|
|
475
|
+
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;
|
|
476
|
+
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); }
|
|
477
|
+
const reNames = /(?:(?:const|let|var)\s*\{([^}]*)\}\s*=\s*require\(\s*['"]([^'"]+)['"]\s*\))|(?:import\s*\{([^}]*)\}\s*from\s+['"]([^'"]+)['"])/g;
|
|
478
|
+
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); } }
|
|
479
|
+
// Python bindings: from pkg.mod import a, b / import pkg.mod as m / from pkg import mod
|
|
480
|
+
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); };
|
|
481
|
+
const rePyFrom = /^[ \t]*from[ \t]+([\w.]+)[ \t]+import[ \t]+(?:\(([\w\s,]+)\)|([\w \t,]+))/gm;
|
|
482
|
+
while ((m = rePyFrom.exec(src))) {
|
|
483
|
+
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;
|
|
484
|
+
if (pyOwn(m[1])) names.add(local); else if (pyOwn(m[1] + '.' + name)) objs.add(local); }
|
|
485
|
+
}
|
|
486
|
+
const rePyImp = /^\s*import\s+([\w.]+)(?:\s+as\s+(\w+))?/gm;
|
|
487
|
+
while ((m = rePyImp.exec(src))) if (pyOwn(m[1])) objs.add(m[2] || m[1]);
|
|
488
|
+
if (!objs.size && !names.size) return null;
|
|
489
|
+
for (const raw of added) {
|
|
490
|
+
const l = String(raw);
|
|
491
|
+
if (/requireActual|importActual|importOriginal/.test(l)) continue;
|
|
492
|
+
for (const o of objs) {
|
|
493
|
+
const O = esc(o);
|
|
494
|
+
if (new RegExp('(^|[^\\w.])' + O + '(\\.\\w+|\\[\\s*[\'"`]\\w+[\'"`]\\s*\\])\\s*=(?!=)').test(l)) return l.trim();
|
|
495
|
+
if (new RegExp('\\.\\.\\.\\s*' + O + '\\b[^}]*,\\s*\\w+\\s*:').test(l) || new RegExp('\\.\\.\\.\\s*' + O + '\\s*,\\s*$').test(l)) return l.trim();
|
|
496
|
+
if (new RegExp('Object\\.assign\\(\\s*' + O + '\\b').test(l)) return l.trim();
|
|
497
|
+
if (new RegExp('(^|[^.\\w])setattr\\(\\s*' + O + '\\s*,').test(l)) return l.trim();
|
|
498
|
+
if (new RegExp('(?:jest|vi)\\.spyOn\\(\\s*' + O + '\\s*,[^)]*\\)\\s*\\.(mockImplementation|mockReturnValue|mockResolvedValue|mockRejectedValue)').test(l)) return l.trim();
|
|
499
|
+
}
|
|
500
|
+
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();
|
|
501
|
+
}
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** Does this line mock away the very module this new test file is about?
|
|
506
|
+
* Only one precise form counts, so ordinary dependency mocks are never flagged:
|
|
507
|
+
* jest.mock / vi.mock / jest.doMock / mock.module('<relative path>') where the path, resolved from the test file,
|
|
508
|
+
* is a code file changed in the same change AND has the same name as the test file (fees.test.js mocking ./fees). */
|
|
509
|
+
function mocksChangedModule(line, changed, testRel = '') {
|
|
510
|
+
const l = String(line);
|
|
511
|
+
const js = l.match(/\b(?:jest|vi)\.(?:mock|doMock)\s*\(\s*(['"`])([^'"`]+)\1|\bmock\.module\s*\(\s*(['"`])([^'"`]+)\3/);
|
|
512
|
+
if (!js) return false;
|
|
513
|
+
const spec = js[2] || js[4];
|
|
514
|
+
if (!/^[./]/.test(spec)) return false; // a package or a Node built-in, not the project's own code
|
|
515
|
+
const strip = (f) => f.replace(/\\/g, '/').replace(/\.(c|m)?[jt]sx?$/i, '').replace(/\/index$/i, '').toLowerCase();
|
|
516
|
+
const t = String(testRel).replace(/\\/g, '/');
|
|
517
|
+
const target = strip(path.posix.normalize(path.posix.join(path.posix.dirname(t), spec)));
|
|
518
|
+
// the test's subject: fees.test.js / fees.spec.ts / __tests__/fees.js -> "fees"
|
|
519
|
+
const subject = path.posix.basename(t).replace(/\.(c|m)?[jt]sx?$/i, '').replace(/[._-](test|spec)s?$/i, '').toLowerCase();
|
|
520
|
+
if (!subject || target.split('/').pop() !== subject) return false;
|
|
521
|
+
if (/requireActual|importActual|importOriginal/.test(l)) return false; // partial mock: the real module stays in use
|
|
522
|
+
if (!changed.some((x) => /\.(c|m)?[jt]sx?$/i.test(x.file) && strip(x.file) === target)) return false;
|
|
523
|
+
// it must be the test's OWN file, not a same-named module in another layer (controllers/users.test.js -> ../services/users)
|
|
524
|
+
const tdir = path.posix.dirname(t).toLowerCase(); const targetDir = path.posix.dirname(target);
|
|
525
|
+
const TESTDIR = /^(__tests__|tests?|spec|specs)$/i;
|
|
526
|
+
if (targetDir === tdir) return true; // src/fees.test.js -> ./fees
|
|
527
|
+
if (TESTDIR.test(path.posix.basename(tdir)) && targetDir === path.posix.dirname(tdir)) return true; // src/__tests__/fees.js -> ../fees
|
|
528
|
+
const segs = tdir.split('/'); const i = segs.findIndex((x) => TESTDIR.test(x));
|
|
529
|
+
if (i >= 0) { // mirrored layout: test/a/fees.test.js -> src/a/fees ; only when the name is unique in the change
|
|
530
|
+
const rest = segs.slice(i + 1).join('/');
|
|
531
|
+
const same = changed.filter((x) => /\.(c|m)?[jt]sx?$/i.test(x.file) && strip(x.file).split('/').pop() === subject);
|
|
532
|
+
return same.length === 1 && (rest === '' || targetDir === rest || targetDir.endsWith('/' + rest));
|
|
533
|
+
}
|
|
534
|
+
return false;
|
|
535
|
+
}
|
|
536
|
+
|
|
305
537
|
function addedMatch(before, after, re) {
|
|
306
538
|
const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g');
|
|
307
539
|
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.0",
|
|
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": {
|