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/LICENSE.txt ADDED
@@ -0,0 +1,2 @@
1
+ BuildProof - Copyright (c) 2026. All rights reserved.
2
+ Commercial software. Use requires an active trial or a license key.
package/README.md CHANGED
@@ -1,3 +1,26 @@
1
- # Temporary Holding Version
1
+ # BuildProof v3 - proof gate for AI-written code
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Works two ways, same guarantees:
4
+
5
+ **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.
6
+
7
+ **B. Guard my AI tool** - keep using Cursor, Claude Code, Copilot... Start guard (full copy + baseline), work, then Check:
8
+ - Test-integrity guard (10 rules): deleted / skipped / removed tests, changed expected values, new mocks, sleeps, silent catches, silenced checkers, changed test scripts or test config.
9
+ - Fail-closed gate: a check that did not really run (timeout, "no tests found", fewer tests than before) = NOT proven.
10
+ - Hardcoded answers (code that special-cases the test's values) and code that detects the test environment.
11
+ - Revert check: the original code is put back for a moment - the tests must FAIL without the change (covered), otherwise flaky / not covered.
12
+ - Claim vs reality: what the AI said it did ("all tests pass", "added tests", "didn't touch tests", "fixed") is checked against what really happened.
13
+ - Removing the BuildProof hook is itself detected (guard_disabled).
14
+ - Accept -> ed25519-signed certificate (self-verifying HTML). Rollback -> project byte-for-byte as at guard start.
15
+
16
+ One-tap hooks (Projects -> AI tools, or `buildproof connect git,claude,cursor`): Claude Code (UserPromptSubmit starts the guard, Stop checks - exit 2 sends the reason back to Claude), Cursor (beforeSubmitPrompt / stop with followup_message), git pre-commit. Existing files are backed up and merged.
17
+
18
+ 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).
19
+ 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.
20
+
21
+ Pull request checks (3.8.0; free trial, then Team and Enterprise): `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. 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
22
+
23
+ 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.
24
+
25
+ Run: `node scripts/guard.js` (keeps core/server.js alive on port 38700). Test: `node test/run-all.js`.
26
+ Data (config, token, signing key, tasks, backups, certificates, learned fixes): `data/` - never shipped, kept on reinstall.
@@ -0,0 +1,267 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /**
4
+ * BuildProof CLI - use the guard from a terminal, a git hook or an AI tool hook.
5
+ *
6
+ * buildproof start [folder] start guarding (copy + baseline), then work with any AI tool
7
+ * buildproof check [folder] [--claim "what the AI said"] exit 0 = proven, 1 = not proven
8
+ * buildproof accept [folder] [--force] accept and sign a certificate
9
+ * buildproof rollback [folder] restore the project exactly as at guard start
10
+ * buildproof connect [folder] git,claude,cursor install the hooks in one go
11
+ * buildproof status service and AI status
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
+ * buildproof init [folder] one-time setup: background service, project, AI tool hooks
15
+ * buildproof activate <key> activate a license key buildproof license show the plan
16
+ * buildproof open open BuildProof in the browser
17
+ * buildproof ci [folder] [--base origin/main] [--spec spec.md] pull request check for CI (--init writes the GitHub workflow)
18
+ * buildproof spec [folder] [--base main] check the change against .buildproof/spec.md (every requirement needs a passing test)
19
+ *
20
+ * Hook mode (installed by "connect"): --hook=claude | --hook=cursor | --hook=git
21
+ */
22
+ const fs = require('fs');
23
+ const path = require('path');
24
+ const http = require('http');
25
+ function openUrl(u) { // best effort: the default browser
26
+ try { const { spawn } = require('child_process'); const c = process.platform === 'win32' ? spawn('cmd', ['/c', 'start', '', u], { detached: true, stdio: 'ignore', windowsHide: true }) : spawn(process.platform === 'darwin' ? 'open' : 'xdg-open', [u], { detached: true, stdio: 'ignore' }); c.on('error', () => {}); c.unref(); return true; } catch { return false; }
27
+ }
28
+
29
+ const ROOT = path.resolve(__dirname, '..');
30
+ const config = require('../core/config');
31
+
32
+ const args = process.argv.slice(2);
33
+ const cmd = args[0] || 'help';
34
+ const flag = (n) => { const a = args.find((x) => x === `--${n}` || x.startsWith(`--${n}=`)); return a == null ? null : a.includes('=') ? a.split('=').slice(1).join('=') : true; };
35
+ const hook = flag('hook');
36
+ const force = !!flag('force');
37
+ let claimArg = null;
38
+ { const i = args.indexOf('--claim'); if (i >= 0) claimArg = args[i + 1] || ''; }
39
+ const positional = args.slice(1).filter((a, i, all) => !a.startsWith('--') && all[i - 1] !== '--claim');
40
+
41
+ function readStdin() {
42
+ if (!hook || process.stdin.isTTY) return Promise.resolve({});
43
+ return new Promise((resolve) => {
44
+ let raw = ''; const t = setTimeout(() => resolve(parse(raw)), 1500);
45
+ process.stdin.on('data', (d) => { raw += d; });
46
+ process.stdin.on('end', () => { clearTimeout(t); resolve(parse(raw)); });
47
+ process.stdin.on('error', () => { clearTimeout(t); resolve({}); });
48
+ });
49
+ function parse(s) { try { return JSON.parse(s); } catch { return {}; } }
50
+ }
51
+
52
+ function api(method, p, body) {
53
+ const c = config.load();
54
+ return new Promise((resolve) => {
55
+ const data = body ? JSON.stringify(body) : null;
56
+ const req = http.request({ host: '127.0.0.1', port: c.port, path: p, method, headers: { authorization: `Bearer ${c.token}`, ...(data ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) } : {}) }, timeout: 30 * 60 * 1000 }, (res) => {
57
+ let raw = ''; res.on('data', (d) => { raw += d; }); res.on('end', () => { try { resolve(JSON.parse(raw)); } catch { resolve({ ok: false, error: 'bad_response' }); } });
58
+ });
59
+ req.on('error', () => resolve({ ok: false, error: 'service_not_running', down: true }));
60
+ if (data) req.write(data);
61
+ req.end();
62
+ });
63
+ }
64
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
65
+ const same = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase();
66
+
67
+ function out(line, code) { if (line) console.log(line); process.exit(code); }
68
+
69
+ /** Hook replies in the format each tool understands. Hooks never block when BuildProof itself is not in use. */
70
+ function hookPass() {
71
+ if (hook === 'cursor') console.log(cmd === 'start' ? '{"continue":true}' : '{}');
72
+ process.exit(0);
73
+ }
74
+ function hookBlock(msg) {
75
+ if (hook === 'claude') { process.stderr.write(msg + '\n'); process.exit(2); }
76
+ if (hook === 'cursor') { console.log(JSON.stringify({ followup_message: msg })); process.exit(0); }
77
+ console.log(msg); process.exit(1); // git
78
+ }
79
+
80
+ function steps(after) { return Object.entries(after || {}).map(([s, r]) => `${s}=${r.pass ? 'PASS' : r.ran === false ? 'NOTRUN' : 'FAIL'}`).join(' '); }
81
+
82
+ async function findProject(dir, create) {
83
+ if (create) { const r = await api('POST', '/api/projects', { root: dir }); return r.ok ? r.project : (r.down ? { down: true } : null); }
84
+ const r = await api('GET', '/api/projects');
85
+ if (r.down) return { down: true };
86
+ return (r.projects || []).filter((p) => same(p.root, dir) || path.resolve(dir).toLowerCase().startsWith(path.resolve(p.root).toLowerCase() + path.sep)).sort((a, b) => b.root.length - a.root.length)[0] || null;
87
+ }
88
+ async function activeGuard(projectId) {
89
+ const r = await api('GET', '/api/tasks');
90
+ return (r.tasks || []).find((t) => t.kind === 'guard' && t.projectId === projectId && ['baselining', 'watching', 'checking'].includes(t.state));
91
+ }
92
+
93
+ async function main() {
94
+ if (cmd === 'ci' || cmd === 'spec') { // pull request check (Team+) / spec check (Pro+): no background service needed
95
+ const ci = require('../core/ci');
96
+ const folder = positional[0] || process.cwd();
97
+ if (cmd === 'ci' && flag('init')) { const r = ci.init(folder); out(r.ok ? `CI_WORKFLOW ${r.file} - add your key as the BUILDPROOF_LICENSE secret` : `CI_WORKFLOW_EXISTS ${r.file}`, r.ok ? 0 : 1); }
98
+ const lic = ci.licensed(require('../core/license'), cmd);
99
+ if (!lic.ok) out(`CANNOT_CHECK ${lic.why}`, 2);
100
+ const base = typeof flag('base') === 'string' ? flag('base') : null;
101
+ const r = await ci.check(folder, { base, spec: typeof flag('spec') === 'string' ? flag('spec') : null, requireSpec: cmd === 'spec', noBaseline: !!flag('no-baseline') });
102
+ const sum = typeof flag('summary') === 'string' ? flag('summary') : process.env.GITHUB_STEP_SUMMARY;
103
+ if (sum) { try { fs.appendFileSync(sum, r.md + '\n'); } catch { /* summary is optional */ } }
104
+ out(r.text, r.code);
105
+ }
106
+ if (cmd === 'verify') {
107
+ const certs = require('../core/certs');
108
+ const file = positional[0];
109
+ if (!file || !fs.existsSync(file)) out('usage: buildproof verify <certificate.html|.json>', 1);
110
+ const raw = fs.readFileSync(file, 'utf8');
111
+ const m = raw.match(/<script id="cert" type="application\/json">([\s\S]*?)<\/script>/);
112
+ const cert = JSON.parse(m ? m[1] : raw);
113
+ const ok = certs.verify(cert);
114
+ if (!ok) out('INVALID signature - the certificate was modified (or names a key it was not signed with)', 1);
115
+ if (!flag('rerun')) out(`VALID ${cert.payload.id} ${cert.payload.result} project=${cert.payload.project}`, 0);
116
+ // --rerun: is this exactly the certified code, and do the checks really pass here?
117
+ const rr = cert.payload.rerun;
118
+ if (!rr) out(`VALID ${cert.payload.id} - this certificate is too old for --rerun`, 1);
119
+ const dir = path.resolve(positional[1] || process.cwd());
120
+ const tree = certs.treeOf(dir, { legacy: !rr.walk }); // certificates from before 3.7.1 used the old folder rules
121
+ const problems = [];
122
+ if (tree.treeHash !== rr.treeHash) {
123
+ let detail = '';
124
+ if (rr.files && tree.files) {
125
+ const want = new Map(rr.files.map((f) => [f.file, f.sha256])); const have = new Map(tree.files.map((f) => [f.file, f.sha256]));
126
+ const diff = [...new Set([...want.keys(), ...have.keys()])].filter((f) => want.get(f) !== have.get(f));
127
+ detail = ` (${diff.length} file(s) differ: ${diff.slice(0, 5).join(', ')}${diff.length > 5 ? ', ...' : ''})`;
128
+ }
129
+ problems.push('the code is NOT the certified version' + detail);
130
+ }
131
+ const projects = require('../core/projects');
132
+ const { run } = require('../core/runner');
133
+ const gate = require('../core/gate');
134
+ const info = projects.detect(dir);
135
+ const results = [];
136
+ for (const step of rr.steps) {
137
+ const { cmd, args } = projects.commandFor(info, step);
138
+ process.stdout.write(`running ${step}...\r`);
139
+ const r = await run(cmd, args, { cwd: dir, timeoutMs: 10 * 60 * 1000 });
140
+ const g = gate.evaluate(step, r);
141
+ const was = (cert.payload.checks || []).find((c) => c.step === step);
142
+ results.push(`${step}=${g.pass ? 'PASS' : 'FAIL'}${g.tests ? '(' + g.tests.passed + '/' + g.tests.total + ')' : ''}`);
143
+ if (!g.pass) problems.push(`${step} fails here`);
144
+ else if (was && was.tests && g.tests && g.tests.total < was.tests.total) problems.push(`${step}: fewer tests ran here (${g.tests.total}) than certified (${was.tests.total})`);
145
+ }
146
+ out(problems.length ? `RERUN_MISMATCH ${cert.payload.id} | ${problems.join('; ')} | ${results.join(' ')}` : `RERUN_VERIFIED ${cert.payload.id} code=identical(${tree.count} files) ${results.join(' ')}`, problems.length ? 1 : 0);
147
+ }
148
+ if (cmd === 'repro') {
149
+ // replay one hidden-bug finding: buildproof repro <evidence.json> [project folder]
150
+ const file = positional[0];
151
+ if (!file || !fs.existsSync(file)) out('usage: buildproof repro <evidence.json> [project folder]', 1);
152
+ const f = JSON.parse(fs.readFileSync(file, 'utf8'));
153
+ const r = await require('../core/bug-hunter/engine').repro(path.resolve(positional[1] || process.cwd()), f);
154
+ out(`${r.reproduced ? 'REPRODUCED' : 'NOT_REPRODUCED'} ${f.oracle} ${f.file} ${f.export}(${f.inputPreview}) -> ${r.outcome}`, r.reproduced ? 0 : 1);
155
+ }
156
+ if (cmd === 'license' || cmd === 'activate') {
157
+ if (cmd === 'activate') {
158
+ let key = positional[0] || '';
159
+ if (!key) { // no key typed: take it from the clipboard (copied on the thank-you page)
160
+ const { spawnSync } = require('child_process');
161
+ const c = process.platform === 'win32' ? spawnSync('powershell', ['-NoProfile', '-Command', 'Get-Clipboard'], { encoding: 'utf8', windowsHide: true }) : spawnSync(process.platform === 'darwin' ? 'pbpaste' : 'xclip', process.platform === 'darwin' ? [] : ['-o', '-selection', 'clipboard'], { encoding: 'utf8' });
162
+ key = ((c.stdout || '').match(/BP1\.[\w-]+\.[\w-]+/) || [''])[0];
163
+ if (!key) out('ACTIVATE_FAIL no key - copy it from the thank-you page, or: buildproof activate <key>', 1);
164
+ }
165
+ const r = await api('POST', '/api/license', { key });
166
+ out(r.ok ? `ACTIVATED ${r.license.label} until ${String(r.license.expires).slice(0, 10)}` : `ACTIVATE_FAIL ${r.error}`, r.ok ? 0 : 1);
167
+ }
168
+ const r = await api('GET', '/api/license');
169
+ if (!r.ok) out(`DOWN ${r.error}`, 1);
170
+ out(`LICENSE ${r.label} ${r.status}${r.daysLeft != null ? ' days_left=' + r.daysLeft : ''}${r.projects ? ' projects_max=' + r.projects : ''}`, r.status === 'expired' ? 1 : 0);
171
+ }
172
+ if (cmd === 'init') {
173
+ const service = require('../core/service');
174
+ const sv = await service.ensure({ autostart: !process.env.MGR_NO_AUTOSTART });
175
+ if (!sv.ok) out(`INIT_FAIL BuildProof could not start on port ${sv.port}`, 1);
176
+ const dir = path.resolve(positional[0] || process.cwd());
177
+ const pr = await api('POST', '/api/projects', { root: dir });
178
+ if (!pr.ok) out(`INIT_FAIL ${pr.error}${pr.limit ? ' (limit ' + pr.limit + ' projects in this plan)' : ''}`, 1);
179
+ const { spawnSync } = require('child_process');
180
+ const onPath = (c) => { try { return spawnSync(process.platform === 'win32' ? 'where' : 'which', [c], { stdio: 'ignore' }).status === 0; } catch { return false; } };
181
+ const tools = [];
182
+ if (fs.existsSync(path.join(dir, '.claude')) || onPath('claude')) tools.push('claude');
183
+ if (fs.existsSync(path.join(dir, '.cursor')) || onPath('cursor')) tools.push('cursor');
184
+ if (fs.existsSync(path.join(dir, '.git'))) tools.push('git');
185
+ let hk = { ok: true, hooks: {} };
186
+ if (tools.length) hk = await api('POST', `/api/projects/${pr.project.id}/hooks`, { tools });
187
+ const lic = await api('GET', '/api/license');
188
+ const connected = Object.entries(hk.hooks || {}).filter(([, v]) => v.connected).map(([k]) => k);
189
+ console.log(`INIT project=${pr.project.name} type=${pr.project.type} proof=${pr.project.verify.join(',') || 'none'} tools=${connected.join(',') || 'none'} service=${sv.how}${sv.autostart ? '/' + sv.autostart : ''} license=${lic.label}:${lic.status}${lic.daysLeft != null ? '(' + lic.daysLeft + 'd)' : ''}`);
190
+ if (!process.env.MGR_NO_AUTOSTART && !process.env.MGR_NO_OPEN) openUrl(`http://127.0.0.1:${sv.port}/connect`);
191
+ out(`OPEN http://127.0.0.1:${sv.port}/connect (BuildProof on this computer + add your phone)`, 0);
192
+ }
193
+ if (cmd === 'open') { const u = `http://127.0.0.1:${config.load().port || 38700}/connect`; openUrl(u); out('OPEN ' + u, 0); }
194
+ if (cmd === 'status') {
195
+ const r = await api('GET', '/api/status');
196
+ out(r.ok ? `BUILDPROOF v${r.version} AI=${r.ai.ok ? 'OK' : 'DOWN'} fixes=${r.fixes} key=${r.fingerprint}` : `DOWN ${r.error}`, r.ok ? 0 : 1);
197
+ }
198
+ if (!['start', 'check', 'accept', 'rollback', 'connect'].includes(cmd)) {
199
+ out(fs.readFileSync(__filename, 'utf8').split('\n').slice(3, 19).map((l) => l.replace(/^ \* ?/, '')).join('\n'), cmd === 'help' ? 0 : 1);
200
+ }
201
+
202
+ const input = await readStdin();
203
+ const folder = path.resolve(positional[0] && cmd !== 'connect' ? positional[0] : (cmd === 'connect' && positional.length > 1 ? positional[0] : (input.cwd || (input.workspace_roots && input.workspace_roots[0]) || process.cwd())));
204
+ // only start / connect register a new project; check, accept and rollback must work on a known project even when the licence has ended
205
+ const p = await findProject(folder, !hook && ['start', 'connect'].includes(cmd));
206
+ if (!p || p.down) {
207
+ // service down while a guard is active for this folder: a hook must NOT let the work through unchecked
208
+ if (hook && p && p.down && cmd === 'check') {
209
+ const crypto = require('crypto'); const { DATA_DIR } = require('../core/config');
210
+ for (let d = folder; ; d = path.dirname(d)) {
211
+ if (fs.existsSync(path.join(DATA_DIR, 'active-guards', crypto.createHash('sha256').update(path.resolve(d).toLowerCase()).digest('hex').slice(0, 24) + '.json'))) hookBlock('BuildProof: a guard is active for this project, but the BuildProof service is not running, so nothing can be checked. Start it (buildproof open), then check again.');
212
+ if (path.dirname(d) === d) break;
213
+ }
214
+ }
215
+ if (hook) hookPass();
216
+ out(p && p.down ? 'DOWN service_not_running (start BuildProof first)' : `NOT_A_PROJECT ${folder}`, 1);
217
+ }
218
+
219
+ if (cmd === 'connect') {
220
+ const tools = (positional[positional.length - 1] || 'git,claude,cursor').split(',').map((s) => s.trim());
221
+ const r = await api('POST', `/api/projects/${p.id}/hooks`, { tools });
222
+ out(r.ok ? `CONNECTED ${Object.entries(r.hooks).filter(([, v]) => v.connected).map(([k]) => k).join(',')}` : `FAIL ${r.error || JSON.stringify(r.result)}`, r.ok ? 0 : 1);
223
+ }
224
+
225
+ let g = await activeGuard(p.id);
226
+ if (cmd === 'start') {
227
+ if (!g) { const r = await api('POST', '/api/guards', { projectId: p.id, source: hook ? hook : 'cli' }); if (!r.ok) { if (hook) hookPass(); out(`FAIL ${r.error}`, 1); } g = r.task; }
228
+ if (hook) hookPass(); // do not make the developer wait for the baseline
229
+ while (g && g.state === 'baselining') { await sleep(1000); g = (await api('GET', `/api/tasks/${g.id}`)).task; }
230
+ if (!g || g.state !== 'watching') out(`FAIL ${g ? g.resultText : 'guard not started'}`, 1);
231
+ const full = (await api('GET', `/api/tasks/${g.id}`)).task;
232
+ out(`GUARD_ON ${p.name} baseline: ${steps(full.baseline) || 'no build/test scripts'}`, 0);
233
+ }
234
+ if (!g) { if (hook) hookPass(); out(`NO_GUARD for ${p.name}. Run: buildproof start`, 1); }
235
+ while (g.state === 'baselining' || g.state === 'checking') { await sleep(1000); g = (await api('GET', `/api/tasks/${g.id}`)).task; }
236
+
237
+ if (cmd === 'check') {
238
+ const claim = claimArg != null ? claimArg : (input.last_assistant_message || input.text || '');
239
+ const r = await api('POST', `/api/guards/${g.id}/check`, { claim });
240
+ if (!r.ok) { if (hook) hookPass(); out(`FAIL ${r.error}`, 1); }
241
+ const full = (await api('GET', `/api/tasks/${g.id}`)).task;
242
+ const files = (full.changedFiles || []).length;
243
+ const integ = full.integrity && !full.integrity.clean ? full.integrity.findings.map((f) => `${f.text} (${f.file}: ${f.detail})`) : [];
244
+ const falseClaims = (full.claims || []).filter((c) => c.truth === false).map((c) => `You said "${c.text}" but that is not true: ${c.why}`);
245
+ if (hook) {
246
+ if (files === 0) hookPass();
247
+ if (r.proven) {
248
+ if (falseClaims.length && hook === 'claude' && !input.stop_hook_active) { process.stderr.write(`BuildProof: the change is proven, but correct your summary. ${falseClaims.join('. ')}.\n`); process.exit(2); }
249
+ hookPass();
250
+ }
251
+ hookBlock(['BuildProof: NOT PROVEN. ' + full.resultText, ...integ.map((x) => '- ' + x), ...falseClaims.map((x) => '- ' + x),
252
+ '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'));
253
+ }
254
+ const extra = [integ.length ? 'integrity: ' + integ.join('; ') : '', falseClaims.length ? 'claims: ' + falseClaims.join('; ') : '', full.revertCheck ? 'revert: ' + full.revertCheck.verdict : ''].filter(Boolean).join(' | ');
255
+ out(`${r.proven ? 'PROVEN' : 'NOT_PROVEN'} files=${files} ${steps(full.after)}${extra ? ' | ' + extra : ''} | ${full.resultText}`, r.proven ? 0 : 1);
256
+ }
257
+ if (cmd === 'accept') {
258
+ const r = await api('POST', `/api/guards/${g.id}/accept`, { force });
259
+ out(r.ok ? (r.cert ? `CERTIFICATE ${r.cert.id}${force ? ' (with warnings)' : ''}` : 'ACCEPTED (certificates are not in this plan)') : `FAIL ${r.error}`, r.ok ? 0 : 1);
260
+ }
261
+ if (cmd === 'rollback') {
262
+ const r = await api('POST', `/api/guards/${g.id}/rollback`, {});
263
+ out(r.ok ? `ROLLED_BACK restored=${r.restored.length}${r.packagesEdited ? ` packages_edited=${r.packagesEdited} (reinstall them: npm ci)` : ''}` : `FAIL ${r.error}`, r.ok ? 0 : 1);
264
+ }
265
+ }
266
+
267
+ main();
package/core/ai.js ADDED
@@ -0,0 +1,193 @@
1
+ 'use strict';
2
+ /**
3
+ * AI worker for "BuildProof fixes it". The AI only PROPOSES full-file edits; the supervisor decides.
4
+ * Providers: ollama (local, default) | openai (or any OpenAI-compatible server) | anthropic | claude-code (the developer's own CLI).
5
+ * API keys live only in data/secrets.json on this computer, encrypted (or in env vars) - never in the config or the UI.
6
+ */
7
+ const fs = require('fs');
8
+ const os = require('os');
9
+ const path = require('path');
10
+ const http = require('http');
11
+ const https = require('https');
12
+ const { spawn } = require('child_process');
13
+
14
+ const SECRETS = () => path.join(require('./config').DATA_DIR, 'secrets.json');
15
+ // encrypted at rest (AES-256-GCM, key protected by Windows DPAPI) - see vault.js
16
+ function secrets() { try { return require('./vault').readFile(SECRETS()); } catch { return {}; } }
17
+ function saveSecret(name, value) {
18
+ const s = secrets();
19
+ if (value) s[name] = String(value).trim(); else delete s[name];
20
+ require('./vault').writeFile(SECRETS(), s);
21
+ }
22
+ function keyFor(provider) {
23
+ if (provider === 'openai') return process.env.OPENAI_API_KEY || secrets().openaiKey || '';
24
+ if (provider === 'anthropic') return process.env.ANTHROPIC_API_KEY || secrets().anthropicKey || '';
25
+ return '';
26
+ }
27
+ const isLocalUrl = (u) => { try { return /^(localhost|127\.\d+\.\d+\.\d+|\[?::1\]?)$/i.test(new URL(u).hostname); } catch { return false; } };
28
+
29
+ /** Which AI is in use, in one place. */
30
+ function describe(cfg) {
31
+ const a = cfg.ai || {};
32
+ const provider = a.provider || 'ollama';
33
+ if (provider === 'openai') { const endpoint = a.endpoint || 'https://api.openai.com/v1'; return { provider, model: a.model || '', endpoint, local: isLocalUrl(endpoint), label: `${a.model || '(no model)'} via ${isLocalUrl(endpoint) ? 'local OpenAI-compatible server' : new URL(endpoint).hostname}` }; }
34
+ if (provider === 'anthropic') return { provider, model: a.model || 'claude-sonnet-5-5', endpoint: a.endpoint || 'https://api.anthropic.com', local: false, label: `${a.model || 'claude-sonnet-5-5'} (Anthropic API)` };
35
+ if (provider === 'claude-code') return { provider, model: a.model || '', local: false, label: `Claude Code${a.model ? ' · ' + a.model : ''}` };
36
+ return { provider: 'ollama', model: cfg.ollama.model, endpoint: cfg.ollama.endpoint, local: isLocalUrl(cfg.ollama.endpoint), label: cfg.ollama.model };
37
+ }
38
+
39
+ function request(urlStr, body, timeoutMs, headers = {}) {
40
+ return new Promise((resolve) => {
41
+ const url = new URL(urlStr);
42
+ const lib = url.protocol === 'https:' ? https : http;
43
+ const data = body ? JSON.stringify(body) : null;
44
+ const req = lib.request({
45
+ method: body ? 'POST' : 'GET',
46
+ hostname: url.hostname, port: url.port, path: url.pathname + url.search,
47
+ headers: { ...(data ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) } : {}), ...headers },
48
+ timeout: timeoutMs,
49
+ }, (res) => {
50
+ let raw = '';
51
+ res.on('data', (d) => { raw += d; });
52
+ res.on('end', () => {
53
+ try { resolve({ ok: res.statusCode === 200, status: res.statusCode, json: JSON.parse(raw) }); }
54
+ catch { resolve({ ok: false, status: res.statusCode, raw }); }
55
+ });
56
+ });
57
+ req.on('timeout', () => { req.destroy(); resolve({ ok: false, error: 'timeout' }); });
58
+ req.on('error', (e) => resolve({ ok: false, error: e.message }));
59
+ if (data) req.write(data);
60
+ req.end();
61
+ });
62
+ }
63
+
64
+ function claudeBin() { const b = process.env.MGR_CLAUDE_BIN || 'claude'; return process.platform === 'win32' && /\s/.test(b) ? `"${b}"` : b; }
65
+ // Windows needs the shell for claude.cmd - and the shell drops empty args (--tools "") unless they are quoted
66
+ const WIN = process.platform === 'win32';
67
+ const winArgs = (args) => (WIN ? args.map((a) => (a === '' ? '""' : /[\s"&|<>^]/.test(a) ? '"' + a.replace(/"/g, '\\"') + '"' : a)) : args);
68
+
69
+ async function health(cfg) {
70
+ const d = describe(cfg);
71
+ if (d.provider === 'openai') {
72
+ if (!d.model) return { ok: false, model: d.label, reason: 'no_model_set' };
73
+ if (!keyFor('openai') && !d.local) return { ok: false, model: d.label, reason: 'no_api_key' };
74
+ return { ok: true, model: d.label, provider: d.provider };
75
+ }
76
+ if (d.provider === 'anthropic') return keyFor('anthropic') ? { ok: true, model: d.label, provider: d.provider } : { ok: false, model: d.label, reason: 'no_api_key' };
77
+ if (d.provider === 'claude-code') {
78
+ const ok = await new Promise((resolve) => { try { const c = spawn(claudeBin(), ['--version'], { windowsHide: true, shell: process.platform === 'win32' }); c.on('error', () => resolve(false)); c.on('close', (code) => resolve(code === 0)); } catch { resolve(false); } });
79
+ return ok ? { ok: true, model: d.label, provider: d.provider } : { ok: false, model: d.label, reason: 'claude_not_installed' };
80
+ }
81
+ const r = await request(`${cfg.ollama.endpoint}/api/tags`, null, 4000);
82
+ if (!r.ok) return { ok: false, reason: r.error || `http_${r.status}` };
83
+ const models = (r.json.models || []).map((m) => m.name);
84
+ return { ok: models.includes(cfg.ollama.model), models, model: cfg.ollama.model, reason: models.includes(cfg.ollama.model) ? null : 'model_not_installed' };
85
+ }
86
+
87
+ function buildPrompt({ instruction, files, context, failure, attempt }) {
88
+ const fileBlocks = files.map((f) => `### FILE: ${f.path}\n${f.content == null ? '(new file - does not exist yet)' : f.content}`).join('\n\n');
89
+ const ctxBlocks = (context || []).map((f) => `### READ-ONLY TEST: ${f.path}\n${f.content}`).join('\n\n');
90
+ return [
91
+ 'You are a careful senior software engineer. Make the SMALLEST correct change.',
92
+ 'Rules:',
93
+ '- You may ONLY edit the files listed below. Never invent other files.',
94
+ '- Return the COMPLETE new content of each file you change (not a diff).',
95
+ '- Do not change behavior that was not requested. Do not delete or weaken tests.',
96
+ '- Tests are CORRECT. Never say a test is wrong; fix the code. Never special-case test values.',
97
+ '- If the task is impossible with these files, return no edits and explain in "summary".',
98
+ 'Respond with JSON only: {"summary": "<one short sentence>", "edits": [{"path": "<file>", "content": "<full new content>"}]}',
99
+ '',
100
+ `TASK: ${instruction}`,
101
+ failure ? `\nCURRENT FAILURE (attempt ${attempt}) - fix this:\n${failure.slice(-6000)}` : '',
102
+ ctxBlocks ? '\nThe tests below are READ-ONLY. Use them to see the expected behavior and the exact names they use. Never edit them.\n\n' + ctxBlocks : '',
103
+ '\nFILES YOU MAY EDIT:\n',
104
+ fileBlocks,
105
+ ].join('\n');
106
+ }
107
+
108
+ /** Pull the JSON answer out of a model reply (it may wrap it in text or ``` fences). */
109
+ function parseAnswer(text) {
110
+ const t = String(text || '');
111
+ try { return JSON.parse(t); } catch { /* look inside */ }
112
+ const a = t.indexOf('{'); const b = t.lastIndexOf('}');
113
+ if (a >= 0 && b > a) { try { return JSON.parse(t.slice(a, b + 1)); } catch { /* invalid */ } }
114
+ return null;
115
+ }
116
+ function result(parsed, tokens, ms) {
117
+ if (!parsed) return { ok: false, error: 'invalid_json_from_model' };
118
+ const edits = Array.isArray(parsed.edits) ? parsed.edits.filter((e) => e && typeof e.path === 'string' && typeof e.content === 'string') : [];
119
+ return { ok: true, summary: String(parsed.summary || '').slice(0, 500), edits, tokens: tokens || { prompt: 0, output: 0 }, ms: ms || 0 };
120
+ }
121
+ const temperature = (input) => [0.1, 0.5, 0.8][Math.min((input.attempt || 1) - 1, 2)];
122
+
123
+ async function proposeOpenAI(cfg, d, prompt, input) {
124
+ const t0 = Date.now();
125
+ const r = await request(`${d.endpoint.replace(/\/$/, '')}/chat/completions`, { model: d.model, temperature: temperature(input), response_format: { type: 'json_object' }, messages: [{ role: 'user', content: prompt }] }, cfg.ollama.timeoutMs, keyFor('openai') ? { authorization: `Bearer ${keyFor('openai')}` } : {});
126
+ if (!r.ok) return { ok: false, error: r.error || `http_${r.status}${r.json && r.json.error ? ': ' + (r.json.error.message || '').slice(0, 120) : ''}` };
127
+ const msg = r.json.choices && r.json.choices[0] && r.json.choices[0].message;
128
+ const u = r.json.usage || {};
129
+ return result(parseAnswer(msg && msg.content), { prompt: u.prompt_tokens || 0, output: u.completion_tokens || 0 }, Date.now() - t0);
130
+ }
131
+
132
+ async function proposeAnthropic(cfg, d, prompt, input) {
133
+ const t0 = Date.now();
134
+ const r = await request(`${d.endpoint.replace(/\/$/, '')}/v1/messages`, { model: d.model, max_tokens: 16000, temperature: temperature(input), messages: [{ role: 'user', content: prompt }] }, cfg.ollama.timeoutMs, { 'x-api-key': keyFor('anthropic'), 'anthropic-version': '2023-06-01' });
135
+ if (!r.ok) return { ok: false, error: r.error || `http_${r.status}${r.json && r.json.error ? ': ' + (r.json.error.message || '').slice(0, 120) : ''}` };
136
+ const text = (r.json.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('');
137
+ const u = r.json.usage || {};
138
+ return result(parseAnswer(text), { prompt: u.input_tokens || 0, output: u.output_tokens || 0 }, Date.now() - t0);
139
+ }
140
+
141
+ /** The developer's own Claude Code, with every tool switched off: it can only answer, never touch files. */
142
+ function proposeClaudeCode(cfg, d, prompt) {
143
+ const t0 = Date.now();
144
+ return new Promise((resolve) => {
145
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'bp-claude-'));
146
+ const args = ['-p', '--output-format', 'json', '--tools', ''];
147
+ if (d.model) args.push('--model', d.model);
148
+ let out = ''; let err = '';
149
+ let child;
150
+ try { child = spawn(claudeBin(), winArgs(args), { cwd, windowsHide: true, shell: process.platform === 'win32' }); } catch (e) { resolve({ ok: false, error: e.message }); return; }
151
+ const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, cfg.ollama.timeoutMs);
152
+ child.stdout.on('data', (x) => { out += x; });
153
+ child.stderr.on('data', (x) => { err += x; });
154
+ child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, error: e.message }); });
155
+ child.on('close', (code) => {
156
+ clearTimeout(timer);
157
+ try { fs.rmSync(cwd, { recursive: true, force: true }); } catch { /* temp */ }
158
+ if (code !== 0) { resolve({ ok: false, error: `claude exited ${code}: ${err.slice(-200)}` }); return; }
159
+ let text = out; let usage = {};
160
+ try { const j = JSON.parse(out); text = j.result || ''; usage = j.usage || {}; } catch { /* plain text */ }
161
+ resolve(result(parseAnswer(text), { prompt: usage.input_tokens || 0, output: usage.output_tokens || 0 }, Date.now() - t0));
162
+ });
163
+ child.stdin.end(prompt);
164
+ });
165
+ }
166
+
167
+ async function proposeEdits(cfg, input) {
168
+ const prompt = buildPrompt(input);
169
+ const d = describe(cfg);
170
+ if (d.provider === 'openai') return proposeOpenAI(cfg, d, prompt, input);
171
+ if (d.provider === 'anthropic') return proposeAnthropic(cfg, d, prompt, input);
172
+ if (d.provider === 'claude-code') return proposeClaudeCode(cfg, d, prompt);
173
+ const r = await request(`${cfg.ollama.endpoint}/api/generate`, {
174
+ model: cfg.ollama.model,
175
+ prompt,
176
+ stream: false,
177
+ format: 'json',
178
+ options: { temperature: [0.1, 0.5, 0.8][Math.min((input.attempt || 1) - 1, 2)], num_ctx: 16384 },
179
+ }, cfg.ollama.timeoutMs);
180
+ if (!r.ok) return { ok: false, error: r.error || `http_${r.status}` };
181
+ let parsed;
182
+ try { parsed = JSON.parse(r.json.response || '{}'); } catch { return { ok: false, error: 'invalid_json_from_model', raw: String(r.json.response || '').slice(0, 500) }; }
183
+ const edits = Array.isArray(parsed.edits) ? parsed.edits.filter((e) => e && typeof e.path === 'string' && typeof e.content === 'string') : [];
184
+ return {
185
+ ok: true,
186
+ summary: String(parsed.summary || '').slice(0, 500),
187
+ edits,
188
+ tokens: { prompt: r.json.prompt_eval_count || 0, output: r.json.eval_count || 0 },
189
+ ms: Math.round((r.json.total_duration || 0) / 1e6),
190
+ };
191
+ }
192
+
193
+ module.exports = { health, proposeEdits, buildPrompt, request, describe, saveSecret, secrets, parseAnswer };
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+ /**
3
+ * Antivirus scan (ClamAV) of the files the AI changed since guard start.
4
+ * scan(root, files) -> { engine, status, hits:[{file, sig}], scanned, detail }
5
+ * status: 'clean' | 'infected' | 'not_installed' | 'error'
6
+ * Engine: env MGR_CLAMSCAN_BIN, else clamscan on PATH, else the default Windows install folder.
7
+ * Never throws. Missing ClamAV = 'not_installed' (the check goes on). Only 'infected' blocks approval.
8
+ */
9
+ const fs = require('fs'), path = require('path'), { spawnSync } = require('child_process');
10
+ const IS_WIN = process.platform === 'win32';
11
+ const MAX_FILES = 500;
12
+
13
+ function onPath(name) {
14
+ const exts = IS_WIN ? ['.exe', '.cmd', '.bat', ''] : [''];
15
+ for (const d of String(process.env.PATH || '').split(path.delimiter)) {
16
+ if (!d) continue;
17
+ for (const e of exts) { const f = path.join(d, name + e); try { if (fs.statSync(f).isFile()) return f; } catch { /* next */ } }
18
+ }
19
+ return null;
20
+ }
21
+
22
+ function engine() {
23
+ if (process.env.MGR_CLAMSCAN_BIN !== undefined) {
24
+ const b = process.env.MGR_CLAMSCAN_BIN;
25
+ return b && fs.existsSync(b) ? b : null; // set but empty / missing = "not installed" (used by tests)
26
+ }
27
+ const found = onPath('clamscan'); // clamdscan needs a running clamd - only used when set in MGR_CLAMSCAN_BIN
28
+ if (found) return found;
29
+ if (IS_WIN) for (const f of ['C:\\Program Files\\ClamAV\\clamscan.exe', 'C:\\Program Files (x86)\\ClamAV\\clamscan.exe']) if (fs.existsSync(f)) return f;
30
+ return null;
31
+ }
32
+
33
+ function run(bin, args) {
34
+ // a .js engine (used by tests) runs with this node
35
+ const [cmd, a] = /\.js$/i.test(bin) ? [process.execPath, [bin, ...args]] : [bin, args];
36
+ return spawnSync(cmd, a, { encoding: 'utf8', windowsHide: true, timeout: 5 * 60e3, maxBuffer: 16 * 1024 * 1024 });
37
+ }
38
+
39
+ function scan(root, files) {
40
+ const bin = engine();
41
+ if (!bin) return { engine: null, status: 'not_installed', hits: [], scanned: 0, detail: 'ClamAV not found' };
42
+ const base = path.resolve(root);
43
+ const abs = [];
44
+ for (const f of files || []) {
45
+ const p = path.resolve(base, f);
46
+ if (!p.startsWith(base + path.sep)) continue; // never outside the project
47
+ try { if (fs.lstatSync(p).isFile()) abs.push(p); } catch { /* deleted */ }
48
+ }
49
+ if (!abs.length) return { engine: bin, status: 'clean', hits: [], scanned: 0, detail: 'no files to scan' };
50
+ const hits = []; let scanned = 0;
51
+ for (let i = 0; i < Math.min(abs.length, MAX_FILES); i += 50) {
52
+ const batch = abs.slice(i, i + 50);
53
+ const r = run(bin, ['--no-summary', '--infected', ...batch]);
54
+ if (r.error) return { engine: bin, status: 'error', hits, scanned, detail: r.error.message };
55
+ // clamscan: 0 = clean, 1 = virus found, 2 = error
56
+ for (const line of String(r.stdout || '').split(/\r?\n/)) {
57
+ const m = line.match(/^(.*): (.+) FOUND$/);
58
+ if (m) hits.push({ file: path.relative(base, path.resolve(m[1].trim())).split(path.sep).join('/'), sig: m[2].trim() });
59
+ }
60
+ if (r.status === 2 || (r.status === 1 && !hits.length) || r.status === null) return { engine: bin, status: 'error', hits, scanned, detail: String(r.stderr || '').trim().slice(0, 300) || `exit ${r.status}` };
61
+ scanned += batch.length;
62
+ }
63
+ return { engine: bin, status: hits.length ? 'infected' : 'clean', hits, scanned, detail: abs.length > MAX_FILES ? `only first ${MAX_FILES} files scanned` : '' };
64
+ }
65
+
66
+ module.exports = { scan, engine };
@@ -0,0 +1,4 @@
1
+ 'use strict';
2
+ // the hidden bug hunt runs on the BuildProof server (isolated sandbox, signed results); it is not shipped
3
+ const msg='the hidden bug hunt runs on the BuildProof server';
4
+ module.exports={hunt:async()=>({error:msg,findings:[],regressions:[],stats:{}}),repro:async()=>({reproduced:false,outcome:msg})};