buildproof 3.12.1 → 3.12.3

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/bin/buildproof.js CHANGED
@@ -33,7 +33,8 @@ const ROOT = path.resolve(__dirname, '..');
33
33
  const config = require('../core/config');
34
34
 
35
35
  const args = process.argv.slice(2);
36
- const cmd = args[0] || 'help';
36
+ const cmd = ['-h', '--help'].includes(args[0]) ? 'help' : (args[0] || 'help');
37
+ if (['-v', '--version', 'version'].includes(cmd)) { console.log(require('../package.json').version); process.exit(0); }
37
38
  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; };
38
39
  const hook = flag('hook');
39
40
  const force = !!flag('force');
@@ -52,14 +53,15 @@ function readStdin() {
52
53
  function parse(s) { try { return JSON.parse(s); } catch { return {}; } }
53
54
  }
54
55
 
55
- function api(method, p, body) {
56
+ function api(method, p, body, timeoutMs = 30 * 60 * 1000) {
56
57
  const c = config.load();
57
58
  return new Promise((resolve) => {
58
59
  const data = body ? JSON.stringify(body) : null;
59
- 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) => {
60
+ 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: timeoutMs }, (res) => {
60
61
  let raw = ''; res.on('data', (d) => { raw += d; }); res.on('end', () => { try { resolve(JSON.parse(raw)); } catch { resolve({ ok: false, error: 'bad_response' }); } });
61
62
  });
62
- req.on('error', () => resolve({ ok: false, error: 'service_not_running', down: true }));
63
+ req.on('timeout', () => req.destroy(new Error('timeout')));
64
+ req.on('error', (e) => resolve(e && e.message === 'timeout' ? { ok: false, error: 'no_answer' } : { ok: false, error: 'service_not_running', down: true }));
63
65
  if (data) req.write(data);
64
66
  req.end();
65
67
  });
@@ -205,26 +207,37 @@ async function main() {
205
207
  const r = await require('../core/bug-hunter/engine').repro(path.resolve(positional[1] || process.cwd()), f);
206
208
  out(`${r.reproduced ? 'REPRODUCED' : 'NOT_REPRODUCED'} ${f.oracle} ${f.file} ${f.export}(${f.inputPreview}) -> ${r.outcome}`, r.reproduced ? 0 : 1);
207
209
  }
210
+ if (['license', 'activate', 'status', 'open'].includes(cmd)) { // these need the local service: start it if it is not running
211
+ const sv = await require('../core/service').ensure({ autostart: false });
212
+ if (!sv.ok) out(sv.how === 'port_busy' ? `DOWN port ${sv.port} is used by another program, not BuildProof - pick a free port: set MGR_PORT=38711` : `DOWN BuildProof could not start on port ${sv.port} (if another program uses it, pick a free port: set MGR_PORT=38711)`, 1);
213
+ }
208
214
  if (cmd === 'license' || cmd === 'activate') {
209
215
  if (cmd === 'activate') {
210
216
  let key = positional[0] || '';
211
217
  if (!key) { // no key typed: take it from the clipboard (copied on the thank-you page)
212
218
  const { spawnSync } = require('child_process');
213
- 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' });
214
- key = ((c.stdout || '').match(/BP1\.[\w-]+\.[\w-]+/) || [''])[0];
215
- if (!key) out('ACTIVATE_FAIL no key - copy it from the thank-you page, or: buildproof activate <key>', 1);
219
+ const tries = process.platform === 'win32' ? [['powershell', ['-NoProfile', '-Command', 'Get-Clipboard']]] : process.platform === 'darwin' ? [['pbpaste', []]] : [['wl-paste', ['-n']], ['xclip', ['-o', '-selection', 'clipboard']], ['xsel', ['-b', '-o']]];
220
+ let readable = false;
221
+ for (const [bin, a] of tries) {
222
+ const c = spawnSync(bin, a, { encoding: 'utf8', windowsHide: true });
223
+ if (c.error || c.status !== 0) continue;
224
+ readable = true;
225
+ key = ((c.stdout || '').match(/BP1\.[\w-]+\.[\w-]+/) || [''])[0];
226
+ if (key) break;
227
+ }
228
+ if (!key) out(readable ? 'ACTIVATE_FAIL no key in the clipboard - copy it from the thank-you page, or: buildproof activate <key>' : 'ACTIVATE_FAIL cannot read the clipboard here - run: buildproof activate <key>', 1);
216
229
  }
217
230
  const r = await api('POST', '/api/license', { key });
218
231
  out(r.ok ? `ACTIVATED ${r.license.label} until ${String(r.license.expires).slice(0, 10)}` : `ACTIVATE_FAIL ${r.error}`, r.ok ? 0 : 1);
219
232
  }
220
- const r = await api('GET', '/api/license');
221
- if (!r.ok) out(`DOWN ${r.error}`, 1);
233
+ const r = await api('GET', '/api/license', null, 15000);
234
+ if (!r.ok || !r.label) out(`DOWN ${r.error || 'unexpected answer on port ' + config.load().port}`, 1);
222
235
  out(`LICENSE ${r.label} ${r.status}${r.daysLeft != null ? ' days_left=' + r.daysLeft : ''}${r.projects ? ' projects_max=' + r.projects : ''}`, r.status === 'expired' ? 1 : 0);
223
236
  }
