buildproof 0.0.0-stage → 3.8.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/core/certs.js ADDED
@@ -0,0 +1,194 @@
1
+ 'use strict';
2
+ /**
3
+ * Signed proof certificates (ed25519, key generated and kept on this computer).
4
+ * A certificate is a canonical JSON payload + signature + public key.
5
+ * The exported HTML file verifies itself in the browser (WebCrypto Ed25519), no server needed.
6
+ */
7
+ const fs = require('fs');
8
+ const os = require('os');
9
+ const path = require('path');
10
+ const crypto = require('crypto');
11
+ const store = require('./store');
12
+ const { DATA_DIR } = require('./config');
13
+
14
+ const KEY_DIR = path.join(DATA_DIR, 'keys');
15
+ const PRIV = path.join(KEY_DIR, 'signing-ed25519.pem');
16
+ const PUB = path.join(KEY_DIR, 'signing-ed25519.pub.pem');
17
+
18
+ function keys() {
19
+ if (!fs.existsSync(PRIV)) {
20
+ fs.mkdirSync(KEY_DIR, { recursive: true });
21
+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519');
22
+ fs.writeFileSync(PRIV, privateKey.export({ type: 'pkcs8', format: 'pem' }), { mode: 0o600 });
23
+ fs.writeFileSync(PUB, publicKey.export({ type: 'spki', format: 'pem' }));
24
+ }
25
+ const privateKey = crypto.createPrivateKey(fs.readFileSync(PRIV));
26
+ const publicKey = crypto.createPublicKey(fs.readFileSync(PUB));
27
+ const spki = publicKey.export({ type: 'spki', format: 'der' });
28
+ return { privateKey, publicKey, spkiB64: spki.toString('base64'), fingerprint: fingerprintOf(spki) };
29
+ }
30
+
31
+ function fingerprintOf(spkiDer) {
32
+ return crypto.createHash('sha256').update(spkiDer).digest('hex').slice(0, 32).toUpperCase().match(/.{4}/g).join(' ');
33
+ }
34
+
35
+ /** Stable JSON: sorted keys, no whitespace. Same bytes in Node and in the browser. */
36
+ function canonical(v) {
37
+ if (Array.isArray(v)) return '[' + v.map(canonical).join(',') + ']';
38
+ if (v && typeof v === 'object') return '{' + Object.keys(v).sort().filter((k) => v[k] !== undefined).map((k) => JSON.stringify(k) + ':' + canonical(v[k])).join(',') + '}';
39
+ return JSON.stringify(v === undefined ? null : v);
40
+ }
41
+
42
+ function sha256File(abs) { try { return crypto.createHash('sha256').update(fs.readFileSync(abs)).digest('hex'); } catch { return null; } }
43
+
44
+ /**
45
+ * Build + sign a certificate from a finished task (supervised or guard).
46
+ * Only issued when the work is proven and integrity is clean, or when a human explicitly accepted warnings.
47
+ */
48
+ /**
49
+ * Fingerprint of the WHOLE certified code: sha256 of every file (sorted "path sha256" lines).
50
+ * The client recomputes it on the code they received - any difference shows up.
51
+ */
52
+ function treeOf(root, opts = {}) {
53
+ const { walk } = require('./snapshot');
54
+ const { DEFAULTS } = require('./config');
55
+ const files = walk(root, DEFAULTS.ignoreDirs, opts.legacy ? 20000 : DEFAULTS.maxProjectFiles, { legacy: !!opts.legacy }).sort();
56
+ const list = files.map((f) => ({ file: f, sha256: sha256File(path.join(root, f)) }));
57
+ const treeHash = crypto.createHash('sha256').update(list.map((x) => `${x.file} ${x.sha256}`).join('\n')).digest('hex');
58
+ return { treeHash, count: list.length, files: list.length <= 3000 ? list : null };
59
+ }
60
+
61
+ function gitInfo(root) {
62
+ try {
63
+ const { spawnSync } = require('child_process');
64
+ const head = spawnSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8', windowsHide: true, timeout: 5000 });
65
+ if (head.status !== 0) return null;
66
+ const st = spawnSync('git', ['status', '--porcelain'], { cwd: root, encoding: 'utf8', windowsHide: true, timeout: 5000 });
67
+ return { commit: head.stdout.trim(), dirty: !!st.stdout.trim() };
68
+ } catch { return null; }
69
+ }
70
+
71
+ function issue(task, project, { acceptedWarnings = false } = {}) {
72
+ const k = keys();
73
+ const tree = treeOf(project.root);
74
+ const checks = Object.entries(task.after || {}).map(([step, r]) => ({
75
+ step,
76
+ before: task.baseline && task.baseline[step] ? (task.baseline[step].pass ? 'pass' : 'fail') : 'n/a',
77
+ after: r.pass ? 'pass' : r.ran === false ? 'did_not_run' : 'fail',
78
+ ms: r.ms || 0,
79
+ tests: r.tests || null,
80
+ }));
81
+ const changed = (task.changedFiles || []).map((c) => ({ file: c.file, kind: c.kind, sha256: c.kind === 'deleted' ? null : sha256File(path.join(project.root, c.file)) }));
82
+ const integ = task.integrity || { clean: true, findings: [], rulesChecked: [] };
83
+ const payload = {
84
+ format: 'buildproof-certificate/1',
85
+ id: 'c_' + crypto.randomBytes(6).toString('hex'),
86
+ issuedAt: new Date().toISOString(),
87
+ machine: os.hostname(),
88
+ project: project.name,
89
+ task: { id: task.id, kind: task.kind || 'supervised', text: task.text, source: task.source || 'web' },
90
+ result: acceptedWarnings ? 'ACCEPTED_WITH_WARNINGS' : 'PROVEN',
91
+ checks,
92
+ integrity: { clean: !!integ.clean, rulesChecked: integ.rulesChecked || [], findings: (integ.findings || []).map((f) => ({ rule: f.rule, file: f.file, text: f.text })) },
93
+ scope: { approved: task.approvedScope || null, outsideReverted: (task.scopeGuard && task.scopeGuard.reverted) || [] },
94
+ changes: changed,
95
+ ai: { calls: task.aiCalls || 0, model: task.aiModel || null, local: task.aiLocal !== false },
96
+ revertCheck: task.revertCheck ? { verdict: task.revertCheck.verdict, text: task.revertCheck.text } : null,
97
+ claims: (task.claims || []).map((c) => ({ claim: c.text, true: c.truth, why: c.why })),
98
+ rerun: { walk: 2, projectType: project.type, steps: Object.keys(task.after || {}), treeHash: tree.treeHash, fileCount: tree.count, files: tree.files, git: gitInfo(project.root) },
99
+ };
100
+ const body = canonical(payload);
101
+ const signature = crypto.sign(null, Buffer.from(body, 'utf8'), k.privateKey).toString('base64');
102
+ const cert = { id: payload.id, taskId: task.id, project: project.name, result: payload.result, issuedAt: payload.issuedAt, payload, signature, publicKey: k.spkiB64, fingerprint: k.fingerprint };
103
+ store.insert('certs', cert);
104
+ return cert;
105
+ }
106
+
107
+ /**
108
+ * Level 2 trust: the BuildProof license server countersigns the certificate and writes it to a public log,
109
+ * so a client can see WHO issued it (a registered, licensed developer) and WHEN. Best effort - offline is fine.
110
+ */
111
+ async function countersign(cert, cfg) {
112
+ if (!cfg || !cfg.licenseServer) return null;
113
+ const key = require('./license').currentKey();
114
+ if (!key) return null;
115
+ const certHash = crypto.createHash('sha256').update(canonical(cert.payload)).digest('hex');
116
+ const ask = () => require('./ai').request(`${cfg.licenseServer.replace(/\/$/, '')}/api/countersign`, { certHash, fingerprint: cert.fingerprint, licenseKey: key, proof: require('./machine-proof').make('countersign', certHash) }, 5000);
117
+ let r = await ask();
118
+ // not registered yet (offline at activation, or a renewed key) -> register this signing key, try once more
119
+ if (r.json && r.json.error === 'fingerprint_not_registered' && await registerFingerprint(cfg)) r = await ask();
120
+ if (!r.ok || !r.json || !r.json.ok) return null;
121
+ const cs = { server: cfg.licenseServer, entry: r.json.entry, sig: r.json.sig };
122
+ store.update('certs', cert.id, { countersign: cs });
123
+ return cs;
124
+ }
125
+
126
+ async function registerFingerprint(cfg) {
127
+ if (!cfg || !cfg.licenseServer) return null;
128
+ const key = require('./license').currentKey();
129
+ if (!key) return null;
130
+ const k = require('./license').parseKey(key);
131
+ const id = k.ok ? k.payload.id : '';
132
+ const r = await require('./ai').request(`${cfg.licenseServer.replace(/\/$/, '')}/api/register`, { licenseKey: key, fingerprint: keys().fingerprint, proof: require('./machine-proof').make('register', id) }, 5000);
133
+ return r.ok;
134
+ }
135
+
136
+ function verify(cert) {
137
+ try {
138
+ // the fingerprint sits outside the signed payload: it must be the one of the key that signed, or it could name anybody
139
+ if (cert.fingerprint != null && cert.fingerprint !== require('./machine-proof').fingerprintOfSpki(cert.publicKey)) return false;
140
+ const pub = crypto.createPublicKey({ key: Buffer.from(cert.publicKey, 'base64'), format: 'der', type: 'spki' });
141
+ return crypto.verify(null, Buffer.from(canonical(cert.payload), 'utf8'), pub, Buffer.from(cert.signature, 'base64'));
142
+ } catch { return false; }
143
+ }
144
+
145
+ function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c])); }
146
+
147
+ /** Self-contained, self-verifying certificate page. */
148
+ function html(cert) {
149
+ const p = cert.payload;
150
+ const good = p.result === 'PROVEN';
151
+ const row = (c) => `<tr><td>${esc(c.step)}${c.tests ? ` <span class="dim">· ${c.tests.passed}/${c.tests.total} tests</span>` : ''}</td><td class="${c.before === 'pass' ? 'g' : 'r'}">${esc(c.before)}</td><td class="${c.after === 'pass' ? 'g' : 'r'}">${esc(c.after)}</td><td class="mono dim">${(c.ms / 1000).toFixed(1)}s</td></tr>`;
152
+ const integ = p.integrity.clean
153
+ ? `<li class="g">No tests deleted, skipped or weakened</li><li class="g">No new mocks, sleeps or silent catches</li><li class="g">No checks silenced, no test scripts changed</li>`
154
+ : p.integrity.findings.map((f) => `<li class="r">${esc(f.text)} <span class="mono dim">${esc(f.file)}</span></li>`).join('');
155
+ const files = p.changes.map((c) => `<li><span class="mono">${esc(c.file)}</span> <span class="dim">${esc(c.kind)}</span>${c.sha256 ? `<br><span class="mono dim small">sha256 ${esc(c.sha256)}</span>` : ''}</li>`).join('') || '<li class="dim">No files changed</li>';
156
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
157
+ <title>BuildProof certificate ${esc(p.id)}</title>
158
+ <style>*{box-sizing:border-box}body{margin:0;background:#F4F5F7;font:500 18px/1.5 Inter,"Segoe UI",system-ui,sans-serif;color:#0A0A0A}
159
+ .wrap{max-width:760px;margin:0 auto;padding:24px 16px 48px}.card{background:#fff;border:1px solid #E6E6E6;border-radius:16px;padding:22px;margin-bottom:14px}
160
+ h1{font-size:15px;letter-spacing:1.5px;text-transform:uppercase;color:#5F6368;margin:0 0 14px}.big{font:800 34px/1.1 Inter,system-ui,sans-serif;color:${good ? '#12803F' : '#B26A00'};letter-spacing:.5px}
161
+ .task{font-size:22px;font-weight:650;margin:12px 0 4px}.dim{color:#5F6368}.small{font-size:13px}.mono{font-family:ui-monospace,Consolas,"DejaVu Sans Mono",monospace;font-size:14px;word-break:break-all}
162
+ table{width:100%;border-collapse:collapse}td{padding:9px 6px;border-top:1px solid #EEE}td:nth-child(2),td:nth-child(3){font-weight:700;width:90px}.g{color:#12803F}.r{color:#C5221F}
163
+ ul{margin:0;padding-left:20px}li{margin:6px 0}h2{font-size:15px;color:#5F6368;margin:0 0 8px}
164
+ #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
+ <body><div class="wrap">
166
+ <div class="card"><h1>BuildProof certificate</h1><div class="big">${good ? 'PROVEN' : 'ACCEPTED WITH WARNINGS'}</div>
167
+ <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
+ <div class="card"><h2>Checks · before → after</h2><table>${p.checks.map(row).join('')}</table></div>
169
+ <div class="card"><h2>Test integrity · ${p.integrity.rulesChecked.length} rules checked</h2><ul>${integ}</ul></div>
170
+ ${p.revertCheck ? `<div class="card"><h2>Revert check</h2><div class="${p.revertCheck.verdict === 'covered' ? 'g' : p.revertCheck.verdict === 'skipped' ? 'dim' : 'r'}">${esc(p.revertCheck.text)}</div></div>` : ''}
171
+ ${(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
+ <div class="card"><h2>Changed files</h2><ul>${files}</ul></div>
173
+ <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
+ ${cert.countersign ? `<div class="card"><h2>Countersigned</h2><div class="g">Registered with BuildProof at ${esc(new Date(cert.countersign.entry.time).toUTCString())} - public log: ${esc(cert.countersign.server)}/verify</div></div>` : ''}
175
+ <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 &lt;your-project-folder&gt;</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
+ <div class="card"><h2>Signature</h2><div id="sig">Checking signature…</div>
177
+ <p class="mono dim small">ed25519 · key fingerprint <span id="fp">${esc(cert.fingerprint)}</span><br>certificate ${esc(p.id)}</p>
178
+ <p class="dim small">The signature proves this report was not changed after it was issued on the developer's computer. Ask the developer to confirm the key fingerprint.</p></div>
179
+ </div>
180
+ <script id="cert" type="application/json">${JSON.stringify({ payload: p, signature: cert.signature, publicKey: cert.publicKey, fingerprint: cert.fingerprint, countersign: cert.countersign || null }).replace(/</g, '\\u003c')}</script>
181
+ <script>
182
+ function canonical(v){if(Array.isArray(v))return'['+v.map(canonical).join(',')+']';if(v&&typeof v==='object')return'{'+Object.keys(v).sort().filter(function(k){return v[k]!==undefined}).map(function(k){return JSON.stringify(k)+':'+canonical(v[k])}).join(',')+'}';return JSON.stringify(v===undefined?null:v)}
183
+ function b64(s){var b=atob(s),u=new Uint8Array(b.length);for(var i=0;i<b.length;i++)u[i]=b.charCodeAt(i);return u}
184
+ (async function(){var el=document.getElementById('sig');try{var c=JSON.parse(document.getElementById('cert').textContent);
185
+ var key=await crypto.subtle.importKey('spki',b64(c.publicKey),{name:'Ed25519'},false,['verify']);
186
+ var ok=await crypto.subtle.verify({name:'Ed25519'},key,b64(c.signature),new TextEncoder().encode(canonical(c.payload)));
187
+ 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
+ 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 report was not modified.':'✗ Signature INVALID. This report was modified.';}
190
+ catch(e){el.textContent='This browser cannot check ed25519 signatures. Open the file in a current Chrome, Edge, Safari or Firefox.';}})();
191
+ </script></body></html>`;
192
+ }
193
+
194
+ module.exports = { issue, verify, html, canonical, keys, treeOf, countersign, registerFingerprint };
package/core/ci.js ADDED
@@ -0,0 +1,254 @@
1
+ 'use strict';
2
+ /**
3
+ * CI / pull request check: compare the pull request (HEAD) with its base branch, without the background service.
4
+ *
5
+ * buildproof ci [folder] [--base origin/main] [--spec spec.md] [--no-baseline] [--summary file.md]
6
+ *
7
+ * 1. test-integrity rules on every changed file (deleted / skipped / weakened tests, silenced checkers...)
8
+ * 2. the project's build / test scripts on the base and on the pull request
9
+ * 3. spec check (optional): every requirement in .buildproof/spec.md (or --spec) must name a test that exists and passes
10
+ * 4. fail-closed verdict: PROVEN only if the checks really ran, nothing regressed, no fewer tests ran and the spec is met
11
+ * Exit code: 0 = PROVEN, 1 = NOT PROVEN, 2 = cannot check (no licence, no git, no base).
12
+ */
13
+ const fs = require('fs');
14
+ const os = require('os');
15
+ const path = require('path');
16
+ const cp = require('child_process');
17
+ const integrity = require('./integrity');
18
+ const gate = require('./gate');
19
+ const { run } = require('./runner');
20
+
21
+ const STRICT_TYPES = new Set(['go', 'rust', 'java-maven', 'java-gradle', 'dotnet', 'ruby', 'php']);
22
+
23
+ function git(args, cwd) { return cp.execFileSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }).trim(); }
24
+
25
+ /** Base ref: --base, then the GitHub pull request base, then origin/main or origin/master. */
26
+ function findBase(root, wanted) {
27
+ const tries = wanted ? [wanted] : [process.env.GITHUB_BASE_REF && 'origin/' + process.env.GITHUB_BASE_REF, 'origin/main', 'origin/master', 'main', 'master'].filter(Boolean);
28
+ for (const ref of tries) { try { git(['rev-parse', '--verify', '--quiet', ref + '^{commit}'], root); return ref; } catch { /* next */ } }
29
+ return null;
30
+ }
31
+
32
+ /** Changed files between the merge base and HEAD, in the shape integrity.analyze expects. */
33
+ function changesBetween(root, base) {
34
+ const out = git(['diff', '--name-status', '--no-renames', '--no-color', base + '...HEAD'], root);
35
+ const changes = [];
36
+ for (const line of out.split(/\r?\n/).filter(Boolean)) {
37
+ const [st, file] = line.split('\t');
38
+ const kind = st[0] === 'A' ? 'added' : st[0] === 'D' ? 'deleted' : 'modified';
39
+ changes.push({ file: file.replace(/\\/g, '/'), kind });
40
+ }
41
+ return changes;
42
+ }
43
+
44
+ function listFiles(root) {
45
+ try { return git(['ls-files'], root).split(/\r?\n/).filter(Boolean); } catch { return []; }
46
+ }
47
+
48
+ /** Install dependencies in the base copy (Node only: other toolchains fetch them inside their own test command). */
49
+ async function installDeps(dir, info, timeoutMs) {
50
+ if (!info.needsInstall) return null;
51
+ const pm = info.packageManager || 'npm';
52
+ const lock = { npm: 'package-lock.json', yarn: 'yarn.lock', pnpm: 'pnpm-lock.yaml' }[pm];
53
+ const args = pm === 'npm' ? (fs.existsSync(path.join(dir, lock)) ? ['ci', '--no-audit', '--no-fund'] : ['install', '--no-audit', '--no-fund']) : ['install', '--frozen-lockfile'];
54
+ return run(pm, args, { cwd: dir, timeoutMs });
55
+ }
56
+
57
+ async function verifyDir(dir, info, commandFor, timeoutMs) {
58
+ const results = {};
59
+ for (const step of info.verify) {
60
+ const { cmd, args } = commandFor(info, step);
61
+ // NODE_TEST_CONTEXT would make a nested `node --test` report to its parent instead of failing here
62
+ const r = await run(cmd, args, { cwd: dir, timeoutMs, env: { PYTHONDONTWRITEBYTECODE: '1', NODE_TEST_CONTEXT: undefined } });
63
+ const g = gate.evaluate(step, r, { strictCounts: STRICT_TYPES.has(info.type) });
64
+ results[step] = { ...g, tail: String(r.output || '').slice(-1500) };
65
+ }
66
+ return results;
67
+ }
68
+
69
+ /**
70
+ * Can this machine run the check? feature 'ci' (pull request gate, Team and up) or 'spec' (spec check, Pro and up).
71
+ * Key from BUILDPROOF_LICENSE (CI secret) or the local licence. A CI runner without a key gets no trial:
72
+ * every runner is a new machine, so the trial is for your own computer.
73
+ */
74
+ function licensed(license, feature = 'ci') {
75
+ const need = license.F[feature];
76
+ const planName = feature === 'ci' ? 'Team' : 'Pro';
77
+ const key = process.env.BUILDPROOF_LICENSE;
78
+ if (key) {
79
+ const k = license.parseKey(String(key).trim());
80
+ if (!k.ok) return { ok: false, why: 'BUILDPROOF_LICENSE is not a valid BuildProof key' };
81
+ const exp = Date.parse(k.payload.exp);
82
+ if (!(exp + 3 * 864e5 > Date.now())) return { ok: false, why: 'the licence in BUILDPROOF_LICENSE has expired' };
83
+ const plan = license.PLANS[k.payload.plan];
84
+ return plan && plan.features.includes(need) ? { ok: true, plan: k.payload.plan } : { ok: false, why: `${feature === 'ci' ? 'pull request checks are' : 'the spec check is'} in the ${planName} plan and up (this key is ${k.payload.plan})` };
85
+ }
86
+ if (process.env.GITHUB_ACTIONS || process.env.CI) return { ok: false, why: 'add your licence key as the BUILDPROOF_LICENSE secret (the free trial runs on your own computer)' };
87
+ const st = license.status();
88
+ return st.features.includes(need) ? { ok: true, plan: st.plan } : { ok: false, why: `${feature === 'ci' ? 'pull request checks are' : 'the spec check is'} in the ${planName} plan and up${st.plan === 'trial' ? ' (your trial has ended)' : ''}` };
89
+ }
90
+
91
+ /**
92
+ * Spec file: one requirement per list line, each tied to the test that proves it.
93
+ * - Users can reset their password => test: reset password sends an email
94
+ * A requirement without "test:" can never be proven (fail closed).
95
+ */
96
+ function parseSpec(text) {
97
+ const items = [];
98
+ for (const raw of String(text || '').split(/\r?\n/)) {
99
+ const m = /^\s*(?:[-*]|\d+[.)])\s+(?:\[[ xX]\]\s*)?(.+?)\s*$/.exec(raw);
100
+ if (!m) continue;
101
+ const t = /^(.*?)\s*(?:=>|->|\|)?\s*\btest:\s*["'`]?(.+?)["'`]?\s*$/i.exec(m[1]);
102
+ items.push(t ? { req: t[1].trim() || t[2].trim(), test: t[2].trim() } : { req: m[1], test: null });
103
+ }
104
+ return items;
105
+ }
106
+
107
+ /** A test name appears in a test file as the first string argument of test( / it( / describe( / def test_... */
108
+ function testNameIn(src, name) {
109
+ const esc = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
110
+ return new RegExp(`\\b(?:test|it|specify|describe)(?:\\.only)?\\s*\\(\\s*["'\`]${esc}["'\`]`).test(src) || new RegExp(`\\bdef\\s+${esc.replace(/\s+/g, '_')}\\s*\\(`).test(src) || new RegExp(`\\b(?:func|fn|void|public\\s+void)\\s+${esc.replace(/\s+/g, '_')}\\s*\\(`).test(src);
111
+ }
112
+
113
+ function checkSpec(items, { root, baseDir, testFiles, after, baseline }) {
114
+ const read = (d, f) => { try { return fs.readFileSync(path.join(d, f), 'utf8'); } catch { return ''; } };
115
+ const headSrc = testFiles.map((f) => read(root, f));
116
+ const baseSrc = baseDir ? testFiles.map((f) => read(baseDir, f)) : [];
117
+ const testSteps = Object.keys(after || {}).filter((s) => /test/.test(s));
118
+ const failedNow = testSteps.flatMap((s) => after[s].failedTests || []);
119
+ const failedBefore = testSteps.flatMap((s) => (baseline && baseline[s] && baseline[s].failedTests) || []);
120
+ const stepsPass = testSteps.length > 0 && testSteps.every((s) => after[s].pass);
121
+ return items.map((it) => {
122
+ if (!it.test) return { ...it, status: 'no_test', why: 'no test is named for this requirement' };
123
+ if (!headSrc.some((src) => testNameIn(src, it.test))) return { ...it, status: 'missing', why: 'the named test does not exist' };
124
+ if (!stepsPass || failedNow.some((n) => n.includes(it.test))) return { ...it, status: 'failing', why: 'the test does not pass' };
125
+ const isNew = !baseSrc.some((src) => testNameIn(src, it.test)) || failedBefore.some((n) => n.includes(it.test));
126
+ return { ...it, status: 'met', isNew };
127
+ });
128
+ }
129
+
130
+ function stepLine(s, r) {
131
+ if (!r) return `- ${s}: did not run`;
132
+ const t = r.tests ? ` (${r.tests.passed}/${r.tests.total} tests)` : '';
133
+ return `- ${s}: ${r.pass ? 'pass' : r.ran ? 'FAIL' : 'did not really run (' + r.reason + ')'}${t}`;
134
+ }
135
+
136
+ function markdown(res) {
137
+ const L = [`## BuildProof: ${res.proven ? 'PROVEN' : 'NOT PROVEN'}`, '', res.why, ''];
138
+ L.push(`Compared with \`${res.base}\`: ${res.changes.length} changed file(s).`, '');
139
+ if (res.integrity.findings.length) {
140
+ L.push('### Checks weakened in this change');
141
+ for (const f of res.integrity.findings) L.push(`- **${f.text}** \`${f.file}\` ${f.detail ? '- `' + f.detail.replace(/`/g, "'") + '`' : ''}`);
142
+ L.push('');
143
+ }
144
+ if (res.spec) {
145
+ L.push('### Spec');
146
+ for (const x of res.spec) L.push(`- ${x.status === 'met' ? 'met' : 'NOT MET'}: ${x.req}${x.test ? ` (test: \`${x.test}\`${x.isNew ? ', new in this change' : ''})` : ''}${x.why ? ' - ' + x.why : ''}`);
147
+ L.push('');
148
+ }
149
+ if (res.after) {
150
+ L.push('### Checks on this pull request');
151
+ for (const s of res.steps) L.push(stepLine(s, res.after[s]));
152
+ L.push('');
153
+ }
154
+ if (res.baseline) {
155
+ L.push(`### Checks on ${res.base}`);
156
+ for (const s of res.steps) L.push(stepLine(s, res.baseline[s]));
157
+ L.push('');
158
+ }
159
+ L.push('_BuildProof is fail-closed: anything it cannot see is a fail, never a pass._');
160
+ return L.join('\n');
161
+ }
162
+
163
+ /**
164
+ * @returns {Promise<{code:number, proven:boolean, why:string, text:string, md:string}>}
165
+ */
166
+ async function check(root, opts = {}) {
167
+ const projects = opts.projects || require('./projects');
168
+ const timeoutMs = opts.timeoutMs || 15 * 60 * 1000;
169
+ root = path.resolve(root);
170
+ try { git(['rev-parse', '--is-inside-work-tree'], root); } catch { return fail('not a git repository: ' + root); }
171
+ const base = findBase(root, opts.base);
172
+ if (!base) return fail('base branch not found. Use --base <branch>, and fetch it (actions/checkout with fetch-depth: 0)');
173
+
174
+ const changes = changesBetween(root, base);
175
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bp-ci-'));
176
+ const baseDir = path.join(tmp, 'base');
177
+ try {
178
+ let mergeBase;
179
+ try { mergeBase = git(['merge-base', base, 'HEAD'], root); } catch { return fail('no common history with ' + base + ' (fetch-depth: 0 is needed)'); }
180
+ git(['worktree', 'add', '--detach', '--force', baseDir, mergeBase], root);
181
+
182
+ const testFiles = listFiles(root).filter((f) => integrity.isTestFile(f));
183
+ const integ = integrity.analyze({ root, beforeDir: baseDir, changes, testFiles });
184
+
185
+ const info = projects.detect(root);
186
+ const steps = info.verify || [];
187
+ let after = null, baseline = null, verdict = null;
188
+ if (steps.length) {
189
+ after = await verifyDir(root, info, projects.commandFor, timeoutMs);
190
+ if (!opts.noBaseline) {
191
+ const binfo = projects.detect(baseDir);
192
+ binfo.verify = steps.filter((s) => (binfo.verify || []).includes(s));
193
+ await installDeps(baseDir, binfo, timeoutMs);
194
+ baseline = await verifyDir(baseDir, binfo, projects.commandFor, timeoutMs);
195
+ }
196
+ // no baseline: every step must pass on its own (stricter)
197
+ verdict = gate.judge(baseline || after, after, steps, true); // a pull request must leave every check passing
198
+ }
199
+ let spec = null;
200
+ const specFile = opts.spec ? path.resolve(root, opts.spec) : path.join(root, '.buildproof', 'spec.md');
201
+ if (opts.spec && !fs.existsSync(specFile)) return fail('spec file not found: ' + opts.spec);
202
+ if (opts.requireSpec && !fs.existsSync(specFile)) return fail('no spec: write .buildproof/spec.md (one line per requirement: - requirement => test: test name)');
203
+ if (fs.existsSync(specFile)) {
204
+ const items = parseSpec(fs.readFileSync(specFile, 'utf8'));
205
+ if (!items.length) return fail('the spec file has no requirements (one per list line: - requirement => test: test name)');
206
+ spec = checkSpec(items, { root, baseDir, testFiles, after, baseline });
207
+ }
208
+ const specBad = spec ? spec.filter((x) => x.status !== 'met') : [];
209
+ const proven = integ.clean && !!verdict && verdict.ok && specBad.length === 0;
210
+ const why = proven ? `The checks really ran, nothing regressed, no test was weakened${spec ? ', every spec requirement is proven by a passing test' : ''}.`
211
+ : (integ.clean && verdict && verdict.ok ? `Spec not met: ${specBad.slice(0, 3).map((x) => `${x.req} (${x.why})`).join('; ')}` : gate.whyNot(verdict, integ));
212
+ const res = { proven, why, base, changes, integrity: integ, steps, after, baseline, spec };
213
+ const md = markdown(res);
214
+ const text = `${proven ? 'PROVEN' : 'NOT_PROVEN'} files=${changes.length} base=${base} | ${why}`;
215
+ return { code: proven ? 0 : 1, proven, why, text, md };
216
+ } finally {
217
+ try { git(['worktree', 'remove', '--force', baseDir], root); } catch { /* ignore */ }
218
+ try { fs.rmSync(tmp, { recursive: true, force: true }); } catch { /* ignore */ }
219
+ }
220
+
221
+ function fail(why) { return { code: 2, proven: false, why, text: 'CANNOT_CHECK ' + why, md: `## BuildProof: cannot check\n\n${why}\n` }; }
222
+ }
223
+
224
+ const WORKFLOW = `name: BuildProof
225
+ on:
226
+ pull_request:
227
+ permissions:
228
+ contents: read
229
+ jobs:
230
+ buildproof:
231
+ runs-on: ubuntu-latest
232
+ steps:
233
+ - uses: actions/checkout@v4
234
+ with:
235
+ fetch-depth: 0
236
+ - uses: actions/setup-node@v4
237
+ with:
238
+ node-version: 20
239
+ - run: npm ci
240
+ - run: npx -y buildproof ci --base origin/\${{ github.base_ref }}
241
+ env:
242
+ BUILDPROOF_LICENSE: \${{ secrets.BUILDPROOF_LICENSE }}
243
+ `;
244
+
245
+ /** Write .github/workflows/buildproof.yml (never overwrites an existing file). */
246
+ function init(root) {
247
+ const f = path.join(path.resolve(root), '.github', 'workflows', 'buildproof.yml');
248
+ if (fs.existsSync(f)) return { ok: false, file: f, error: 'exists' };
249
+ fs.mkdirSync(path.dirname(f), { recursive: true });
250
+ fs.writeFileSync(f, WORKFLOW);
251
+ return { ok: true, file: f };
252
+ }
253
+
254
+ module.exports = { check, init, licensed, changesBetween, findBase, markdown, parseSpec, testNameIn, WORKFLOW };
package/core/claims.js ADDED
@@ -0,0 +1,53 @@
1
+ 'use strict';
2
+ /**
3
+ * Claim vs reality: what the AI SAID it did, compared with what really happened.
4
+ * Deterministic patterns, no AI. A false claim never blocks proof by itself - it is reported loudly.
5
+ */
6
+
7
+ const CLAIMS = [
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
+ { 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
+ { 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?\b/i, text: 'Tests were not changed' },
12
+ { id: 'fixed', re: /\b(fixed|resolved|the (bug|issue|error) is (now )?(gone|fixed|resolved))\b/i, text: 'The problem is fixed' },
13
+ ];
14
+
15
+ function extract(text) {
16
+ const s = String(text || '').slice(-20000);
17
+ if (!s.trim()) return [];
18
+ const out = [];
19
+ for (const c of CLAIMS) {
20
+ const m = s.match(c.re);
21
+ if (m) out.push({ id: c.id, text: c.text, quote: quoteAround(s, m.index, m[0].length) });
22
+ }
23
+ return out;
24
+ }
25
+
26
+ function quoteAround(s, i, len) {
27
+ const start = Math.max(0, s.lastIndexOf('\n', i) + 1, i - 80);
28
+ let end = s.indexOf('\n', i + len); if (end < 0 || end - i > 120) end = Math.min(s.length, i + len + 80);
29
+ return s.slice(start, end).trim().slice(0, 200);
30
+ }
31
+
32
+ /**
33
+ * @param {string} text the AI's own words (final message)
34
+ * @param {object} r { after, changes, integrity, testFilesChanged, testCasesBefore, testCasesAfter, verdict }
35
+ */
36
+ function compare(text, r) {
37
+ const claims = extract(text);
38
+ const after = r.after || {};
39
+ const testSteps = Object.keys(after).filter((s) => /test/.test(s));
40
+ const buildSteps = Object.keys(after).filter((s) => !/test/.test(s));
41
+ const testChanges = (r.changes || []).filter((c) => r.isTest(c.file));
42
+ return claims.map((c) => {
43
+ let truth = null; let why = '';
44
+ if (c.id === 'tests_pass') { truth = testSteps.length ? testSteps.every((s) => after[s].pass) : null; why = testSteps.length ? testSteps.map((s) => `${s} ${after[s].pass ? 'passed' : 'failed'}`).join(', ') : 'no test step to check'; }
45
+ if (c.id === 'build_ok') { truth = buildSteps.length ? buildSteps.every((s) => after[s].pass) : null; why = buildSteps.length ? buildSteps.map((s) => `${s} ${after[s].pass ? 'passed' : 'failed'}`).join(', ') : 'no build step to check'; }
46
+ if (c.id === 'tests_added') { truth = (r.testCasesAfter || 0) > (r.testCasesBefore || 0); why = `test cases ${r.testCasesBefore || 0} -> ${r.testCasesAfter || 0}`; }
47
+ if (c.id === 'tests_untouched') { truth = testChanges.length === 0; why = testChanges.length ? `changed: ${testChanges.map((x) => x.file).join(', ')}` : 'no test file changed'; }
48
+ if (c.id === 'fixed') { truth = !!(r.verdict && r.verdict.ok); why = r.verdict ? (r.verdict.ok ? 'all checks pass' : `still failing: ${(r.verdict.stillFailing || []).concat(r.verdict.regressions || []).join(', ') || 'not proven'}`) : 'not checked'; }
49
+ return { ...c, truth, why };
50
+ });
51
+ }
52
+
53
+ module.exports = { extract, compare, CLAIMS };
package/core/config.js ADDED
@@ -0,0 +1,57 @@
1
+ 'use strict';
2
+ /** Config: defaults <- data/config.json <- env. Zero dependencies. */
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const crypto = require('crypto');
6
+
7
+ const ROOT = path.resolve(__dirname, '..');
8
+ // Installed with npm (inside node_modules): data lives in the user's home, so updates never touch it.
9
+ const NPM_MODE = /[\\/]node_modules[\\/]/.test(ROOT);
10
+ const HOME_DIR = path.join(require('os').homedir(), '.buildproof');
11
+ const DATA_DIR = process.env.MGR_DATA_DIR || (NPM_MODE ? path.join(HOME_DIR, 'data') : path.join(ROOT, 'data'));
12
+ const LOG_DIR = process.env.MGR_LOG_DIR || (NPM_MODE ? path.join(HOME_DIR, 'logs') : path.join(ROOT, 'logs'));
13
+ const CONFIG_FILE = path.join(DATA_DIR, 'config.json');
14
+
15
+ const DEFAULTS = {
16
+ port: 38700,
17
+ host: '0.0.0.0',
18
+ allowedHosts: [], // extra host names this server answers to (IPs, localhost and *.ts.net always work)
19
+ token: '', // generated on first run
20
+ ollama: { endpoint: 'http://127.0.0.1:11434', model: 'qwen2.5-coder:14b', timeoutMs: 180000 },
21
+ budget: { maxAiCallsPerTask: 3, maxTaskSeconds: 900 },
22
+ commandTimeoutMs: 300000,
23
+ maxScopeFiles: 8,
24
+ licenseServer: '', // e.g. https://buildproof.dev - countersigned, publicly logged certificates
25
+ maxFileBytes: 60000,
26
+ maxProjectFiles: 100000, // more files than this: the guard refuses (it never guards half a project)
27
+ bugHunter: 'warn', // hidden-bug hunt on proven changes: 'warn' (shown, not blocking), 'block', 'off'
28
+ bugHunterSeconds: 120,
29
+ ignoreDirs: ['node_modules', '.git', '.next', 'dist', 'build', 'out', 'coverage', '.expo', '.turbo', '.cache', 'Library', 'Temp', 'obj', 'bin', '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache', '.venv', 'venv', '.tox', 'target', 'vendor', '.gradle', '.phpunit.cache', '.phpunit.result.cache', '.rspec_status', '.bundle'],
30
+ };
31
+
32
+ function deepMerge(a, b) {
33
+ const out = { ...a };
34
+ for (const [k, v] of Object.entries(b || {})) {
35
+ out[k] = v && typeof v === 'object' && !Array.isArray(v) ? deepMerge(a[k] || {}, v) : v;
36
+ }
37
+ return out;
38
+ }
39
+
40
+ function load() {
41
+ fs.mkdirSync(DATA_DIR, { recursive: true });
42
+ // first run, or a damaged file (kept aside as config.json.corrupt-<time>, never silently overwritten)
43
+ const file = require('./keep-corrupt').readJsonSafe(CONFIG_FILE) || {};
44
+ let cfg = deepMerge(DEFAULTS, file);
45
+ if (!cfg.token) {
46
+ cfg.token = crypto.randomBytes(18).toString('base64url');
47
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify({ ...file, token: cfg.token }, null, 2), 'utf8');
48
+ }
49
+ if (process.env.MGR_PORT) cfg.port = Number(process.env.MGR_PORT);
50
+ if (process.env.MGR_TOKEN) cfg.token = process.env.MGR_TOKEN;
51
+ if (process.env.MGR_OLLAMA_ENDPOINT) cfg.ollama.endpoint = process.env.MGR_OLLAMA_ENDPOINT;
52
+ if (process.env.MGR_OLLAMA_MODEL) cfg.ollama.model = process.env.MGR_OLLAMA_MODEL;
53
+ if (process.env.MGR_LICENSE_SERVER) cfg.licenseServer = process.env.MGR_LICENSE_SERVER;
54
+ return cfg;
55
+ }
56
+
57
+ module.exports = { load, ROOT, DATA_DIR, LOG_DIR, NPM_MODE, HOME_DIR, CONFIG_FILE, DEFAULTS };
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+ /**
3
+ * Installed packages are not part of the snapshot (too big), so an AI could "fix" a failing test by editing
4
+ * node_modules/<the test runner or a dependency> instead of the code. Installs keep the package files' own dates
5
+ * (npm writes 1985), so a code file inside node_modules / the virtualenv that was written after the guard started,
6
+ * while no package / lock file changed, is an edit, not an install.
7
+ *
8
+ * Files written while BuildProof itself ran the project's scripts (baseline, checks: a build may write into
9
+ * node_modules/.prisma, caches ...) are the project's own doing: `windows` lists those [start, end] times.
10
+ *
11
+ * tampered(root, sinceMs, changes, windows) -> { file, total } | { skipped: reason } | null
12
+ */
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+
16
+ const DEP_DIRS = ['node_modules', '.venv', 'venv', 'vendor'];
17
+ const MANIFEST = /(^|\/)(package\.json|package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb|requirements[^/]*\.txt|pyproject\.toml|poetry\.lock|Pipfile(\.lock)?|uv\.lock|setup\.(py|cfg)|go\.(mod|sum)|Cargo\.(toml|lock)|composer\.(json|lock)|Gemfile(\.lock)?|pom\.xml|build\.gradle(\.kts)?|packages\.lock\.json|[^/]+\.csproj)$/i;
18
+ const CODE = /\.([cm]?js|[cm]?ts|jsx|tsx|node|py|pth|json|php|rb|go)$/i;
19
+ const SKIP = new Set(['__pycache__']); // and every folder whose name starts with a dot (.cache, .prisma, .vite, .bin ...)
20
+ const MAX_ENTRIES = 400000;
21
+ const MAX_MS = 8000;
22
+
23
+ function tampered(root, sinceMs, changes, windows) {
24
+ // a file written by the project's own scripts is written AFTER the run started (no slack before it, or an AI edit made just before a check would be missed)
25
+ const ours = (t) => (windows || []).some(([a, b]) => t >= a - 50 && t <= (b || Date.now()) + 2000);
26
+ if (!Number.isFinite(sinceMs)) return null;
27
+ if ((changes || []).some((c) => MANIFEST.test(c.file))) return { skipped: 'packages were installed or changed' };
28
+ const t0 = Date.now();
29
+ let seen = 0; let first = null; let total = 0;
30
+ const rec = (dir, rel) => {
31
+ let entries; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
32
+ for (const e of entries) {
33
+ if (++seen > MAX_ENTRIES || Date.now() - t0 > MAX_MS) throw new Error('budget');
34
+ if (SKIP.has(e.name) || e.name.startsWith('.') || e.isSymbolicLink()) continue;
35
+ const abs = path.join(dir, e.name); const r = rel + '/' + e.name;
36
+ if (e.isDirectory()) { rec(abs, r); continue; }
37
+ if (!e.isFile() || !CODE.test(e.name)) continue;
38
+ let st; try { st = fs.statSync(abs); } catch { continue; }
39
+ // ctime too: an edit can set the modified date back, not the change time
40
+ const t = Math.max(st.mtimeMs, st.ctimeMs);
41
+ if (t > sinceMs + 1000 && !ours(t)) { total++; if (!first) first = r.slice(1); }
42
+ }
43
+ };
44
+ try { for (const d of DEP_DIRS) if (fs.existsSync(path.join(root, d))) rec(path.join(root, d), '/' + d); }
45
+ catch (e) { if (e.message === 'budget') return first ? { file: first, total, partial: true } : { skipped: 'too many package files to scan in time' }; throw e; }
46
+ return first ? { file: first, total } : null;
47
+ }
48
+
49
+ module.exports = { tampered, MANIFEST };