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.
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+ /**
3
+ * A JSON file that cannot be read is NEVER silently replaced: it is moved aside as <file>.corrupt-<time> first,
4
+ * so the data can still be recovered by hand. Returns the parsed value, or null (missing or damaged file).
5
+ */
6
+ const fs = require('fs');
7
+ function readJsonSafe(file) {
8
+ let raw;
9
+ try { raw = fs.readFileSync(file, 'utf8'); } catch { return null; }
10
+ try { return JSON.parse(raw); } catch {
11
+ if (!raw.trim()) return null;
12
+ const aside = `${file}.corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}`;
13
+ try { fs.renameSync(file, aside); console.error(`[buildproof] damaged file kept as ${aside}`); } catch { /* read-only: leave it */ }
14
+ return null;
15
+ }
16
+ }
17
+ module.exports = { readJsonSafe };
@@ -0,0 +1,165 @@
1
+ 'use strict';
2
+ /**
3
+ * Licensing - works offline.
4
+ * Trial: 14 days, up to 2 projects, every Pro feature.
5
+ * Plans: basic $15 | pro $25 | team $50/user | enterprise from $90/user (min 10).
6
+ * Key: "BP1.<payload>.<signature>" - ed25519 signed by the vendor; verified here with the vendor PUBLIC key only.
7
+ * After the trial / license ends nothing is deleted: history, proofs and certificates stay readable, only new work is locked.
8
+ */
9
+ const fs = require('fs');
10
+ const os = require('os');
11
+ const path = require('path');
12
+ const crypto = require('crypto');
13
+ const { DATA_DIR, ROOT } = require('./config');
14
+
15
+ const TRIAL_DAYS = 14;
16
+ const GRACE_DAYS = 3;
17
+ const DAY = 864e5;
18
+
19
+ const F = { guard: 'guard', hooks: 'hooks', certificates: 'certificates', remote: 'remote', revertCheck: 'revertCheck', claims: 'claims', aiFix: 'aiFix', ci: 'ci', spec: 'spec', verifyPage: 'verifyPage', dashboard: 'dashboard', sso: 'sso', audit: 'audit' };
20
+ const BASIC = [F.guard, F.hooks];
21
+ const PRO = [...BASIC, F.certificates, F.remote, F.revertCheck, F.claims, F.aiFix, F.spec];
22
+ const TEAM = [...PRO, F.ci, F.verifyPage, F.dashboard];
23
+ const PLANS = {
24
+ trial: { label: 'Trial', price: 'free for 14 days', projects: 2, features: [...PRO, F.ci] }, // the trial opens everything up to Team checks
25
+ basic: { label: 'Basic', price: '$15 / month', projects: 3, features: BASIC },
26
+ pro: { label: 'Pro', price: '$25 / month', projects: Infinity, features: PRO },
27
+ team: { label: 'Team', price: '$50 / user / month', projects: Infinity, features: TEAM },
28
+ enterprise: { label: 'Enterprise', price: 'from $90 / user / month, 10 users minimum', projects: Infinity, features: [...TEAM, F.sso, F.audit] },
29
+ };
30
+ const FEATURE_TEXT = {
31
+ guard: 'Guard any AI tool + test-integrity rules', hooks: 'One-tap Claude Code / Cursor / git hooks', certificates: 'Signed proof certificates',
32
+ remote: 'Phone and tablet control', revertCheck: 'Revert check', claims: 'AI claim check', aiFix: 'BuildProof fixes it (local AI)',
33
+ ci: 'CI / pull request checks', spec: 'Spec check: every requirement proven by a passing test', verifyPage: 'Public verify page', dashboard: 'Team dashboard', sso: 'Single sign-on', audit: 'Audit reports',
34
+ };
35
+
36
+ const FILE = () => path.join(DATA_DIR, 'license.json');
37
+ const MARKER = () => process.env.MGR_TRIAL_MARKER || path.join(os.homedir(), '.buildproof_trial');
38
+
39
+ function readJson(f) { return require('./keep-corrupt').readJsonSafe(f); } // a damaged licence file is kept aside, never overwritten
40
+ function b64u(buf) { return Buffer.from(buf).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }
41
+ function unb64u(s) { return Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64'); }
42
+
43
+ function vendorKey() {
44
+ const f = process.env.MGR_VENDOR_PUB_FILE || path.join(ROOT, 'license', 'vendor.pub.pem');
45
+ try { return crypto.createPublicKey(fs.readFileSync(f)); } catch { return null; }
46
+ }
47
+
48
+ /** Decode + verify a key. Returns {ok, payload} or {ok:false, error}. */
49
+ function parseKey(key) {
50
+ const parts = String(key || '').trim().split('.');
51
+ if (parts.length !== 3 || parts[0] !== 'BP1') return { ok: false, error: 'invalid_key_format' };
52
+ const pub = vendorKey();
53
+ if (!pub) return { ok: false, error: 'no_vendor_key' };
54
+ let payload;
55
+ try { payload = JSON.parse(unb64u(parts[1]).toString('utf8')); } catch { return { ok: false, error: 'invalid_key_format' }; }
56
+ // one key = one exact text: a second spelling of the same bytes (padding bits, + / instead of - _) is refused
57
+ if (b64u(unb64u(parts[1])) !== parts[1] || b64u(unb64u(parts[2])) !== parts[2]) return { ok: false, error: 'invalid_key_format' };
58
+ const good = (() => { try { return crypto.verify(null, Buffer.from(parts[0] + '.' + parts[1]), pub, unb64u(parts[2])); } catch { return false; } })();
59
+ if (!good) return { ok: false, error: 'invalid_signature' };
60
+ if (!PLANS[payload.plan] || payload.plan === 'trial') return { ok: false, error: 'unknown_plan' };
61
+ return { ok: true, payload };
62
+ }
63
+
64
+ /** Sign a key (vendor side only - needs the vendor PRIVATE key). */
65
+ function signKey(privateKey, payload) {
66
+ const body = 'BP1.' + b64u(JSON.stringify(payload));
67
+ return body + '.' + b64u(crypto.sign(null, Buffer.from(body), privateKey));
68
+ }
69
+
70
+ // BP_TRIAL_V4: server-backed trial; local files cannot reset its start date.
71
+ function trialStart() {
72
+ const now=Date.now(), st=readJson(FILE())||{};
73
+ const marker=MARKER(); let prev=Date.parse(st.trialStart||'');
74
+ try { const t=Date.parse(fs.readFileSync(marker,'utf8').trim()); if(Number.isFinite(t))prev=Math.min(Number.isFinite(prev)?prev:t,t); }catch{}
75
+ try {const t=Date.parse(fs.readFileSync(process.env.MGR_TRIAL_SECONDARY||path.join(os.homedir(),'.buildproof_trial_backup'),'utf8').trim());if(Number.isFinite(t))prev=Math.min(Number.isFinite(prev)?prev:t,t);}catch{}
76
+ if(!Number.isFinite(prev))prev=now;
77
+ const iso=new Date(prev).toISOString();
78
+ if(st.trialStart!==iso){fs.mkdirSync(DATA_DIR,{recursive:true});fs.writeFileSync(FILE(),JSON.stringify({...st,trialStart:iso},null,2));}
79
+ try{fs.writeFileSync(marker,iso)}catch{}
80
+ return prev;
81
+ }
82
+ function onlineTrial(){
83
+ if(global.__bpTrialCache && Date.now()-global.__bpTrialCacheAt<30000)return global.__bpTrialCache;
84
+ const cp=require('child_process');
85
+ const cfg=require('./config').load();
86
+ const base=process.env.MGR_TRIAL_SERVER||cfg.licenseServer;
87
+ if(!base)return null; // developer test installations without a configured server
88
+ const os=require('os');
89
+ let identity='';
90
+ if(process.platform==='win32'){
91
+ try{identity=cp.execFileSync('reg',['query','HKLM\\SOFTWARE\\Microsoft\\Cryptography','/v','MachineGuid'],{encoding:'utf8',timeout:1500}).match(/MachineGuid\s+REG_SZ\s+(\S+)/i)?.[1]||''}catch{}
92
+ }else {try{identity=fs.readFileSync('/etc/machine-id','utf8').trim()}catch{}}
93
+ if(!identity)identity=os.hostname()+'|'+Object.values(os.networkInterfaces()).flat().filter(x=>x&&!x.internal&&x.mac&&x.mac!=='00:00:00:00:00:00').map(x=>x.mac).sort().join('|');
94
+ const device=crypto.createHash('sha256').update('BuildProof-trial-v4:'+identity).digest('hex');
95
+ const url=new URL('/api/trial/start',base).href;
96
+ const childCode="const u=process.argv[1],d=process.argv[2],m=u.startsWith('https:')?require('https'):require('http');const r=m.request(u,{method:'POST',headers:{'content-type':'application/json'},timeout:3000},s=>{let b='';s.on('data',x=>b+=x);s.on('end',()=>{if(s.statusCode!==200)process.exit(4);try{const v=JSON.parse(b);if(!v.ok||!['trial','expired'].includes(v.status)||!Number.isInteger(v.daysLeft))process.exit(5);process.stdout.write(JSON.stringify(v))}catch{process.exit(6)}})});r.on('timeout',()=>r.destroy());r.on('error',()=>process.exit(7));r.end(JSON.stringify({device:d}))";
97
+ const r=cp.spawnSync(process.execPath,['-e',childCode,url,device],{encoding:'utf8',timeout:4500,windowsHide:true});
98
+ if(r.status!==0||r.error)return {status:'expired',daysLeft:0,reason:'trial_server_unavailable'};
99
+ try{const result=JSON.parse(r.stdout);global.__bpTrialCache=result;global.__bpTrialCacheAt=Date.now();return result}catch{return {status:'expired',daysLeft:0,reason:'trial_response_invalid'}}
100
+ }
101
+ function status() {
102
+ const now = Date.now();
103
+ const st = readJson(FILE()) || {};
104
+ if (st.key) {
105
+ const k = parseKey(st.key);
106
+ if (k.ok) {
107
+ const exp = Date.parse(k.payload.exp);
108
+ const active = !Number.isNaN(exp) && now <= exp + GRACE_DAYS * DAY;
109
+ const plan = PLANS[k.payload.plan];
110
+ return {
111
+ status: active ? 'active' : 'expired', plan: k.payload.plan, label: plan.label, email: k.payload.email || null, seats: k.payload.seats || 1,
112
+ expires: k.payload.exp, daysLeft: Math.max(0, Math.ceil((exp - now) / DAY)), inGrace: active && now > exp,
113
+ projects: plan.projects === Infinity ? null : plan.projects, features: active ? plan.features : [],
114
+ };
115
+ }
116
+ }
117
+ const online=onlineTrial();
118
+ if(online){
119
+ const left=online.daysLeft;
120
+ return { status:online.status, plan:'trial',label:'Trial',daysLeft:left,trialStarted:online.started||null,projects:PLANS.trial.projects,features:online.status==='trial'?PLANS.trial.features:[], ...(online.reason?{reason:online.reason}:{}) };
121
+ }
122
+ const start = trialStart();
123
+ const left = Math.max(0, Math.ceil((start + TRIAL_DAYS * DAY - now) / DAY));
124
+ return { status: left > 0 ? 'trial' : 'expired', plan: 'trial', label: 'Trial', daysLeft: left, trialStarted: new Date(start).toISOString(), projects: PLANS.trial.projects, features: left > 0 ? PLANS.trial.features : [] };
125
+ }
126
+
127
+ function currentKey() { const st = readJson(FILE()) || {}; return st.key || null; }
128
+
129
+ function has(feature) { return status().features.includes(feature); }
130
+
131
+ function activate(key) {
132
+ const k = parseKey(key);
133
+ if (!k.ok) return k;
134
+ if (Date.parse(k.payload.exp) + GRACE_DAYS * DAY < Date.now()) return { ok: false, error: 'key_expired' };
135
+ const st = readJson(FILE()) || {};
136
+ fs.mkdirSync(DATA_DIR, { recursive: true });
137
+ if (st.key && st.key !== key) fs.writeFileSync(FILE() + '.prev', JSON.stringify(st, null, 2)); // keep the previous key
138
+ fs.writeFileSync(FILE(), JSON.stringify({ ...st, key: String(key).trim(), activatedAt: new Date().toISOString() }, null, 2));
139
+ return { ok: true, license: status() };
140
+ }
141
+
142
+ /** Monthly plans: fetch the renewed key from the license server (near the end of the period, or when asked). */
143
+ async function renew(cfg, force) {
144
+ const key = currentKey();
145
+ if (!key || !cfg || !cfg.licenseServer) return { ok: false, error: 'nothing_to_renew' };
146
+ const k = parseKey(key);
147
+ if (!k.ok || !k.payload.subscription) return { ok: false, error: 'not_a_subscription' };
148
+ if (!force && Date.parse(k.payload.exp) - Date.now() > 7 * DAY) return { ok: true, renewed: false };
149
+ // the machine's signing-key fingerprint: the server renews only for machines registered to this license (seats)
150
+ // + a fresh signature with that key: the fingerprint alone is public (printed on every certificate)
151
+ let q = 'fp=';
152
+ try { const ks = require('./certs').keys(); const pr = require('./machine-proof').make('renew', k.payload.subscription, ks); q = `fp=${encodeURIComponent(ks.fingerprint)}&ts=${pr.ts}&spki=${encodeURIComponent(pr.spki)}&sig=${encodeURIComponent(pr.sig)}`; } catch { /* no key yet */ }
153
+ const r = await require('./ai').request(`${cfg.licenseServer.replace(/\/$/, '')}/api/license/${encodeURIComponent(k.payload.subscription)}?${q}`, null, 8000);
154
+ if (!r.ok || !r.json || !r.json.key || r.json.key === key) return { ok: true, renewed: false };
155
+ const n = parseKey(r.json.key);
156
+ if (!n.ok || n.payload.subscription !== k.payload.subscription || Date.parse(n.payload.exp) <= Date.parse(k.payload.exp)) return { ok: true, renewed: false };
157
+ const a = activate(r.json.key);
158
+ return a.ok ? { ok: true, renewed: true, license: a.license } : a;
159
+ }
160
+
161
+ function publicInfo() {
162
+ return { ...status(), plans: Object.fromEntries(Object.entries(PLANS).map(([k, v]) => [k, { label: v.label, price: v.price, projects: v.projects === Infinity ? null : v.projects, features: v.features }])), featureText: FEATURE_TEXT };
163
+ }
164
+
165
+ module.exports = { status, has, currentKey, activate, renew, parseKey, signKey, publicInfo, PLANS, F, TRIAL_DAYS };
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+ /**
3
+ * Machine proof for the license server.
4
+ * The signing-key fingerprint is public (it is printed on every certificate), so it is never enough on its own.
5
+ * Register / renew / countersign also send a fresh signature made with this machine's own signing key:
6
+ * sig = ed25519("BP-PROOF|<purpose>|<fingerprint>|<subject>|<ts>")
7
+ * Same format as server/license-server.js proofOk().
8
+ */
9
+ const crypto = require('crypto');
10
+
11
+ function make(purpose, subject, k) {
12
+ const keys = k || require('./certs').keys();
13
+ const ts = Date.now();
14
+ const sig = crypto.sign(null, Buffer.from(`BP-PROOF|${purpose}|${keys.fingerprint}|${subject}|${ts}`), keys.privateKey).toString('base64');
15
+ return { spki: keys.spkiB64, ts, sig };
16
+ }
17
+
18
+ /** The fingerprint that belongs to a public key (base64 DER spki). null when the key is not readable. */
19
+ function fingerprintOfSpki(spkiB64) {
20
+ try {
21
+ const der = Buffer.from(String(spkiB64 || ''), 'base64');
22
+ crypto.createPublicKey({ key: der, format: 'der', type: 'spki' });
23
+ return crypto.createHash('sha256').update(der).digest('hex').slice(0, 32).toUpperCase().match(/.{4}/g).join(' ');
24
+ } catch { return null; }
25
+ }
26
+
27
+ module.exports = { make, fingerprintOfSpki };
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+ /**
3
+ * One running task per project folder, also across processes.
4
+ * A lock left behind by a crashed process is reclaimed: its pid is gone, or it is older than STALE_MS.
5
+ */
6
+ const fs = require('fs'), path = require('path'), crypto = require('crypto');
7
+ const STALE_MS = 6 * 3600e3;
8
+ const dir = () => process.env.MGR_LOCK_DIR || path.join(require('os').tmpdir(), 'buildproof-locks');
9
+ const fileFor = (root) => path.join(dir(), crypto.createHash('sha256').update(path.resolve(root).toLowerCase()).digest('hex') + '.lock');
10
+ function alive(pid) { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } }
11
+ function acquire(root) {
12
+ fs.mkdirSync(dir(), { recursive: true });
13
+ const f = fileFor(root);
14
+ for (let attempt = 0; attempt < 2; attempt++) {
15
+ try {
16
+ const fd = fs.openSync(f, 'wx', 0o600);
17
+ fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, time: Date.now(), root: path.resolve(root) }));
18
+ fs.closeSync(fd);
19
+ let released = false;
20
+ return () => { if (released) return; released = true; try { const cur = JSON.parse(fs.readFileSync(f, 'utf8')); if (cur.pid === process.pid) fs.unlinkSync(f); } catch { /* already gone */ } };
21
+ } catch (e) {
22
+ if (e.code !== 'EEXIST') throw e;
23
+ let cur = null; try { cur = JSON.parse(fs.readFileSync(f, 'utf8')); } catch { /* unreadable = broken lock */ }
24
+ const stale = !cur || !Number.isInteger(cur.pid) || !alive(cur.pid) || Date.now() - (cur.time || 0) > STALE_MS;
25
+ if (!stale) throw Object.assign(new Error('PROJECT_LOCKED by pid ' + cur.pid), { code: 'PROJECT_LOCKED' });
26
+ try { fs.unlinkSync(f); } catch { /* raced */ }
27
+ }
28
+ }
29
+ throw Object.assign(new Error('PROJECT_LOCKED'), { code: 'PROJECT_LOCKED' });
30
+ }
31
+ module.exports = { acquire, fileFor, STALE_MS };
@@ -0,0 +1,180 @@
1
+ 'use strict';
2
+ /** Project registry + detection of type and verification commands. */
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const crypto = require('crypto');
6
+ const { spawnSync } = require('child_process');
7
+ const store = require('./store');
8
+
9
+ const VERIFY_SCRIPTS = ['typecheck', 'lint', 'build', 'test'];
10
+ const IS_WIN = process.platform === 'win32';
11
+ const PY_MARKERS = ['pyproject.toml', 'requirements.txt', 'setup.py', 'setup.cfg', 'pytest.ini', 'tox.ini', 'Pipfile'];
12
+
13
+ /** Syntax-check every .py file WITHOUT writing .pyc files (the project stays untouched). */
14
+ const PY_COMPILE = [
15
+ 'import sys, pathlib, re',
16
+ 'bad = 0; n = 0',
17
+ "skip = re.compile(r'(^|[\\\\/])(\\.venv|venv|env|\\.tox|node_modules|\\.git|build|dist|site-packages|__pycache__)([\\\\/]|$)')",
18
+ "for p in pathlib.Path('.').rglob('*.py'):",
19
+ ' if skip.search(str(p.parent)): continue',
20
+ ' n += 1',
21
+ ' try: compile(p.read_text(encoding="utf-8", errors="replace"), str(p), "exec")',
22
+ ' except SyntaxError as e:',
23
+ ' bad += 1; print(f"{p}:{e.lineno}: SyntaxError: {e.msg}")',
24
+ 'print(f"compiled {n} file(s), {bad} error(s)")',
25
+ 'sys.exit(1 if bad else 0)',
26
+ ].join('\n');
27
+
28
+ let pyCache = null;
29
+ /** Find a working Python 3 (Windows: python / py; others: python3 / python). Venv in the project wins. */
30
+ function findPython(root) {
31
+ for (const v of ['.venv', 'venv', 'env']) {
32
+ const exe = IS_WIN ? path.join(root, v, 'Scripts', 'python.exe') : path.join(root, v, 'bin', 'python');
33
+ if (fs.existsSync(exe)) return exe;
34
+ }
35
+ if (pyCache !== null) return pyCache;
36
+ for (const c of IS_WIN ? ['python', 'py', 'python3'] : ['python3', 'python']) {
37
+ try {
38
+ const r = spawnSync(c, ['--version'], { encoding: 'utf8', windowsHide: true, timeout: 8000 });
39
+ if (r.status === 0 && /Python 3/.test((r.stdout || '') + (r.stderr || ''))) { pyCache = c; return c; }
40
+ } catch { /* next */ }
41
+ }
42
+ pyCache = '';
43
+ return '';
44
+ }
45
+ function hasModule(py, mod) {
46
+ try { return spawnSync(py, ['-c', `import ${mod}`], { windowsHide: true, timeout: 15000 }).status === 0; } catch { return false; }
47
+ }
48
+ function hasExe(cmd, args = ['--version']) {
49
+ // Windows: mvn / gradle / composer / bundle are .cmd / .bat wrappers -> found through the shell
50
+ try { return spawnSync(cmd, args, { windowsHide: true, timeout: 30000, shell: IS_WIN && require('./runner').WRAPPERS.has(cmd) }).status === 0; } catch { return false; }
51
+ }
52
+ const exists = (root, f) => fs.existsSync(path.join(root, f));
53
+ const anyFile = (root, re) => { try { return fs.readdirSync(root).some((f) => re.test(f)); } catch { return false; } };
54
+ // a .NET test project: a project file that references a test framework
55
+ function testProject(root) { let hit = false, n = 0; (function rec(d) { if (hit || n > 3000) return; let es = []; try { es = fs.readdirSync(d, { withFileTypes: true }); } catch { return; } for (const e of es) { if (hit || ++n > 3000) return; if (e.isDirectory()) { if (!/^(node_modules|\.git|bin|obj|packages)$/.test(e.name)) rec(path.join(d, e.name)); } else if (/\.(cs|fs|vb)proj$/i.test(e.name) && /Microsoft\.NET\.Test\.Sdk|xunit|nunit|MSTest/i.test(readText(path.join(d, e.name)))) hit = true; } })(root); return hit; }
56
+ const tree = (root, re, max = 4000) => { let hit = false, n = 0; (function rec(d) { if (hit || n > max) return; let es = []; try { es = fs.readdirSync(d, { withFileTypes: true }); } catch { return; } for (const e of es) { if (hit || ++n > max) return; if (e.isDirectory()) { if (!/^(node_modules|\.git|vendor|target|bin|obj|build|\.gradle)$/.test(e.name)) rec(path.join(d, e.name)); } else if (re.test(e.name)) hit = true; } })(root); return hit; };
57
+
58
+ /**
59
+ * More languages. Each one: the real build and the real tests of its own toolchain, so a change is proven the
60
+ * same way the developer proves it. A missing toolchain = an honest note, never a pass.
61
+ */
62
+ function detectOther(root, info) {
63
+ const need = (name, ok) => { if (!ok) info.notes.push(`${name} is not installed on this computer - install it to verify this project.`); return ok; };
64
+ if (exists(root, 'go.mod')) {
65
+ info.type = 'go'; info.commands = {};
66
+ if (need('Go', hasExe('go', ['version']))) { info.commands.build = ['go', 'build', './...']; info.commands.lint = ['go', 'vet', './...']; info.commands.test = ['go', 'test', '-v', '-count=1', './...']; }
67
+ } else if (exists(root, 'Cargo.toml')) {
68
+ info.type = 'rust'; info.commands = {};
69
+ if (need('Rust (cargo)', hasExe('cargo'))) { info.commands.build = ['cargo', 'build', '--quiet']; info.commands.test = ['cargo', 'test']; }
70
+ } else if (exists(root, 'pom.xml')) {
71
+ info.type = 'java-maven'; info.commands = {};
72
+ const mvn = exists(root, IS_WIN ? 'mvnw.cmd' : 'mvnw') ? path.join(root, IS_WIN ? 'mvnw.cmd' : 'mvnw') : 'mvn';
73
+ if (need('Maven', mvn !== 'mvn' || hasExe('mvn', ['-v']))) { info.commands.build = [mvn, '-B', '-q', 'compile']; info.commands.test = [mvn, '-B', 'test']; }
74
+ } else if (exists(root, 'build.gradle') || exists(root, 'build.gradle.kts')) {
75
+ info.type = 'java-gradle'; info.commands = {};
76
+ const gw = exists(root, IS_WIN ? 'gradlew.bat' : 'gradlew') ? path.join(root, IS_WIN ? 'gradlew.bat' : 'gradlew') : 'gradle';
77
+ if (need('Gradle', gw !== 'gradle' || hasExe('gradle', ['-v']))) { info.commands.build = [gw, 'classes', '--console=plain', '-q']; info.commands.test = [gw, 'test', '--rerun', '--console=plain']; info.junitXml = 'build/test-results'; }
78
+ } else if (anyFile(root, /\.(sln|csproj|fsproj|vbproj)$/i)) {
79
+ info.type = 'dotnet'; info.commands = {};
80
+ if (need('.NET SDK', hasExe('dotnet', ['--version']))) { info.commands.build = ['dotnet', 'build', '--nologo', '--disable-build-servers']; if (testProject(root)) info.commands.test = ['dotnet', 'test', '--nologo', '--disable-build-servers']; else info.notes.push('No .NET test project (xunit / nunit / MSTest) found.'); }
81
+ } else if (exists(root, 'Gemfile') || anyFile(root, /\.gemspec$/) || (exists(root, 'Rakefile') && tree(root, /\.rb$/))) {
82
+ info.type = 'ruby'; info.commands = {};
83
+ if (need('Ruby', hasExe('ruby', ['-v']))) {
84
+ info.commands.build = ['ruby', '-e', 'bad = Dir.glob("**/*.rb").reject { |f| f =~ %r{^(vendor|tmp|node_modules)/} }.reject { |f| system("ruby", "-c", f, out: File::NULL, err: File::NULL) }; puts "syntax ok: #{bad.empty?}"; bad.each { |f| puts "SyntaxError in #{f}" }; exit(bad.empty? ? 0 : 1)'];
85
+ if (exists(root, 'spec') && /rspec/.test(readText(path.join(root, 'Gemfile')) + readText(path.join(root, 'Gemfile.lock')))) info.commands.test = exists(root, 'Gemfile.lock') ? ['bundle', 'exec', 'rspec'] : ['rspec'];
86
+ else if (exists(root, 'test')) info.commands.test = ['ruby', '-Ilib', '-Itest', '-e', 'Dir.glob("test/**/{*_test,test_*}.rb").sort.each { |f| require File.expand_path(f) }'];
87
+ }
88
+ } else if (exists(root, 'composer.json')) {
89
+ info.type = 'php'; info.commands = {};
90
+ if (need('PHP', hasExe('php', ['-v']))) {
91
+ info.commands.build = ['php', '-r', '$bad=0;$it=new RecursiveIteratorIterator(new RecursiveDirectoryIterator(".",FilesystemIterator::SKIP_DOTS));foreach($it as $f){$p=$f->getPathname();if(substr($p,-4)!==".php"||preg_match("#[/\\\\](vendor|node_modules)[/\\\\]#",$p))continue;exec(escapeshellarg(PHP_BINARY)." -l ".escapeshellarg($p)." 2>&1",$o,$c);if($c){$bad++;echo "Parse error in $p\n";}}echo "lint done, $bad error(s)\n";exit($bad?1:0);'];
92
+ const pu = exists(root, 'vendor/bin/phpunit') ? ['php', path.join('vendor', 'bin', 'phpunit')] : hasExe('phpunit') ? ['phpunit'] : null;
93
+ if (pu) info.commands.test = pu; else info.notes.push('PHPUnit not found (composer install, or phpunit on the PATH) - only the syntax check can run.');
94
+ }
95
+ } else return null;
96
+ info.verify = ['typecheck', 'lint', 'build', 'test'].filter((s) => info.commands[s]);
97
+ if (!info.commands.test) info.notes.push('No test command for this project - changes can be checked for syntax, but not proven.');
98
+ return info;
99
+ }
100
+ function readText(f) { try { return fs.readFileSync(f, 'utf8'); } catch { return ''; } }
101
+
102
+ /** Python project: proof steps = build (compile every file), lint (ruff), typecheck (mypy), test (pytest / unittest). */
103
+ function detectPython(root, info) {
104
+ info.type = 'python';
105
+ info.commands = {};
106
+ const py = findPython(root);
107
+ if (!py) { info.notes.push('Python 3 was not found on this computer. Install Python to verify this project.'); return info; }
108
+ info.python = py;
109
+ const pyproject = readText(path.join(root, 'pyproject.toml'));
110
+ info.commands.build = [py, '-c', PY_COMPILE];
111
+ if ((/\[tool\.ruff/.test(pyproject) || fs.existsSync(path.join(root, 'ruff.toml'))) && (hasModule(py, 'ruff') || hasExe('ruff'))) info.commands.lint = hasModule(py, 'ruff') ? [py, '-m', 'ruff', 'check', '.'] : ['ruff', 'check', '.'];
112
+ if ((/\[tool\.mypy/.test(pyproject) || fs.existsSync(path.join(root, 'mypy.ini'))) && hasModule(py, 'mypy')) info.commands.typecheck = [py, '-m', 'mypy', '.'];
113
+ const testDir = ['tests', 'test'].find((d) => fs.existsSync(path.join(root, d)));
114
+ if (hasModule(py, 'pytest')) info.commands.test = [py, '-m', 'pytest', '-q', '-rA'];
115
+ else info.commands.test = [py, '-m', 'unittest', 'discover', '-v', ...(testDir ? ['-s', testDir] : [])];
116
+ if (!hasModule(py, 'pytest')) info.notes.push('pytest is not installed - using unittest. Install pytest for full test results.');
117
+ info.verify = ['typecheck', 'lint', 'build', 'test'].filter((s) => info.commands[s]);
118
+ return info;
119
+ }
120
+
121
+ /** The exact command for one proof step. */
122
+ function commandFor(project, step) {
123
+ if (project.commands && project.commands[step]) { const [cmd, ...args] = project.commands[step]; return { cmd, args }; }
124
+ return { cmd: 'npm', args: ['run', step] };
125
+ }
126
+
127
+ function detect(root) {
128
+ const info = { type: 'unknown', verify: [], packageManager: null, hasNodeModules: false, needsInstall: false, notes: [] };
129
+ const pkgPath = path.join(root, 'package.json');
130
+ if (fs.existsSync(path.join(root, 'ProjectSettings')) && fs.existsSync(path.join(root, 'Assets'))) {
131
+ info.type = 'unity';
132
+ info.notes.push('Unity projects are planned for version 2 (build/verify through Unity).');
133
+ return info;
134
+ }
135
+ if (!fs.existsSync(pkgPath)) {
136
+ const other = detectOther(root, info);
137
+ if (other) return other;
138
+ if (PY_MARKERS.some((f) => fs.existsSync(path.join(root, f))) || fs.readdirSync(root).some((f) => /\.py$/.test(f)) || ['tests', 'test'].some((d) => { try { return fs.readdirSync(path.join(root, d)).some((f) => /^test_.*\.py$|_test\.py$/.test(f)); } catch { return false; } })) return detectPython(root, info);
139
+ info.notes.push('No supported project found - supported: Node / TypeScript, Python, Go, Rust, Java (Maven / Gradle), .NET, Ruby, PHP.');
140
+ return info;
141
+ }
142
+ let pkg = {};
143
+ try { pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); } catch (e) { info.notes.push(`package.json is invalid: ${e.message}`); return info; }
144
+ const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
145
+ info.type = deps.next ? 'next' : deps.react ? 'react' : deps.vite ? 'vite' : deps.express ? 'node-server' : 'node';
146
+ info.packageManager = fs.existsSync(path.join(root, 'pnpm-lock.yaml')) ? 'pnpm' : fs.existsSync(path.join(root, 'yarn.lock')) ? 'yarn' : 'npm';
147
+ info.hasNodeModules = fs.existsSync(path.join(root, 'node_modules'));
148
+ info.needsInstall = Object.keys(deps).length > 0 && !info.hasNodeModules;
149
+ const scripts = pkg.scripts || {};
150
+ for (const s of VERIFY_SCRIPTS) {
151
+ if (scripts[s] && !/no test specified|echo\s+["']?error/i.test(scripts[s])) info.verify.push(s);
152
+ }
153
+ if (!info.verify.length) info.notes.push('No build/test scripts - changes can be applied but not proven. Add a "test" or "build" script.');
154
+ if (info.needsInstall) info.notes.push('node_modules missing - dependencies must be installed (npm install) before verification.');
155
+ return info;
156
+ }
157
+
158
+ function add({ name, root }) {
159
+ const abs = path.resolve(String(root || '').trim());
160
+ if (!root || !fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) return { ok: false, error: 'folder_not_found', path: abs };
161
+ const existing = store.list('projects', (p) => path.resolve(p.root).toLowerCase() === abs.toLowerCase());
162
+ if (existing.length) return { ok: true, project: refresh(existing[0].id) };
163
+ const project = {
164
+ id: 'p_' + crypto.randomBytes(5).toString('hex'),
165
+ name: String(name || path.basename(abs)),
166
+ root: abs,
167
+ createdAt: new Date().toISOString(),
168
+ ...detect(abs),
169
+ };
170
+ store.insert('projects', project);
171
+ return { ok: true, project };
172
+ }
173
+
174
+ function refresh(id) {
175
+ const p = store.get('projects', id);
176
+ if (!p) return null;
177
+ return store.update('projects', id, detect(p.root));
178
+ }
179
+
180
+ module.exports = { detect, add, refresh, commandFor, findPython, VERIFY_SCRIPTS };
@@ -0,0 +1,11 @@
1
+ 'use strict';
2
+ function score(t){
3
+ if(!t||!t.lastCheck)return {score:0,status:'unverified'};
4
+ const c=t.lastCheck;
5
+ if(!c.ok)return {score:0,status:'not_proven'};
6
+ let n=60;
7
+ if(t.integrity?.clean)n+=20;
8
+ if(t.revertCheck?.verdict==='covered')n+=20;
9
+ return {score:n,status:'proven'};
10
+ }
11
+ module.exports={score};
package/core/runner.js ADDED
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+ /** Run an allow-listed command in a project. Captures output, enforces timeout. */
3
+ const { spawn } = require('child_process');
4
+
5
+ const IS_WIN = process.platform === 'win32';
6
+ // Windows: these are .cmd / .bat wrappers - started through the shell (fixed arguments only, never user text)
7
+ const WRAPPERS = new Set(['npm', 'npx', 'mvn', 'gradle', 'composer', 'bundle', 'rspec', 'rake', 'phpunit']);
8
+ const MAX_OUT = 200000;
9
+
10
+ function run(cmd, args, { cwd, timeoutMs = 300000, env } = {}) {
11
+ return new Promise((resolve) => {
12
+ const started = Date.now();
13
+ let out = '';
14
+ let done = false;
15
+ const base = require('path').basename(String(cmd)).replace(/\.(cmd|bat)$/i, '');
16
+ const wrapper = IS_WIN && (WRAPPERS.has(base) || /\.(cmd|bat)$/i.test(cmd));
17
+ let exe = IS_WIN && (cmd === 'npm' || cmd === 'npx') ? `${cmd}.cmd` : cmd;
18
+ if (wrapper && /\s/.test(exe)) exe = `"${exe}"`; // a wrapper inside a folder with spaces (gradlew.bat in C:\My Projects)
19
+ let child;
20
+ try {
21
+ child = spawn(exe, args, { cwd, env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1', PYTHON_COLORS: '0', MSBUILDDISABLENODEREUSE: '1', DOTNET_CLI_TELEMETRY_OPTOUT: '1', DOTNET_NOLOGO: '1', ...env }, windowsHide: true, shell: wrapper });
22
+ } catch (e) {
23
+ resolve({ ok: false, code: -1, output: String(e.message), ms: 0, timedOut: false });
24
+ return;
25
+ }
26
+ const add = (d) => { if (out.length < MAX_OUT) out += String(d); };
27
+ child.stdout.on('data', add);
28
+ child.stderr.on('data', add);
29
+ const timer = setTimeout(() => {
30
+ if (done) return;
31
+ try {
32
+ if (IS_WIN) spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true });
33
+ else child.kill('SIGKILL');
34
+ } catch { /* ignore */ }
35
+ }, timeoutMs);
36
+ child.on('error', (e) => { add(`\n[spawn error] ${e.message}`); });
37
+ child.on('close', (code) => {
38
+ done = true;
39
+ clearTimeout(timer);
40
+ const ms = Date.now() - started;
41
+ resolve({ ok: code === 0, code, output: out, ms, timedOut: ms >= timeoutMs });
42
+ });
43
+ });
44
+ }
45
+
46
+ module.exports = { run, WRAPPERS };
package/core/scope.js ADDED
@@ -0,0 +1,153 @@
1
+ 'use strict';
2
+ /** Pick the files a task is allowed to touch. Deterministic, explainable. Tests are protected by default. */
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ const TEXT_EXT = /\.(js|jsx|ts|tsx|mjs|cjs|json|css|scss|html|vue|svelte|md|txt|yml|yaml|py|toml|cfg|ini)$/i;
7
+ const LOCK = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|uv\.lock|Pipfile\.lock)$/i;
8
+ const CONFIG_LIKE = /(^|\/)(package\.json|tsconfig[^/]*\.json|README[^/]*|[^/]+\.md|pyproject\.toml|setup\.(py|cfg)|requirements[^/]*\.txt|conftest\.py)$/i;
9
+ const TEST = /(^|\/)(__tests__|tests?|spec)\/|\.(test|spec)\.[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.py$|(^|\/)conftest\.py$/i;
10
+ const STOP = new Set(['this', 'that', 'with', 'from', 'when', 'into', 'should', 'please', 'make', 'file', 'code', 'function', 'add', 'fix', 'the', 'and', 'return', 'true', 'false', 'null', 'const', 'error', 'test', 'tests', 'page', 'button']);
11
+
12
+ function isTest(rel) { return TEST.test(rel); }
13
+
14
+ function explicitMentions(text, files) {
15
+ const t = String(text || '').replace(/\\/g, '/').toLowerCase();
16
+ return files.filter((f) => {
17
+ const low = f.toLowerCase();
18
+ const base = path.basename(low);
19
+ return t.includes(low) || (base.length > 4 && new RegExp(`(^|[^\\w.])${base.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}($|[^\\w])`).test(t));
20
+ });
21
+ }
22
+
23
+ function errorPaths(errText, files) {
24
+ const out = new Set();
25
+ const re = /([\w@./\\:-]+\.(?:js|jsx|ts|tsx|mjs|cjs|json|css|scss|html|vue|svelte|py))(?::\d+|"?, line \d+)?/g;
26
+ let m;
27
+ while ((m = re.exec(String(errText || '')))) {
28
+ const p = m[1].replace(/\\/g, '/').replace(/^\.\//, '');
29
+ for (const f of files) if (p.endsWith('/' + f) || p === f || f.endsWith('/' + p) || p.endsWith(f)) out.add(f);
30
+ }
31
+ return [...out].filter((f) => !f.includes('node_modules/'));
32
+ }
33
+
34
+ /** Local modules imported by a file (require / import from), resolved to project files. */
35
+ function localImports(root, rel, files) {
36
+ let src = '';
37
+ try { src = fs.readFileSync(path.join(root, rel), 'utf8'); } catch { return []; }
38
+ const out = [];
39
+ const re = /(?:require\(\s*|from\s+|import\s+)['"](\.{1,2}\/[^'"]+)['"]/g;
40
+ let m;
41
+ while ((m = re.exec(src))) {
42
+ const base = path.posix.normalize(path.posix.join(path.posix.dirname(rel), m[1]));
43
+ const cands = [base, `${base}.js`, `${base}.ts`, `${base}.tsx`, `${base}.jsx`, `${base}.mjs`, `${base}.cjs`, `${base}/index.js`, `${base}/index.ts`];
44
+ const hit = cands.find((c) => files.includes(c));
45
+ if (hit) out.push(hit);
46
+ }
47
+ if (/\.py$/.test(rel)) {
48
+ const py = /^\s*(?:from\s+(\.*[\w.]*)\s+import\s+([\w, ]+)|import\s+([\w.]+))/gm;
49
+ while ((m = py.exec(src))) {
50
+ const mod = m[1] != null ? m[1] : m[3];
51
+ const dots = (mod.match(/^\.+/) || [''])[0].length;
52
+ const parts = mod.slice(dots).split('.').filter(Boolean);
53
+ const names = m[2] ? m[2].split(',').map((x) => x.trim()).filter(Boolean) : [];
54
+ let bases = [];
55
+ if (dots) { let d = path.posix.dirname(rel); for (let i = 1; i < dots; i++) d = path.posix.dirname(d); bases = [d === '.' ? '' : d]; }
56
+ else bases = ['', 'src', 'app', 'lib'];
57
+ for (const b of bases) {
58
+ const stem = [b, ...parts].filter(Boolean).join('/');
59
+ const cands = [`${stem}.py`, `${stem}/__init__.py`, ...names.map((n) => `${stem ? stem + '/' : ''}${n}.py`)];
60
+ for (const c of cands) if (files.includes(c) && !out.includes(c)) out.push(c);
61
+ }
62
+ }
63
+ }
64
+ return out;
65
+ }
66
+
67
+ function keywordHits(root, text, files, maxBytes) {
68
+ const words = [...new Set((String(text || '').match(/[A-Za-z_][A-Za-z0-9_]{3,}/g) || []).map((w) => w.toLowerCase()))].filter((w) => !STOP.has(w));
69
+ if (!words.length) return [];
70
+ const scored = [];
71
+ for (const f of files) {
72
+ if (!TEXT_EXT.test(f) || LOCK.test(f)) continue;
73
+ let content = '';
74
+ try {
75
+ const abs = path.join(root, f);
76
+ if (fs.statSync(abs).size > maxBytes) continue;
77
+ content = fs.readFileSync(abs, 'utf8').toLowerCase();
78
+ } catch { continue; }
79
+ let score = 0;
80
+ for (const w of words) {
81
+ if (f.toLowerCase().includes(w)) score += 5;
82
+ const hits = content.split(w).length - 1;
83
+ score += Math.min(hits, 10);
84
+ }
85
+ if (score > 0) scored.push({ f, score });
86
+ }
87
+ return scored.sort((a, b) => b.score - a.score).map((s) => s.f);
88
+ }
89
+
90
+ /** Words of the task, with a short stem so "payments" matches "payment". */
91
+ function taskStems(text) {
92
+ return [...new Set((String(text || '').toLowerCase().match(/[a-z_][a-z0-9_]{3,}/g) || []).filter((w) => !STOP.has(w)))]
93
+ .map((w) => w.slice(0, Math.max(4, w.length - 2)));
94
+ }
95
+ function relevance(root, rel, stems) {
96
+ let src = '';
97
+ try { src = fs.readFileSync(path.join(root, rel), 'utf8').toLowerCase(); } catch { return 0; }
98
+ const name = rel.toLowerCase();
99
+ let score = 0;
100
+ for (const s of stems) { if (name.includes(s)) score += 5; if (src.includes(s)) score += 2; }
101
+ return score;
102
+ }
103
+
104
+ /**
105
+ * Focused scope: the AI gets only the few files that matter (a big scope makes small models give up).
106
+ * 1. files named in the task -> only those
107
+ * 2. else the failing test that best matches the task words -> the source files it imports (max 3)
108
+ * 3. else imports of every failing test (max 3), then keyword search
109
+ * @returns {{files: string[], reasons: Record<string,string>, protectedTests: string[], targetTests: string[]}}
110
+ */
111
+ function propose({ root, text, errText, files, max = 8, maxBytes = 60000 }) {
112
+ const reasons = {};
113
+ const picked = [];
114
+ const cap = Math.min(max, 3);
115
+ const add = (f, why, limit = cap) => {
116
+ if (picked.length >= limit || picked.includes(f) || LOCK.test(f) || isTest(f)) return;
117
+ picked.push(f); reasons[f] = why;
118
+ };
119
+ const failing = errorPaths(errText, files).filter((f) => isTest(f));
120
+ const importsOf = (t) => localImports(root, t, files).filter((x) => !isTest(x));
121
+ const mentioned = explicitMentions(text, files).filter((f) => !isTest(f));
122
+ const stems = taskStems(text);
123
+ let targets = [];
124
+
125
+ if (mentioned.length) {
126
+ for (const f of mentioned) add(f, 'named in the task', max);
127
+ targets = failing.filter((t) => importsOf(t).some((x) => mentioned.includes(x)));
128
+ } else if (failing.length) {
129
+ const ranked = failing.map((t) => ({ t, score: relevance(root, t, stems) + importsOf(t).reduce((n, x) => n + relevance(root, x, stems), 0) / 2 }))
130
+ .sort((a, b) => b.score - a.score);
131
+ if (ranked[0].score > 0) {
132
+ targets = ranked.filter((r) => r.score === ranked[0].score).slice(0, 2).map((r) => r.t);
133
+ const cand = [...new Set(targets.flatMap(importsOf))].map((f) => ({ f, score: relevance(root, f, stems) })).sort((a, b) => b.score - a.score);
134
+ for (const c of cand) add(c.f, `used by the failing test ${targets.find((t) => importsOf(t).includes(c.f))} that matches the task`);
135
+ } else {
136
+ targets = failing.slice();
137
+ for (const t of failing) for (const imp of importsOf(t)) add(imp, `used by the failing test ${t}`);
138
+ }
139
+ }
140
+ if (!picked.length) {
141
+ for (const f of errorPaths(errText, files)) add(f, 'appears in the error output');
142
+ }
143
+ if (!picked.length) {
144
+ for (const f of keywordHits(root, text, files, maxBytes)) {
145
+ if (CONFIG_LIKE.test(f)) continue;
146
+ add(f, 'matches words in the task');
147
+ }
148
+ }
149
+ const protectedTests = (targets.length ? targets : failing).slice(0, 4);
150
+ return { files: picked, reasons, protectedTests, targetTests: targets };
151
+ }
152
+
153
+ module.exports = { propose, isTest, explicitMentions, errorPaths, localImports };