224
237
  if (cmd === 'init') {
225
238
  const service = require('../core/service');
226
239
  const sv = await service.ensure({ autostart: !process.env.MGR_NO_AUTOSTART });
227
- if (!sv.ok) out(`INIT_FAIL BuildProof could not start on port ${sv.port}`, 1);
240
+ if (!sv.ok) out(`INIT_FAIL BuildProof could not start on port ${sv.port} (if another program uses it, pick a free port: set MGR_PORT=38711)`, 1);
228
241
  const dir = path.resolve(positional[0] || process.cwd());
229
242
  const pr = await api('POST', '/api/projects', { root: dir });
230
243
  if (!pr.ok) out(`INIT_FAIL ${pr.error}${pr.limit ? ' (limit ' + pr.limit + ' projects in this plan)' : ''}`, 1);
@@ -245,10 +258,10 @@ async function main() {
245
258
  if (!process.env.MGR_NO_AUTOSTART && !process.env.MGR_NO_OPEN) openUrl(`http://127.0.0.1:${sv.port}/connect`);
246
259
  out(`OPEN http://127.0.0.1:${sv.port}/connect (BuildProof on this computer + add your phone)`, 0);
247
260
  }
248
- if (cmd === 'try') { // 30-second demo on a throw-away sample project, never on your code
261
+ if (cmd === 'try') { // 30-second demo on a throw-away sample project, never on your code (installs nothing that starts at login)
249
262
  const service = require('../core/service');
250
- const sv = await service.ensure({ autostart: !process.env.MGR_NO_AUTOSTART });
251
- if (!sv.ok) out(`TRY_FAIL BuildProof could not start on port ${sv.port}`, 1);
263
+ const sv = await service.ensure({ autostart: false });
264
+ if (!sv.ok) out(`TRY_FAIL BuildProof could not start on port ${sv.port} (if another program uses it, pick a free port: set MGR_PORT=38711)`, 1);
252
265
  const r = await require('../core/try-demo').run({ api, sleep, say: (t) => console.log(t) });
253
266
  if (!r.ok) out(`TRY_FAIL ${r.error}${r.error === 'license_required' ? ' (start the free trial: buildproof init)' : ''}${r.limit ? ' (limit ' + r.limit + ' projects in this plan)' : ''}`, 1);
254
267
  const good = !r.round1.proven && r.round2.proven;
@@ -258,8 +271,9 @@ async function main() {
258
271
  }
259
272
  if (cmd === 'open') { const u = `http://127.0.0.1:${config.load().port || 38700}/connect`; openUrl(u); out('OPEN ' + u, 0); }
260
273
  if (cmd === 'status') {
261
- const r = await api('GET', '/api/status');
262
- 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);
274
+ const r = await api('GET', '/api/status', null, 15000);
275
+ if (r.ok && typeof r.version !== 'string') out(`DOWN unexpected answer on port ${config.load().port}`, 1);
276
+ out(r.ok ? `BUILDPROOF v${r.version} AI=${r.ai && r.ai.ok ? 'OK' : 'DOWN'} fixes=${r.fixes} key=${r.fingerprint}` : `DOWN ${r.error}`, r.ok ? 0 : 1);
263
277
  }
264
278
  if (!['start', 'check', 'accept', 'rollback', 'connect', 'try'].includes(cmd)) {
265
279
  out(fs.readFileSync(__filename, 'utf8').split('\n').slice(3, 22).map((l) => l.replace(/^ \* ?/, '')).join('\n'), cmd === 'help' ? 0 : 1);
@@ -52,8 +52,20 @@ function localLlm(cfg, env = process.env) {
52
52
  };
53
53
  }
54
54
 
55
+ /** Is the customer's own model reachable (and pulled)? Checked before any code is sent. */
56
+ async function localReady(cfg, env = process.env) {
57
+ const endpoint = (env.BUILDPROOF_AI_URL || (cfg.ollama && cfg.ollama.endpoint) || 'http://127.0.0.1:11434').replace(/\/$/, '');
58
+ const model = env.BUILDPROOF_AI_MODEL || (cfg.ollama && cfg.ollama.model) || 'qwen3-coder:30b';
59
+ const r = await request('GET', endpoint + '/api/tags', {}, null, 3000);
60
+ if (r.code !== 200 || !r.j) return { ok: false, why: `no local AI model answers at ${endpoint} - install Ollama (ollama.com) and run: ollama pull ${model}, or use --cloud` };
61
+ const names = (Array.isArray(r.j.models) ? r.j.models : []).map((m) => (m && (m.name || m.model)) || '');
62
+ if (!names.some((n) => n === model || n === model + ':latest' || n.split(':')[0] === model)) return { ok: false, why: `the model ${model} is not pulled - run: ollama pull ${model}, or use --cloud` };
63
+ return { ok: true };
64
+ }
65
+
55
66
  async function run({ root, base, cloud, intent, cfg, license, server, llm, log = () => {}, pollMs = 2000, maxMs = 40 * 60000 }) {
56
67
  const headers = authHeaders(license);
68
+ if (!cloud && !llm) { const lr = await localReady(cfg || {}); if (!lr.ok) return { code: 2, text: 'CANNOT_HUNT ' + lr.why }; }
57
69
  let a; try { a = archives(root, base); } catch (e) { return { code: 2, text: 'CANNOT_HUNT git: ' + String(e.message).split('\n')[0] }; }
58
70
  const start = await request('POST', server + '/api/hunt', headers, { before: a.before, after: a.after, mode: cloud ? 'cloud' : 'local', intent }, 300000);
59
71
  if (start.code !== 200 || !start.j || !start.j.ok) {
@@ -63,6 +75,7 @@ async function run({ root, base, cloud, intent, cfg, license, server, llm, log =
63
75
  }
64
76
  const id = start.j.id;
65
77
  const ask = llm || localLlm(cfg || {});
78
+ let unanswered = 0;
66
79
  log(`HUNT_STARTED ${id} mode=${start.j.mode}`);
67
80
  const t0 = Date.now();
68
81
  for (;;) {
@@ -71,7 +84,8 @@ async function run({ root, base, cloud, intent, cfg, license, server, llm, log =
71
84
  if (st.code !== 200 || !st.j) { await sleep(pollMs); continue; }
72
85
  for (const p of st.j.prompts || []) { // the server's AI questions, answered by the local model
73
86
  const text = await ask(p.prompt);
74
- await request('POST', `${server}/api/hunt/${id}/answer`, headers, { id: p.id, text }, 60000);
87
+ const sent = await request('POST', `${server}/api/hunt/${id}/answer`, headers, { id: p.id, text }, 60000);
88
+ if (!String(text || '').trim() || sent.code !== 200) unanswered += 1;
75
89
  }
76
90
  if (st.j.status === 'done' || st.j.status === 'error') {
77
91
  const dir = path.join(root, '.buildproof'); fs.mkdirSync(dir, { recursive: true });
@@ -79,6 +93,7 @@ async function run({ root, base, cloud, intent, cfg, license, server, llm, log =
79
93
  fs.writeFileSync(file, JSON.stringify({ report: st.j.report, certificate: st.j.certificate, signature: st.j.signature, algo: st.j.algo }, null, 2));
80
94
  if (st.j.status === 'error') return { code: 2, text: `CANNOT_HUNT ${(st.j.report && st.j.report.error) || 'hunter error'}`, file };
81
95
  const proven = (st.j.report.findings || []).filter((f) => f.proven);
96
+ if (!proven.length && unanswered) return { code: 2, text: `CANNOT_HUNT the AI model did not answer ${unanswered} question(s), so "no bugs" would not be honest - check your local model (ollama), or run with --cloud`, file };
82
97
  const lines = proven.map((f) => ` - ${f.oracle} ${f.file}${f.line ? ':' + f.line : ''} ${f.why || ''}`);
83
98
  return { code: proven.length ? 1 : 0, text: `${proven.length ? 'BUGS_PROVEN ' + proven.length : 'NO_PROVEN_BUGS'} files=${(st.j.report.files || []).length} report=${file}${lines.length ? '\n' + lines.join('\n') : ''}`, file, report: st.j.report };
84
99
  }
@@ -93,11 +108,11 @@ async function credits({ license, server, buy, open }) {
93
108
  const r = await request('POST', server + '/api/credits/order', headers, { pack: String(buy) });
94
109
  if (r.code !== 200 || !r.j || !r.j.ok) return { code: 2, text: 'CANNOT_BUY ' + ((r.j && r.j.error) || 'server_unavailable') };
95
110
  open(r.j.approve);
96
- return { code: 0, text: `PAY ${r.j.checks} cloud checks for $${r.j.usd} in the PayPal page that opened: ${r.j.approve}` };
111
+ return { code: 0, text: `PAY ${r.j.checks} cloud checks for $${r.j.usd} in the checkout page that opened: ${r.j.approve}` };
97
112
  }
98
113
  const r = await request('GET', server + '/api/credits', headers);
99
114
  if (r.code !== 200 || !r.j) return { code: 2, text: 'CANNOT_READ ' + ((r.j && r.j.error) || 'server_unavailable') };
100
115
  return { code: 0, text: `CLOUD_CHECKS ${r.j.cloudChecks} (buy more: buildproof credits --buy 20)` };
101
116
  }
102
117
 
103
- module.exports = { run, credits, archives, authHeaders, localLlm };
118
+ module.exports = { run, credits, archives, authHeaders, localLlm, localReady };
package/core/license.js CHANGED
@@ -89,18 +89,40 @@ function deviceId(){
89
89
  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('|');
90
90
  return crypto.createHash('sha256').update('BuildProof-trial-v4:'+identity).digest('hex');
91
91
  }
92
+ const OFFLINE_FILE = () => path.join(DATA_DIR, 'trial-offline.json');
93
+ /** Remember the server's trial start locally, so going offline later can never give more days than the server allows. */
94
+ function recordServerStart(online){
95
+ try{
96
+ let t=Date.parse(online.started||'');
97
+ if(!Number.isFinite(t))t=Date.now()-(TRIAL_DAYS-Math.max(0,online.daysLeft))*DAY-(online.status==='expired'?DAY:0);
98
+ const st=readJson(FILE())||{}; const prev=Date.parse(st.trialStart||'');
99
+ if(Number.isFinite(prev)&&prev<=t)return;
100
+ const iso=new Date(t).toISOString();
101
+ fs.mkdirSync(DATA_DIR,{recursive:true}); fs.writeFileSync(FILE(),JSON.stringify({...st,trialStart:iso},null,2));
102
+ try{fs.writeFileSync(MARKER(),iso)}catch{}
103
+ }catch{}
104
+ }
92
105
  function onlineTrial(){
93
106
  if(global.__bpTrialCache && Date.now()-global.__bpTrialCacheAt<30000)return global.__bpTrialCache;
94
107
  const cp=require('child_process');
95
108
  const cfg=require('./config').load();
96
109
  const base=process.env.MGR_TRIAL_SERVER||cfg.licenseServer;
97
110
  if(!base)return null; // developer test installations without a configured server
111
+ // the server did not answer recently: do not wait for it again for 10 minutes (firewalls, proxies, no internet)
112
+ try{const o=JSON.parse(fs.readFileSync(OFFLINE_FILE(),'utf8'));if(o.base===base&&Date.now()<o.until&&o.until<=Date.now()+10*60*1000)return null;}catch{}
98
113
  const device=deviceId();
99
114
  const url=new URL('/api/trial/start',base).href;
100
- 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}))";
101
- const r=cp.spawnSync(process.execPath,['-e',childCode,url,device],{encoding:'utf8',timeout:4500,windowsHide:true});
102
- if(r.status!==0||r.error)return null; // server unreachable: use the local trial clock, never lock a user out because of the network
103
- try{const result=JSON.parse(r.stdout);global.__bpTrialCache=result;global.__bpTrialCacheAt=Date.now();return result}catch{return null}
115
+ 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:2500},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}))";
116
+ const r=cp.spawnSync(process.execPath,['-e',childCode,url,device],{encoding:'utf8',timeout:3500,windowsHide:true});
117
+ let result=null;
118
+ if(r.status===0&&!r.error){try{result=JSON.parse(r.stdout)}catch{result=null}}
119
+ if(!result){ // server unreachable: use the local trial clock, never lock a user out because of the network
120
+ try{fs.mkdirSync(DATA_DIR,{recursive:true});fs.writeFileSync(OFFLINE_FILE(),JSON.stringify({base,until:Date.now()+10*60*1000}))}catch{}
121
+ return null;
122
+ }
123
+ try{fs.unlinkSync(OFFLINE_FILE())}catch{}
124
+ recordServerStart(result);
125
+ global.__bpTrialCache=result;global.__bpTrialCacheAt=Date.now();return result;
104
126
  }
105
127
  function status() {
106
128
  const now = Date.now();
@@ -124,7 +146,7 @@ function status() {
124
146
  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}:{}) };
125
147
  }
126
148
  const start = trialStart();
127
- const left = Math.max(0, Math.ceil((start + TRIAL_DAYS * DAY - now) / DAY));
149
+ const left = Math.max(0, Math.ceil((start + TRIAL_DAYS * DAY - Math.max(now, start)) / DAY));
128
150
  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 : [] };
129
151
  }
130
152
 
package/core/procs.js ADDED
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+ /** Who is that process? Used before BuildProof ever stops one: only its own guard / server may be stopped. */
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { execSync } = require('child_process');
6
+ const ROOT = path.resolve(__dirname, '..');
7
+ const IS_WIN = process.platform === 'win32';
8
+ const cache = new Map(); // pid -> { at, cmd }
9
+
10
+ /** Command line of a process, or null when it cannot be read (cached 5 minutes per pid). */
11
+ function cmdLine(pid, fresh) {
12
+ pid = Number(pid);
13
+ if (!Number.isInteger(pid) || pid <= 0) return null;
14
+ const hit = cache.get(pid);
15
+ if (!fresh && hit && Date.now() - hit.at < 5 * 60 * 1000) return hit.cmd;
16
+ let cmd = null;
17
+ try {
18
+ if (process.platform === 'linux') cmd = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').join(' ').trim() || null;
19
+ else if (IS_WIN) cmd = execSync(`powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CommandLine"`, { encoding: 'utf8', windowsHide: true, timeout: 8000 }).trim() || null;
20
+ else cmd = execSync(`ps -o command= -p ${pid}`, { encoding: 'utf8', timeout: 3000 }).trim() || null;
21
+ } catch { cmd = null; }
22
+ cache.set(pid, { at: Date.now(), cmd });
23
+ return cmd;
24
+ }
25
+
26
+ /** true = a BuildProof process of this kind ('guard' | 'server'), false = something else, null = unknown. */
27
+ /** fresh = re-read now (always used right before stopping a process). */
28
+ function isOurs(pid, kind, fresh) {
29
+ const c = cmdLine(pid, fresh);
30
+ if (c == null) return null;
31
+ const n = c.replace(/\\/g, '/');
32
+ const script = kind === 'guard' ? /scripts\/guard\.js/i : /core\/server\.js/i;
33
+ const home = n.toLowerCase().includes(ROOT.replace(/\\/g, '/').toLowerCase()) || /node_modules\/buildproof\//i.test(n);
34
+ return script.test(n) && home;
35
+ }
36
+
37
+ module.exports = { cmdLine, isOurs, ROOT };
package/core/service.js CHANGED
@@ -16,13 +16,31 @@ const config = require('./config');
16
16
  const GUARD = path.join(config.ROOT, 'scripts', 'guard.js');
17
17
  const NODE = process.execPath;
18
18
 
19
- function health(port, timeoutMs = 1500) {
19
+ function healthInfo(port, timeoutMs = 1500) {
20
20
  return new Promise((resolve) => {
21
- const req = http.get({ host: '127.0.0.1', port, path: '/healthz', timeout: timeoutMs }, (res) => { res.resume(); resolve(res.statusCode === 200); });
22
- req.on('error', () => resolve(false));
23
- req.on('timeout', () => { req.destroy(); resolve(false); });
21
+ const req = http.get({ host: '127.0.0.1', port, path: '/healthz', timeout: timeoutMs }, (res) => {
22
+ let b = ''; res.on('data', (d) => { b += d; });
23
+ res.on('end', () => { if (res.statusCode !== 200) return resolve(null); try { resolve(JSON.parse(b)); } catch { resolve({}); } });
24
+ });
25
+ req.on('error', () => resolve(null));
26
+ req.on('timeout', () => { req.destroy(); resolve(null); });
24
27
  });
25
28
  }
29
+ async function health(port, timeoutMs) { return !!(await healthInfo(port, timeoutMs)); }
30
+
31
+ /** An older BuildProof is still answering after an update: stop it (its guard first, so it is not restarted). */
32
+ // Only processes whose command line shows they ARE BuildProof are ever stopped: never trust a PID from a file or an HTTP reply alone.
33
+ function stopOld(info) {
34
+ const { isOurs } = require('./procs');
35
+ let stopped = false;
36
+ try {
37
+ const pidFile = path.join(config.LOG_DIR, 'server_guard.pid');
38
+ const g = Number(String(fs.readFileSync(pidFile, 'utf8')).trim());
39
+ if (g > 0 && g !== process.pid && isOurs(g, 'guard', true) === true) { try { process.kill(g); } catch { /* gone */ } }
40
+ } catch { /* no guard */ }
41
+ if (info && info.pid > 0 && info.pid !== process.pid && isOurs(info.pid, 'server', true) === true) { try { process.kill(info.pid); stopped = true; } catch { /* gone */ } }
42
+ return stopped;
43
+ }
26
44
 
27
45
  function startDetached() {
28
46
  const child = spawn(NODE, [GUARD], { detached: true, stdio: 'ignore', windowsHide: true, cwd: config.ROOT, env: process.env });
@@ -74,11 +92,24 @@ function installAutostart() {
74
92
  async function ensure({ autostart = true } = {}) {
75
93
  const cfg = config.load();
76
94
  let how = 'already-running';
77
- if (!(await health(cfg.port))) {
95
+ const VERSION = require('../package.json').version;
96
+ let info = await healthInfo(cfg.port);
97
+ const older = (a, b) => { const x = String(a).split('.').map(Number), y = String(b).split('.').map(Number); for (let i = 0; i < 3; i++) { if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) < (y[i] || 0); } return false; };
98
+ if (info && info.ok === true && typeof info.version === 'string' && older(info.version, VERSION)) { // updated: replace the older service
99
+ if (stopOld(info)) {
100
+ for (let i = 0; i < 20 && info; i++) { await new Promise((r) => setTimeout(r, 300)); info = await healthInfo(cfg.port, 800); }
101
+ }
102
+ if (info) return { ok: true, how: `old-version-running(${info.version})`, autostart: null, port: cfg.port }; // could not replace it safely: keep using it
103
+ how = 'updated';
104
+ }
105
+ const isBp = (x) => !!(x && x.ok === true && typeof x.version === 'string');
106
+ if (info && !isBp(info)) return { ok: false, how: 'port_busy', port: cfg.port }; // another program answers on this port: never treat it as BuildProof
107
+ if (!info) {
78
108
  startDetached();
79
- how = 'started';
109
+ if (how !== 'updated') how = 'started';
80
110
  let ok = false;
81
- for (let i = 0; i < 40 && !ok; i++) { await new Promise((r) => setTimeout(r, 500)); ok = await health(cfg.port); }
111
+ const until = Date.now() + 20000; // at most 20 seconds, even when something on the port never answers
112
+ while (!ok && Date.now() < until) { await new Promise((r) => setTimeout(r, 500)); ok = isBp(await healthInfo(cfg.port, 1000)); }
82
113
  if (!ok) return { ok: false, how: 'start_failed', port: cfg.port };
83
114
  }
84
115
  let auto = null;
@@ -86,4 +117,4 @@ async function ensure({ autostart = true } = {}) {
86
117
  return { ok: true, how, autostart: auto, port: cfg.port };
87
118
  }
88
119
 
89
- module.exports = { ensure, health, installAutostart, startDetached };
120
+ module.exports = { ensure, health, healthInfo, installAutostart, startDetached };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "buildproof",
3
- "version": "3.12.1",
3
+ "version": "3.12.3",
4
4
  "description": "BuildProof - proof gate for AI-written code: test-integrity guard, fail-closed checks, scope lock, full rollback, signed certificates, local AI under supervision.",
5
5
  "main": "core/server.js",
6
6
  "scripts": {
package/scripts/guard.js CHANGED
@@ -28,7 +28,8 @@ const ERR_LOG = path.join(LOG_DIR, 'backend.err.log');
28
28
  const PID_FILE = path.join(LOG_DIR, 'server_guard.pid');
29
29
  const STATUS_FILE = path.join(LOG_DIR, 'server_guard.status.json');
30
30
 
31
- const PORT = parseInt(process.env.MGR_PORT || process.env.PORT || '38700', 10);
31
+ // Same port as the CLI and the server: MGR_PORT, else config.json, else 38700. Never the generic PORT variable (that is the customer's own app).
32
+ const PORT = parseInt(process.env.MGR_PORT || (() => { try { return require('../core/config').load().port; } catch { return 0; } })() || '38700', 10);
32
33
  const HEALTH_PATH = process.env.MGR_HEALTH_PATH || '/healthz';
33
34
  const CHECK_MS = parseInt(process.env.MGR_GUARD_CHECK_MS || '10000', 10);
34
35
  const HEALTH_TIMEOUT_MS = parseInt(process.env.MGR_GUARD_HEALTH_TIMEOUT_MS || '5000', 10);
@@ -49,6 +50,7 @@ let restarting = false;
49
50
  let stopping = false;
50
51
  let errTail = [];
51
52
  let lastHealthOkAt = 0;
53
+ let foreignWarned = false;
52
54
 
53
55
  function ensureLogDir() { fs.mkdirSync(LOG_DIR, { recursive: true }); }
54
56
 
@@ -91,13 +93,20 @@ function isPidAlive(pid) {
91
93
  try { process.kill(pid, 0); return true; } catch (e) { return !!(e && e.code === 'EPERM'); }
92
94
  }
93
95
 
96
+ const { cmdLine, isOurs } = require('../core/procs');
97
+ function statusFresh() {
98
+ try { return Date.now() - Date.parse(JSON.parse(fs.readFileSync(STATUS_FILE, 'utf8')).updatedAt) < 90000; } catch { return false; }
99
+ }
100
+
94
101
  function acquireLock() {
95
102
  ensureLogDir();
96
103
  try {
97
104
  if (fs.existsSync(PID_FILE)) {
98
105
  const existing = Number(String(fs.readFileSync(PID_FILE, 'utf8')).trim());
99
106
  if (existing !== process.pid && isPidAlive(existing)) {
100
- process.exit(0); // another guard is already running
107
+ // the PID may have been reused by an unrelated process after a reboot or crash: only a real BuildProof guard counts
108
+ const ours = isOurs(existing, 'guard', true);
109
+ if (ours === true || (ours === null && statusFresh())) process.exit(0); // another guard is already running
101
110
  }
102
111
  }
103
112
  } catch { /* stale lock */ }
@@ -146,9 +155,15 @@ function pidListeningOnPort(port) {
146
155
  }
147
156
  return null;
148
157
  }
149
- const out = execSync(`ss -ltnp 2>/dev/null | grep ':${port} ' || true`, { encoding: 'utf8' });
150
- const m = out.match(/pid=(\d+)/);
151
- return m ? Number(m[1]) : null;
158
+ if (process.platform === 'linux') {
159
+ const out = execSync(`ss -ltnp 2>/dev/null | grep ':${port} ' || true`, { encoding: 'utf8' });
160
+ const m = out.match(/pid=(\d+)/);
161
+ if (m) return Number(m[1]);
162
+ }
163
+ // macOS (no ss), or Linux without ss
164
+ const out = execSync(`lsof -nP -iTCP:${Number(port)} -sTCP:LISTEN -t 2>/dev/null || true`, { encoding: 'utf8', timeout: 5000 });
165
+ const pid = Number(String(out).trim().split(/\s+/)[0]);
166
+ return pid > 0 ? pid : null;
152
167
  } catch { return null; }
153
168
  }
154
169
 
@@ -241,8 +256,8 @@ function hardRestart(reason) {
241
256
  killTree(pid);
242
257
  const holder = pidListeningOnPort(PORT);
243
258
  if (holder && holder !== process.pid) {
244
- log(`FREE-PORT killing pid=${holder} holding :${PORT}`);
245
- killTree(holder);
259
+ if (isOurs(holder, 'server', true) === true) { log(`FREE-PORT killing hung BuildProof backend pid=${holder} on :${PORT}`); killTree(holder); }
260
+ else log(`PORT-BUSY :${PORT} is held by pid=${holder}, which is not BuildProof - left alone`);
246
261
  }
247
262
  scheduleRestart(reason);
248
263
  }
@@ -268,9 +283,14 @@ async function tick() {
268
283
  if (!child) {
269
284
  const holder = pidListeningOnPort(PORT);
270
285
  if (!holder) { startBackend('not-running'); return; }
286
+ if (isOurs(holder, 'server') !== true) { // another program owns this port: never touch it
287
+ if (!foreignWarned) { log(`PORT-BUSY :${PORT} is used by pid=${holder} (not BuildProof) - waiting, nothing is killed. Set another port: MGR_PORT or "port" in config.json`); foreignWarned = true; }
288
+ writeStatus({ portBusy: true });
289
+ return;
290
+ }
271
291
  consecutiveFails += 1;
272
- log(`HEALTH-FAIL foreign pid=${holder} on :${PORT} (${consecutiveFails}/${FAILS_BEFORE_RESTART})`);
273
- if (consecutiveFails >= FAILS_BEFORE_RESTART) hardRestart('foreign process unhealthy');
292
+ log(`HEALTH-FAIL own backend pid=${holder} on :${PORT} (${consecutiveFails}/${FAILS_BEFORE_RESTART})`);
293
+ if (consecutiveFails >= FAILS_BEFORE_RESTART) hardRestart('orphan backend unhealthy');
274
294
  writeStatus();
275
295
  return;
276
296
  }
@@ -308,4 +328,4 @@ async function main() {
308
328
 
309
329
  if (require.main === module) main();
310
330
 
311
- module.exports = { checkHealth, pidListeningOnPort, memoryMb, PORT };
331
+ module.exports = { checkHealth, pidListeningOnPort, memoryMb, isOurs, cmdLine, PORT };