buildproof 3.13.0 → 3.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/bin/buildproof.js +39 -11
- package/core/hunt-client.js +1 -1
- package/core/integrity.js +374 -2
- package/core/license.js +19 -5
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -7,6 +7,8 @@ npx buildproof try # see it first, on a throw-away sample: a skipped test is
|
|
|
7
7
|
npx buildproof init # then on your project: hooks for Claude Code / Cursor / git, 14-day free trial (add --ci for the GitHub PR check)
|
|
8
8
|
```
|
|
9
9
|
|
|
10
|
+
**New: BuildProof Review for GitHub** - install the GitHub App and every pull request gets a reviewer that only reports bugs it can prove: it writes a test, runs it in a locked container, and posts it only if it fails on the PR and passes on the base branch. JavaScript, TypeScript and Python, 20 free checks a month: https://buildproof.mgrprosnetwork.com/github
|
|
11
|
+
|
|
10
12
|
After `init`, keep working as usual. When your AI tool finishes, BuildProof re-runs your real checks; if a test was skipped, deleted or weakened, or "all tests pass" is not true, it answers NOT PROVEN and sends the reason back to the AI.
|
|
11
13
|
|
|
12
14
|
Works two ways, same guarantees:
|
|
@@ -31,7 +33,7 @@ Pull request checks (3.8.0; Team and Enterprise - in CI they need a paid licence
|
|
|
31
33
|
|
|
32
34
|
Audit report (3.9.0; free trial, then Enterprise): `buildproof audit --since 2026-01-01` writes a signed HTML + JSON report of every accepted and rejected change; `buildproof audit --verify report.json` shows any later edit. Team dashboard (Team and Enterprise): `buildproof team` opens it; your licence key unlocks your own team's certificates.
|
|
33
35
|
|
|
34
|
-
AI bug hunt (3.10.0;
|
|
36
|
+
AI bug hunt (3.10.0; every paid plan - Basic 3 hunts a month, Pro 30 cloud checks a month - and the trial): `buildproof hunt --base main` uploads copies of the tracked files at the base commit and at your current version (including uncommitted edits), plus the change description, to the BuildProof server, where the hunter runs your code and the AI-written tests in a locked-down container (no network) and reports only bugs it PROVED (a test that fails on the new code and passes on the old). By default your own local model (Ollama) answers the AI's questions - free; `--cloud` uses the server's AI (one cloud check; 5 in the trial; `buildproof credits --buy 20`). Your code is deleted from the server when the check ends. Since 3.12 the hunter is told what the change was meant to do: taken from `--intent "..."`, else from the pull request (GitHub) or merge request (GitLab) title and description, else from the commit messages since the base. This helps it tell a real bug from an intended change. `--no-intent` turns it off.
|
|
35
37
|
|
|
36
38
|
CLI: `buildproof start | check [--claim "..."] | accept [--force] | rollback | connect | verify <cert.html> | status | ci [--base origin/main] [--spec spec.md]`. `buildproof check` exits 0 only when proven.
|
|
37
39
|
|
|
@@ -42,4 +44,4 @@ Background service: `init` and `try` start a small local service (127.0.0.1 only
|
|
|
42
44
|
|
|
43
45
|
Certificates: the signature proves a certificate was not edited after it was issued. It does not prove who issued it: anyone can sign their own. `buildproof verify` therefore also checks the BuildProof public log (key registered to a licensed account, certificate countersigned with BuildProof's key) and says SELF_SIGNED otherwise. The real proof is `buildproof verify <cert> --rerun <folder>`: it re-runs the checks on the code you received.
|
|
44
46
|
|
|
45
|
-
Network calls (all of them): trial start (`/api/trial/start`, a one-way hash of a device id, cached for 10 minutes when offline); licence activation / renewal / certificate countersigning (licence key or subscription id, signing public key and fingerprint, certificate hash - never your code); a daily npm registry version check; `ci --init` asks api.github.com whether your base branch is protected; `hunt` uploads the code as described above; `verify` reads the public log. The local web page loads Google Fonts and, on the phone-connect page, a QR code script from cdnjs.
|
|
47
|
+
Network calls (all of them): trial start (`/api/trial/start`, a one-way hash of a device id, plus the name of the command that ran and the BuildProof version, so we can see whether the trial is used - cached for 10 minutes when offline); the trial email, only if you give one (`buildproof trial --email you@example.com`, or the optional question in `buildproof init`): a confirmation link first, then a reminder before the trial ends and two questions after it, with one-click unsubscribe; licence activation / renewal / certificate countersigning (licence key or subscription id, signing public key and fingerprint, certificate hash - never your code); a daily npm registry version check; `ci --init` asks api.github.com whether your base branch is protected; `hunt` uploads the code as described above; `verify` reads the public log. The local web page loads Google Fonts and, on the phone-connect page, a QR code script from cdnjs.
|
package/bin/buildproof.js
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* buildproof init [folder] [--ci] one-time setup: background service, project, AI tool hooks (--ci also adds the GitHub PR check)
|
|
14
14
|
* buildproof try 30-second demo on a throw-away sample project: a skipped test is caught, the real fix is proven
|
|
15
15
|
* buildproof activate <key> activate a license key buildproof license show the plan
|
|
16
|
+
* buildproof trial [--email you@example.com] trial days left; the email (optional) gets a reminder before the trial ends
|
|
16
17
|
* buildproof open open BuildProof in the browser
|
|
17
18
|
* buildproof stop stop the background service buildproof remote on|off allow your phone / tablet on this network (off = this computer only)
|
|
18
19
|
* buildproof uninstall [folder] [--all --yes] remove BuildProof's hooks from the project and the start-at-login entry, stop the service (--all --yes also deletes ~/.buildproof)
|
|
@@ -37,7 +38,7 @@ const args = process.argv.slice(2);
|
|
|
37
38
|
const cmd = ['-h', '--help'].includes(args[0]) ? 'help' : (args[0] || 'help');
|
|
38
39
|
if (['-v', '--version', 'version'].includes(cmd)) { console.log(require('../package.json').version); process.exit(0); }
|
|
39
40
|
// flags that take a value accept both --name=value and --name value
|
|
40
|
-
const VALUE_FLAGS = new Set(['base', 'buy', 'intent', 'out', 'since', 'until', 'spec', 'verify', 'summary', 'claim']);
|
|
41
|
+
const VALUE_FLAGS = new Set(['email', 'base', 'buy', 'intent', 'out', 'since', 'until', 'spec', 'verify', 'summary', 'claim']);
|
|
41
42
|
const flag = (n) => {
|
|
42
43
|
const i = args.findIndex((x) => x === `--${n}` || x.startsWith(`--${n}=`));
|
|
43
44
|
if (i < 0) return null;
|
|
@@ -176,11 +177,12 @@ async function main() {
|
|
|
176
177
|
if (cmd === 'verify') {
|
|
177
178
|
const certs = require('../core/certs');
|
|
178
179
|
const file = positional[0];
|
|
179
|
-
if (!file
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
const cert = JSON.parse(m ? m[1] : raw);
|
|
183
|
-
|
|
180
|
+
if (!file) out('usage: buildproof verify <certificate.html|.json>', 1);
|
|
181
|
+
if (!fs.existsSync(file)) out(`NOT_FOUND there is no file "${file}"`, 1);
|
|
182
|
+
let cert = null;
|
|
183
|
+
try { const raw = fs.readFileSync(file, 'utf8'); const m = raw.match(/<script id="cert" type="application\/json">([\s\S]*?)<\/script>/); cert = JSON.parse(m ? m[1] : raw); } catch { cert = null; }
|
|
184
|
+
if (!cert || typeof cert !== 'object' || !cert.payload) out(`NOT_A_CERTIFICATE "${file}" is not a BuildProof certificate (expected the .html or .json file BuildProof wrote)`, 1);
|
|
185
|
+
let ok = false; try { ok = certs.verify(cert); } catch { ok = false; }
|
|
184
186
|
if (!ok) out('INVALID signature - the certificate was modified (or names a key it was not signed with)', 1);
|
|
185
187
|
if (!flag('rerun')) {
|
|
186
188
|
// a valid signature only shows the file was not edited; who stands behind it comes from the public log
|
|
@@ -233,6 +235,19 @@ async function main() {
|
|
|
233
235
|
const sv = await require('../core/service').ensure({ autostart: false });
|
|
234
236
|
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);
|
|
235
237
|
}
|
|
238
|
+
if (cmd === 'trial') { // BP_TRIAL_CARE: days left, and an optional email for a reminder before the end
|
|
239
|
+
const L = require('../core/license');
|
|
240
|
+
const e = flag('email');
|
|
241
|
+
if (e === true) out('TRIAL_EMAIL_FAIL add the address: buildproof trial --email you@example.com', 1);
|
|
242
|
+
if (typeof e === 'string') {
|
|
243
|
+
if (!/^[^\s@]+@[^\s@]+\.[A-Za-z]{2,}$/.test(e.trim())) out(`TRIAL_EMAIL_FAIL "${e}" does not look like an email address`, 1);
|
|
244
|
+
const r = await L.trialEmail(e);
|
|
245
|
+
const why = { no_trial: 'no trial on this computer yet: run any buildproof command first', invalid_email: 'the server did not accept this address', too_soon: 'wait a minute and try again', try_later: 'too many sign-ups right now, try again later', email_unavailable: 'our mail service is not answering, try again later', no_server: 'no licence server is set up on this computer', too_many_requests: 'too many tries, wait a minute' }[r.error] || `could not reach the BuildProof server (${r.error})`;
|
|
246
|
+
out(r.ok ? `TRIAL_EMAIL sent a confirmation link to ${e}. Click the button on that page and we will remind you before your trial ends, and ask 2 short questions after it. Every email has a one-click unsubscribe.` : `TRIAL_EMAIL_FAIL ${why}`, r.ok ? 0 : 1);
|
|
247
|
+
}
|
|
248
|
+
const st = L.status();
|
|
249
|
+
out(`TRIAL ${st.plan === 'trial' ? `${st.status} days_left=${st.daysLeft}${st.hasEmail ? ' reminder=on' : '\n Get a reminder before it ends: buildproof trial --email you@example.com'}` : `not in trial (licence: ${st.label} ${st.status})`}`, 0);
|
|
250
|
+
}
|
|
236
251
|
if (cmd === 'license' || cmd === 'activate') {
|
|
237
252
|
if (cmd === 'activate') {
|
|
238
253
|
let key = positional[0] || '';
|
|
@@ -254,15 +269,20 @@ async function main() {
|
|
|
254
269
|
}
|
|
255
270
|
const r = await api('GET', '/api/license', null, 15000);
|
|
256
271
|
if (!r.ok || !r.label) out(`DOWN ${r.error || 'unexpected answer on port ' + config.load().port}`, 1);
|
|
257
|
-
out(`LICENSE ${r.label} ${r.status}${r.daysLeft != null ? ' days_left=' + r.daysLeft : ''}${r.projects ? ' projects_max=' + r.projects : ''}`, r.status === 'expired' ? 1 : 0);
|
|
272
|
+
out(`LICENSE ${r.label} ${r.status}${r.daysLeft != null ? ' days_left=' + r.daysLeft : ''}${r.projects ? ' projects_max=' + r.projects : ''}${r.plan === 'trial' && r.status === 'trial' && r.hasEmail === false ? '\n Get a reminder before your trial ends: buildproof trial --email you@example.com' : ''}`, r.status === 'expired' ? 1 : 0);
|
|
258
273
|
}
|
|
259
274
|
if (cmd === 'init') {
|
|
260
275
|
const service = require('../core/service');
|
|
261
|
-
|
|
276
|
+
let autostart = !process.env.MGR_NO_AUTOSTART && !flag('no-autostart');
|
|
277
|
+
if (autostart && process.stdin.isTTY && process.stdout.isTTY && !process.env.CI && !flag('autostart')) {
|
|
278
|
+
const a = await new Promise((resolve) => { const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout }); const t = setTimeout(() => { rl.close(); resolve(''); }, 60000); rl.question('Start BuildProof automatically when you log in, so the AI-tool hooks always work? [Y/n] ', (x) => { clearTimeout(t); rl.close(); resolve(String(x || '').trim()); }); });
|
|
279
|
+
if (/^n/i.test(a)) autostart = false;
|
|
280
|
+
}
|
|
281
|
+
const sv = await service.ensure({ autostart });
|
|
262
282
|
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);
|
|
263
283
|
const dir = path.resolve(positional[0] || process.cwd());
|
|
264
284
|
const pr = await api('POST', '/api/projects', { root: dir });
|
|
265
|
-
if (!pr.ok) out(`INIT_FAIL ${pr.error
|
|
285
|
+
if (!pr.ok) out(`INIT_FAIL ${pr.error === 'plan_limit_projects' ? `this plan allows ${pr.limit} projects. Remove one in the BuildProof page (buildproof open), or upgrade: https://buildproof.mgrprosnetwork.com/#pricing` : pr.error}`, 1);
|
|
266
286
|
const { spawnSync } = require('child_process');
|
|
267
287
|
const onPath = (c) => { try { return spawnSync(process.platform === 'win32' ? 'where' : 'which', [c], { stdio: 'ignore' }).status === 0; } catch { return false; } };
|
|
268
288
|
const tools = [];
|
|
@@ -277,8 +297,16 @@ async function main() {
|
|
|
277
297
|
let ciNote = '';
|
|
278
298
|
if (flag('ci')) { const w = require('../core/ci').init(dir); ciNote = w.ok ? `pull request check added: ${path.relative(dir, w.file)} - add your licence key as the BUILDPROOF_LICENSE secret in GitHub` : `pull request check already there: ${path.relative(dir, w.file)}`; }
|
|
279
299
|
console.log(initSummary({ project: pr.project, connected, lic, ciNote, git: tools.includes('git') }));
|
|
280
|
-
if (
|
|
281
|
-
|
|
300
|
+
if (lic.plan === 'trial' && lic.status === 'trial' && lic.hasEmail === false && process.stdin.isTTY && process.stdout.isTTY && !process.env.CI && !flag('ci')) {
|
|
301
|
+
const answer = await new Promise((resolve) => {
|
|
302
|
+
const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout });
|
|
303
|
+
const t = setTimeout(() => { rl.close(); resolve(''); }, 60000);
|
|
304
|
+
rl.question('Your email for a reminder before the trial ends (optional, Enter to skip): ', (a) => { clearTimeout(t); rl.close(); resolve(String(a || '').trim()); });
|
|
305
|
+
});
|
|
306
|
+
if (answer) { const r = await require('../core/license').trialEmail(answer); console.log(r.ok ? ` Sent a confirmation link to ${answer}. Click it to get the reminder.` : ` Could not save the email (${r.error}). Later: buildproof trial --email you@example.com`); }
|
|
307
|
+
}
|
|
308
|
+
if (flag('open')) openUrl(`http://127.0.0.1:${sv.port}/connect`);
|
|
309
|
+
out(`READY BuildProof page: http://127.0.0.1:${sv.port}/connect (or: buildproof open)${sv.autostart ? ' · starts at login (turn off: buildproof uninstall)' : ''}`, 0);
|
|
282
310
|
}
|
|
283
311
|
if (cmd === 'try') { // 30-second demo on a throw-away sample project, never on your code (installs nothing that starts at login)
|
|
284
312
|
const service = require('../core/service');
|
package/core/hunt-client.js
CHANGED
|
@@ -70,7 +70,7 @@ async function run({ root, base, cloud, intent, cfg, license, server, llm, log =
|
|
|
70
70
|
const start = await request('POST', server + '/api/hunt', headers, { before: a.before, after: a.after, mode: cloud ? 'cloud' : 'local', intent }, 300000);
|
|
71
71
|
if (start.code !== 200 || !start.j || !start.j.ok) {
|
|
72
72
|
const e = (start.j && start.j.error) || 'server_unavailable';
|
|
73
|
-
const hint = { no_cloud_checks: 'no cloud checks left: buildproof credits --buy 20, or run without --cloud (your own model, free)', hunter_not_in_plan: 'the hunter is in Pro
|
|
73
|
+
const hint = { no_cloud_checks: 'no cloud checks left: buildproof credits --buy 20, or run without --cloud (your own model, free)', hunter_not_in_plan: 'the hunter is in every paid plan (Basic: 3 a month)', basic_hunts_used: 'the 3 hunts of Basic this month are used - Pro has 30 a month: https://buildproof.mgrprosnetwork.com/#pricing', trial_ended: 'the trial has ended', cloud_ai_not_configured: 'cloud AI is not available yet, run without --cloud' }[e];
|
|
74
74
|
return { code: 2, text: `CANNOT_HUNT ${e}${hint ? ' - ' + hint : ''}` };
|
|
75
75
|
}
|
|
76
76
|
const id = start.j.id;
|
package/core/integrity.js
CHANGED
|
@@ -150,18 +150,144 @@ function assertionKeys(src, py) {
|
|
|
150
150
|
if (m[1] === 'assert' && /^\s*=/.test(blank.slice(m.index + m[0].length - 1))) continue;
|
|
151
151
|
let end = close(m.index + m[0].length);
|
|
152
152
|
if (m[1] === 'expect') { const tail = blank.slice(end).match(/^(\s*\.\s*(?:not|resolves|rejects)\b)*\s*\.\s*\w+\s*\(/); if (tail) end = close(end + tail[0].length); }
|
|
153
|
-
keys.push(norm(code.slice(m.index, end)));
|
|
153
|
+
keys.push(norm(code.slice(m.index, end))); (keys.pos || (keys.pos = [])).push(m.index); // BP_3131: positions
|
|
154
154
|
}
|
|
155
155
|
const pyAssert = /^[ \t]*assert[ \t]+(.+)$/gm; // Python assert statements (string contents blanked, so docstrings do not count)
|
|
156
|
-
while ((m = pyAssert.exec(blank))) keys.push(norm(code.slice(m.index, m.index + m[0].length).replace(/^[ \t]*/, '')));
|
|
156
|
+
while ((m = pyAssert.exec(blank))) { keys.push(norm(code.slice(m.index, m.index + m[0].length).replace(/^[ \t]*/, ''))); (keys.pos || (keys.pos = [])).push(m.index); }
|
|
157
157
|
return keys;
|
|
158
158
|
}
|
|
159
159
|
|
|
160
|
+
// ---------- BP_3131 rule 1: a new early `return <nothing / a literal>` before checks that existed before ----------
|
|
161
|
+
// Works on the code with comments removed, so `return null; // TODO` and `return None # skip` count too.
|
|
162
|
+
// Only the function the return actually leaves is looked at: a guard in a helper, a beforeEach or a forEach callback
|
|
163
|
+
// that has no old assertion after it in that same function is fine; `return done(err)` / `return promise` are real work.
|
|
164
|
+
const LIT_JS = /^\s*(?:null|undefined|true|false|NaN|Infinity|void\s*\(?\s*0\s*\)?|!\s*[01]|[-+]?\d[\d_]*(?:\.\d+)?(?:e[-+]?\d+)?n?|'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|`[^`$\\]*`|\{\s*\}|\[\s*\]|\(\s*(?:null|undefined|true|false|void\s*0|[-+]?\d+|'[^'\n]*'|"[^"\n]*"|\{\s*\}|\[\s*\])\s*\))?(?:\s+as\s+[\w$.<>\[\] |]{1,60})?\s*(?=;|\}|$|\belse\b|\)|,)/;
|
|
165
|
+
const LIT_PY = /^[ \t]*(?:None|True|False|[-+]?\d[\d_]*(?:\.\d+)?|'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|\(\s*\)|\[\s*\]|\{\s*\})?[ \t\r]*(?=;|$|\n)/;
|
|
166
|
+
|
|
167
|
+
/** Indexes (0-based) of the lines of `b` that are new compared with `a` (a real line diff, so a copied line does not
|
|
168
|
+
* make an untouched old line look new). Lines are compared whitespace-normalised. */
|
|
169
|
+
function addedLineIndexes(a, b) {
|
|
170
|
+
const A = a.map((x) => x.trim().replace(/\s+/g, ' ')), B = b.map((x) => x.trim().replace(/\s+/g, ' '));
|
|
171
|
+
let s = 0; while (s < A.length && s < B.length && A[s] === B[s]) s++;
|
|
172
|
+
let ea = A.length, eb = B.length; while (ea > s && eb > s && A[ea - 1] === B[eb - 1]) { ea--; eb--; }
|
|
173
|
+
const out = new Set(); const n = ea - s, m = eb - s;
|
|
174
|
+
if (!m) return out;
|
|
175
|
+
if (!n) { for (let j = s; j < eb; j++) out.add(j); return out; }
|
|
176
|
+
if (n * m > 4e6) { // too big for a table: fall back to counting (whitespace-normalised multiset)
|
|
177
|
+
const cnt = new Map(); for (let i = s; i < ea; i++) cnt.set(A[i], (cnt.get(A[i]) || 0) + 1);
|
|
178
|
+
for (let j = s; j < eb; j++) { const c = cnt.get(B[j]) || 0; if (c > 0) cnt.set(B[j], c - 1); else out.add(j); }
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
const W = m + 1; const L = new Uint32Array((n + 1) * W);
|
|
182
|
+
for (let i = n - 1; i >= 0; i--) for (let j = m - 1; j >= 0; j--) L[i * W + j] = A[s + i] === B[s + j] ? L[(i + 1) * W + j + 1] + 1 : Math.max(L[(i + 1) * W + j], L[i * W + j + 1]);
|
|
183
|
+
let i = 0, j = 0;
|
|
184
|
+
while (i < n && j < m) { if (A[s + i] === B[s + j]) { i++; j++; } else if (L[(i + 1) * W + j] >= L[i * W + j + 1]) i++; else { out.add(s + j); j++; } }
|
|
185
|
+
for (; j < m; j++) out.add(s + j);
|
|
186
|
+
return out;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** Is the `{` at k (in the blank view) the body of a function (incl. TS return types, destructured / default params, methods)? */
|
|
190
|
+
function balancedType(t) { // a return-type annotation: balanced brackets, no statement characters
|
|
191
|
+
let d = 0; for (const ch of t) { if ('({[<'.includes(ch)) d++; else if (')}]>'.includes(ch)) { if (ch === '>' && d === 0) continue; d--; if (d < 0) return false; } else if (ch === ';' && d === 0) return false; }
|
|
192
|
+
return d === 0;
|
|
193
|
+
}
|
|
194
|
+
function isFunctionBrace(B, k) {
|
|
195
|
+
let tb = B.slice(Math.max(0, k - 400), k).replace(/\s+$/, '');
|
|
196
|
+
if (/=>$/.test(tb)) return true;
|
|
197
|
+
if (/(^|[^\w$])(else|try|finally|do|static|class\s+[\w$]+(\s+extends\s+[\w$.]+)?)$/.test(tb)) return false;
|
|
198
|
+
if (!/\)$/.test(tb)) { // a return type between `)` and `{`: ): { id: number } | null { ): Promise<(() => void) | null> {
|
|
199
|
+
let found = false;
|
|
200
|
+
for (let p = tb.length - 1, n = 0; p >= 0 && n < 12; p--) {
|
|
201
|
+
if (tb[p] !== ')') continue; n++;
|
|
202
|
+
const rest = tb.slice(p + 1);
|
|
203
|
+
if (/^\s*:/.test(rest) && balancedType(rest.replace(/^\s*:/, '').replace(/=>/g, ' '))) { tb = tb.slice(0, p + 1); found = true; break; }
|
|
204
|
+
}
|
|
205
|
+
if (!found) return false;
|
|
206
|
+
}
|
|
207
|
+
let d = 0, p = tb.length - 1; // matching ( of the parameter list
|
|
208
|
+
for (; p >= 0; p--) { const ch = tb[p]; if (ch === ')' || ch === ']' || ch === '}') d++; else if (ch === '(' || ch === '[' || ch === '{') { d--; if (d === 0) break; } }
|
|
209
|
+
if (p < 0) return false;
|
|
210
|
+
const head = tb.slice(0, p).replace(/\s*<[^<>()]{0,120}>\s*$/, '').replace(/\s+$/, ''); // generics: get<T>(
|
|
211
|
+
if (/(^|[^\w$.])(if|for|while|switch|catch|with|return|typeof|await|new)$/.test(head)) return false;
|
|
212
|
+
return /[\w$\]]$/.test(head); // function f( / method( / get x( / [Symbol.iterator](
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function earlyLiteralReturn(before, after, py, keysBefore) {
|
|
216
|
+
const old = new Set(keysBefore); if (!old.size) return null;
|
|
217
|
+
const vb = codeViews(before, py), va = codeViews(after, py);
|
|
218
|
+
const codeLines = va.code.split('\n');
|
|
219
|
+
const added = addedLineIndexes(vb.code.split('\n'), codeLines);
|
|
220
|
+
if (!added.size) return null;
|
|
221
|
+
const starts = []; { let o = 0; for (const l of codeLines) { starts.push(o); o += l.length + 1; } }
|
|
222
|
+
const lineOf = (pos) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= pos) lo = mid; else hi = mid - 1; } return lo; };
|
|
223
|
+
// old assertions = assertions with an old text that sit on a line the diff did NOT mark as new (a copied test is new)
|
|
224
|
+
// (counted: if a check appears as often as before it is still the old one, even when its line was edited;
|
|
225
|
+
// only copies beyond the old count, on new lines, are new)
|
|
226
|
+
const all = assertionKeys(va.code, py); const pos = all.pos || [];
|
|
227
|
+
const left = new Map(); for (const k of keysBefore) left.set(k, (left.get(k) || 0) + 1);
|
|
228
|
+
const order = pos.map((p, i) => i).sort((x, y) => (added.has(lineOf(pos[x])) - added.has(lineOf(pos[y]))) || (pos[x] - pos[y]));
|
|
229
|
+
const oldPos = [];
|
|
230
|
+
for (const i of order) { const c = left.get(all[i]) || 0; if (c > 0) { left.set(all[i], c - 1); oldPos.push(pos[i]); } }
|
|
231
|
+
oldPos.sort((x, y) => x - y);
|
|
232
|
+
if (!oldPos.length) return null;
|
|
233
|
+
const hasOldIn = (from, to) => { let lo = 0, hi = oldPos.length; while (lo < hi) { const mid = (lo + hi) >> 1; if (oldPos[mid] < from) lo = mid + 1; else hi = mid; } return lo < oldPos.length && oldPos[lo] < to; };
|
|
234
|
+
// an existing guard whose condition was only edited is not a new return: pair added literal returns with removed ones
|
|
235
|
+
const retKey = (t) => t.replace(/\s+/g, '').replace(/^return(undefined|void\(?0\)?)?(?=;|\}|$)/, 'return');
|
|
236
|
+
const removedRet = new Map();
|
|
237
|
+
{ const bl = vb.code.split('\n'); const gone = addedLineIndexes(codeLines, bl);
|
|
238
|
+
for (const j of gone) { const r = (bl[j] || '').match(/\breturn\b.*$/); if (r) { const key = retKey(r[0]); removedRet.set(key, (removedRet.get(key) || 0) + 1); } } }
|
|
239
|
+
// candidate returns on added lines
|
|
240
|
+
const cands = [];
|
|
241
|
+
for (const li of [...added].sort((x, y) => x - y)) {
|
|
242
|
+
const cl = (codeLines[li] || '').replace(/\r$/, ''); const bl = va.blank.slice(starts[li], starts[li] + cl.length);
|
|
243
|
+
if (bl.length > 4000) continue;
|
|
244
|
+
const re = /\breturn\b/g; let m;
|
|
245
|
+
while ((m = re.exec(bl))) {
|
|
246
|
+
const lit = (py ? LIT_PY : LIT_JS).exec(cl.slice(m.index + 6));
|
|
247
|
+
if (!lit) continue;
|
|
248
|
+
const key = retKey(cl.slice(m.index)); const c = removedRet.get(key) || 0;
|
|
249
|
+
if (c > 0) { removedRet.set(key, c - 1); continue; }
|
|
250
|
+
cands.push({ li, pos: starts[li] + m.index, from: starts[li] + m.index + 6 + lit[0].length, text: cl.trim().slice(0, 160) });
|
|
251
|
+
if (cands.length > 2000) break;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
if (!cands.length) return null;
|
|
255
|
+
const report = (c, end) => (end > c.from && hasOldIn(c.from, end)) ? 'early return before the checks: ' + c.text : null;
|
|
256
|
+
if (py) {
|
|
257
|
+
// one forward pass: the def each line belongs to (indentation stack) and where that def ends
|
|
258
|
+
const indOf = (l) => (l.match(/^[ \t]*/) || [''])[0].replace(/\t/g, ' ').length;
|
|
259
|
+
const owner = new Int32Array(codeLines.length).fill(-1); const endOf = new Map(); const stack = [];
|
|
260
|
+
const blankL = va.blank.split('\n'); let par = 0;
|
|
261
|
+
for (let i = 0; i < codeLines.length; i++) {
|
|
262
|
+
const l = codeLines[i]; const cont = par > 0; // inside ( [ { of a previous line: a continuation, e.g. a multi-line def signature
|
|
263
|
+
for (const ch of blankL[i] || '') { if ('([{'.includes(ch)) par++; else if (')]}'.includes(ch) && par > 0) par--; }
|
|
264
|
+
if (!l.trim() || cont) { owner[i] = stack.length ? stack[stack.length - 1].i : -1; continue; }
|
|
265
|
+
const d = indOf(l);
|
|
266
|
+
while (stack.length && d <= stack[stack.length - 1].d) endOf.set(stack.pop().i, starts[i]);
|
|
267
|
+
owner[i] = stack.length ? stack[stack.length - 1].i : -1;
|
|
268
|
+
if (/^\s*(async\s+)?def\b/.test(l)) stack.push({ i, d });
|
|
269
|
+
}
|
|
270
|
+
for (const c of cands) { const o = owner[c.li]; const r = report(c, o < 0 ? va.code.length : (endOf.get(o) || va.code.length)); if (r) return r; }
|
|
271
|
+
return null;
|
|
272
|
+
}
|
|
273
|
+
// JS/TS: one forward pass over the braces; for each candidate the innermost enclosing FUNCTION body and its end
|
|
274
|
+
const B = va.blank; const stack = []; const want = cands.map((c) => c.pos); let w = 0; const fnOf = new Array(cands.length).fill(-1); const closeOf = new Map();
|
|
275
|
+
for (let k = 0; k <= B.length; k++) {
|
|
276
|
+
while (w < want.length && want[w] === k) { for (let s2 = stack.length - 1; s2 >= 0; s2--) if (stack[s2].fn) { fnOf[w] = stack[s2].k; break; } w++; }
|
|
277
|
+
if (k === B.length) break;
|
|
278
|
+
if (B[k] === '{') stack.push({ k, fn: isFunctionBrace(B, k) });
|
|
279
|
+
else if (B[k] === '}' && stack.length) { const o = stack.pop(); if (o.fn) closeOf.set(o.k, k + 1); }
|
|
280
|
+
}
|
|
281
|
+
for (let i = 0; i < cands.length; i++) { const o = fnOf[i]; const r = report(cands[i], o < 0 ? va.code.length : (closeOf.get(o) || va.code.length)); if (r) return r; }
|
|
282
|
+
return null;
|
|
283
|
+
}
|
|
284
|
+
|
|
160
285
|
/** An assertion that still exists but no longer runs: moved under a condition, behind an early return,
|
|
161
286
|
* or into a function nothing calls. Returns the offending text or null. */
|
|
162
287
|
function hiddenAssertion(before, after, py, keysBefore, added, rel) {
|
|
163
288
|
const named = /\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)test_[^/]+\.py$|_test\.py$/i.test(String(rel).replace(/\\/g, '/'));
|
|
164
289
|
if (!named) return null;
|
|
290
|
+
{ const er = earlyLiteralReturn(before, after, py, keysBefore); if (er) return er; } // BP_3131
|
|
165
291
|
const A = /\b(expect|assert\w*|t\.(equal|is|deepEqual|true|false))\b/;
|
|
166
292
|
// only assertions that existed BEFORE the change matter here: new tests may use conditions and callbacks freely
|
|
167
293
|
const old = new Set(keysBefore);
|
|
@@ -309,6 +435,9 @@ function analyze({ root, beforeDir, changes, testFiles }) {
|
|
|
309
435
|
const changedStep = bpBefore.find((l) => !bpAfter.has(l));
|
|
310
436
|
const bypass = wd.added.find((l) => /\|\|\s*(true|exit\s+0|:)\b|continue-on-error\s*:\s*true|^\s*(-\s*)?if\s*:\s*(false|\$\{\{\s*false)|BUILDPROOF_(SKIP|OFF)|buildproof\b.*--no-baseline|^\s*(paths|paths-ignore)\s*:/i.test(l));
|
|
311
437
|
if (bypass) { add('ci_changed', rel, bypass); continue; }
|
|
438
|
+
// BP_3131: the gate now runs in fewer cases (triggers narrowed, or a new if: on the BuildProof job / step)
|
|
439
|
+
const narrowed = triggerNarrowed(before || '', after || '');
|
|
440
|
+
if (narrowed) { add('ci_changed', rel, narrowed); continue; }
|
|
312
441
|
if (changedStep && !wd.added.some((l) => /buildproof\s+ci\b/i.test(l) && !/\|\||continue-on-error/i.test(l))) { add('ci_changed', rel, 'BuildProof step changed: ' + changedStep); continue; }
|
|
313
442
|
continue;
|
|
314
443
|
}
|
|
@@ -408,6 +537,12 @@ function analyze({ root, beforeDir, changes, testFiles }) {
|
|
|
408
537
|
// a partial mock keeps the real module (requireActual / importActual inside the factory, often on the next lines)
|
|
409
538
|
if (i >= 0 && !/requireActual|importActual|importOriginal/.test(d.added.slice(i, i + 6).join('\n'))) mock = d.added[i];
|
|
410
539
|
}
|
|
540
|
+
// BP_3131: the same checks on whole mock calls, so a call wrapped over several lines counts too
|
|
541
|
+
if (!mock && c.kind === 'added' && /\.(c|m)?[jt]sx?$/i.test(rel)) {
|
|
542
|
+
const vv = codeViews(after || '', false);
|
|
543
|
+
for (const mc of mockCalls(vv.code, vv.blank)) { const one = mc.text.replace(/\s*\.\s*/g, '.'); if (!mc.partial && mocksChangedModule(one, changedCode, rel)) { mock = one.slice(0, 160); break; } }
|
|
544
|
+
if (!mock) mock = mockOnlyNewTest(after || '', (changes || []).filter((x) => x.kind !== 'deleted' && !isTestFile(x.file)).map((x) => x.file), rel, root);
|
|
545
|
+
}
|
|
411
546
|
if (mock) add('mock_added', rel, mock);
|
|
412
547
|
// the test overrides the very code under test (c.discount = ..., {...real, discount: ...}, rebinding an imported function)
|
|
413
548
|
const patched = patchesCode(d.added, (before || '') + '\n' + (after || ''), rel, changedCode, root); // imports from before too: dropping an import and redefining the name is the same trick
|
|
@@ -534,6 +669,243 @@ function mocksChangedModule(line, changed, testRel = '') {
|
|
|
534
669
|
return false;
|
|
535
670
|
}
|
|
536
671
|
|
|
672
|
+
// ---------- BP_3131 rule 2: the workflow that runs BuildProof now runs in FEWER cases ----------
|
|
673
|
+
// Only the top-level `on:` block counts (docker `tags:` in a step do not). Filters are compared as sets, so reordering,
|
|
674
|
+
// quoting, flow <-> block style and adding branches / events (broadening) are fine. Narrowing is flagged:
|
|
675
|
+
// a gate event (push / pull_request ...) removed, a branch / tag / path filter added or an entry removed from it,
|
|
676
|
+
// an -ignore entry added, a `types:` filter added or narrowed.
|
|
677
|
+
const GATE_EVENTS = new Set(['push', 'pull_request', 'pull_request_target', 'merge_group']);
|
|
678
|
+
|
|
679
|
+
function yamlStripComment(l) {
|
|
680
|
+
let q = null;
|
|
681
|
+
for (let i = 0; i < l.length; i++) {
|
|
682
|
+
const c = l[i];
|
|
683
|
+
if (q) { if (c === '\\' && q === '"') { i++; continue; } if (c === q) q = null; continue; }
|
|
684
|
+
if (c === '"' || c === "'") { q = c; continue; }
|
|
685
|
+
if (c === '#' && (i === 0 || /\s/.test(l[i - 1]))) return l.slice(0, i);
|
|
686
|
+
}
|
|
687
|
+
return l;
|
|
688
|
+
}
|
|
689
|
+
function yamlScalar(s) {
|
|
690
|
+
s = String(s).trim();
|
|
691
|
+
if (/^".*"$/.test(s)) { try { return JSON.parse(s); } catch { return s.slice(1, -1); } }
|
|
692
|
+
if (/^'.*'$/.test(s)) return s.slice(1, -1).replace(/''/g, "'");
|
|
693
|
+
return s;
|
|
694
|
+
}
|
|
695
|
+
/** Tiny flow-style parser: {a: [x, 'y'], b: {c: z}} */
|
|
696
|
+
function yamlFlow(src) {
|
|
697
|
+
let i = 0; const s = String(src);
|
|
698
|
+
const ws = () => { while (i < s.length && /\s/.test(s[i])) i++; };
|
|
699
|
+
const scalar = (stops) => {
|
|
700
|
+
ws(); if (s[i] === '"' || s[i] === "'") { const q = s[i]; let j = i + 1; while (j < s.length && s[j] !== q) { if (s[j] === '\\' && q === '"') j++; j++; } const r = yamlScalar(s.slice(i, j + 1)); i = j + 1; return r; }
|
|
701
|
+
let j = i; while (j < s.length && !stops.includes(s[j])) j++; const r = s.slice(i, j).trim(); i = j; return r;
|
|
702
|
+
};
|
|
703
|
+
const value = () => {
|
|
704
|
+
ws();
|
|
705
|
+
if (s[i] === '[') { i++; const arr = []; ws(); if (s[i] === ']') { i++; return arr; } for (;;) { arr.push(value()); ws(); if (s[i] === ',') { i++; ws(); if (s[i] === ']') { i++; return arr; } continue; } if (s[i] === ']') { i++; return arr; } throw new Error('flow list'); } }
|
|
706
|
+
if (s[i] === '{') { i++; const obj = {}; ws(); if (s[i] === '}') { i++; return obj; } for (;;) { const k = scalar([':', ',', '}']); ws(); let v = null; if (s[i] === ':') { i++; ws(); v = (s[i] === ',' || s[i] === '}') ? null : value(); } obj[k] = v; ws(); if (s[i] === ',') { i++; ws(); if (s[i] === '}') { i++; return obj; } continue; } if (s[i] === '}') { i++; return obj; } throw new Error('flow map'); } }
|
|
707
|
+
const r = scalar([',', ']', '}']); return r === '' ? null : r;
|
|
708
|
+
};
|
|
709
|
+
const v = value(); ws(); if (i < s.length) throw new Error('flow trailing'); return v;
|
|
710
|
+
}
|
|
711
|
+
/** Block-style YAML (mappings, lists, inline flow values) - enough for a workflow `on:` block. */
|
|
712
|
+
function yamlBlock(L, from, to) {
|
|
713
|
+
const ind = (l) => (l.match(/^ */) || [''])[0].length;
|
|
714
|
+
let i = from;
|
|
715
|
+
const next = () => { while (i < to && !L[i].trim()) i++; return i; };
|
|
716
|
+
const inline = (v) => { v = v.trim(); if (!v) return undefined; if (/^[[{]/.test(v)) return yamlFlow(v); if (/^[|>][-+0-9]*$/.test(v)) { const d0 = i > 0 ? ind(L[i - 1]) : 0; while (i < to && (!L[i].trim() || ind(L[i]) > d0)) i++; return ''; } return yamlScalar(v); };
|
|
717
|
+
const node = (minInd) => {
|
|
718
|
+
next(); if (i >= to) return null;
|
|
719
|
+
const d = ind(L[i]); if (d < minInd) return null;
|
|
720
|
+
if (/^\s*-(\s|$)/.test(L[i])) {
|
|
721
|
+
const arr = [];
|
|
722
|
+
while (next() < to && ind(L[i]) === d && /^\s*-(\s|$)/.test(L[i])) {
|
|
723
|
+
const rest = L[i].replace(/^\s*-\s?/, ''); i++;
|
|
724
|
+
const mm = rest.trim().match(/^("[^"]*"|'[^']*'|[^'"[{:][^:]*?)\s*:(?:\s+(.*)|$)/);
|
|
725
|
+
if (mm) { // `- cron: '0 1 * * *'` (+ more keys below): a one-line map
|
|
726
|
+
const o = {}; const v0 = inline(mm[2] || ''); o[yamlScalar(mm[1])] = v0 === undefined ? null : v0;
|
|
727
|
+
if (next() < to && ind(L[i]) > d && !/^\s*-(\s|$)/.test(L[i])) Object.assign(o, node(ind(L[i])) || {});
|
|
728
|
+
arr.push(o); continue;
|
|
729
|
+
}
|
|
730
|
+
const v = inline(rest); arr.push(v === undefined ? node(d + 1) : v);
|
|
731
|
+
}
|
|
732
|
+
return arr;
|
|
733
|
+
}
|
|
734
|
+
const obj = {};
|
|
735
|
+
while (next() < to && ind(L[i]) === d) {
|
|
736
|
+
const m = L[i].trim().match(/^("[^"]*"|'[^']*'|[^:]+?)\s*:(?:\s+(.*)|$)/);
|
|
737
|
+
if (!m) throw new Error('not a map line');
|
|
738
|
+
i++;
|
|
739
|
+
const k = yamlScalar(m[1]); let raw = m[2] || '';
|
|
740
|
+
if (/^\s*[[{]/.test(raw)) { // a flow list / map continued over several lines
|
|
741
|
+
const bal = (t) => { let d = 0, q = null; for (const ch of t) { if (q) { if (ch === q) q = null; continue; } if (ch === '"' || ch === "'") q = ch; else if ('[{'.includes(ch)) d++; else if (']}'.includes(ch)) d--; } return d; };
|
|
742
|
+
let n = 0; while (bal(raw) > 0 && i < to && n++ < 2000) raw += ' ' + L[i++].trim();
|
|
743
|
+
}
|
|
744
|
+
const v = inline(raw);
|
|
745
|
+
if (v !== undefined) { obj[k] = v; continue; }
|
|
746
|
+
next();
|
|
747
|
+
obj[k] = i < to && (ind(L[i]) > d || (ind(L[i]) === d && /^\s*-(\s|$)/.test(L[i]))) ? node(ind(L[i])) : null;
|
|
748
|
+
}
|
|
749
|
+
return obj;
|
|
750
|
+
};
|
|
751
|
+
return node(0);
|
|
752
|
+
}
|
|
753
|
+
/** The parsed `on:` value of a workflow, or { raw } when it cannot be read with confidence. null = no `on:`. */
|
|
754
|
+
function workflowOn(yaml) {
|
|
755
|
+
const L = lines(yaml).map((l) => yamlStripComment(l).replace(/\t/g, ' ').replace(/\s+$/, ''));
|
|
756
|
+
const k = L.findIndex((l) => /^(["']?)(on|true)\1\s*:(\s|$)/.test(l));
|
|
757
|
+
if (k < 0) return null;
|
|
758
|
+
let e = k + 1; while (e < L.length && (!L[e].trim() || /^\s/.test(L[e]) || /^-(\s|$)/.test(L[e]))) e++;
|
|
759
|
+
const head = L[k].replace(/^(["']?)(on|true)\1\s*:/, '').trim();
|
|
760
|
+
const raw = norm([head, ...L.slice(k + 1, e)].join(' '));
|
|
761
|
+
if (/(^|[\s,[{:])[&*][\w-]+|<<\s*:/.test(raw)) return { raw }; // anchors / aliases: compare the text only
|
|
762
|
+
try { return { v: head ? yamlFlow(head) : yamlBlock(L, k + 1, e), raw }; } catch { return { raw }; }
|
|
763
|
+
}
|
|
764
|
+
function onEvents(v) {
|
|
765
|
+
const out = new Map();
|
|
766
|
+
if (typeof v === 'string') out.set(v, {});
|
|
767
|
+
else if (Array.isArray(v)) for (const x of v) { if (typeof x === 'string') out.set(x, {}); }
|
|
768
|
+
else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) out.set(k, x && typeof x === 'object' && !Array.isArray(x) ? x : {});
|
|
769
|
+
return out;
|
|
770
|
+
}
|
|
771
|
+
const asSet = (x) => x == null ? null : new Set((Array.isArray(x) ? x : [x]).map((s) => String(s).trim()));
|
|
772
|
+
/** Returns a short reason when the trigger set got smaller, else null. */
|
|
773
|
+
function triggerNarrowed(before, after) {
|
|
774
|
+
const b = workflowOn(before), a = workflowOn(after);
|
|
775
|
+
if (!b) return null;
|
|
776
|
+
if (!a) return 'the `on:` triggers were removed';
|
|
777
|
+
if (b.v === undefined || a.v === undefined) return null; // cannot read it with confidence: no alarm
|
|
778
|
+
const eb = onEvents(b.v), ea = onEvents(a.v);
|
|
779
|
+
if (ea.has('workflow_call') && !eb.has('workflow_call')) return null; // turned into a reusable workflow: its callers decide
|
|
780
|
+
const glob = (g) => new RegExp('^' + String(g).replace(/[.+^${}()|\\[\]]/g, '\\$&').replace(/\*\*/g, '\u0000').replace(/\*/g, '[^/]*').replace(/\u0000/g, '.*').replace(/\?/g, '.') + '$');
|
|
781
|
+
const globsOf = new Map(); // compiled once per set
|
|
782
|
+
const covered = (x, set) => {
|
|
783
|
+
if (set.has(x)) return true;
|
|
784
|
+
let gs = globsOf.get(set); if (!gs) { gs = [...set].filter((g) => !String(g).startsWith('!') && /[*?]/.test(g)).slice(0, 200).map(glob); globsOf.set(set, gs); }
|
|
785
|
+
return gs.some((r) => r.test(x));
|
|
786
|
+
};
|
|
787
|
+
const everything = (set) => set && [...set].some((g) => g === '**') && ![...set].some((g) => String(g).startsWith('!'));
|
|
788
|
+
const PR_DEFAULT_TYPES = ['opened', 'synchronize', 'reopened'];
|
|
789
|
+
for (const [ev, fb] of eb) {
|
|
790
|
+
if (!ea.has(ev)) {
|
|
791
|
+
const twin = ev === 'pull_request' ? 'pull_request_target' : ev === 'pull_request_target' ? 'pull_request' : null;
|
|
792
|
+
if (twin && ea.has(twin) && !eb.has(twin)) continue; // pull_request <-> pull_request_target: still runs on every PR
|
|
793
|
+
if (GATE_EVENTS.has(ev)) return 'CI trigger removed: ' + ev; continue;
|
|
794
|
+
}
|
|
795
|
+
if (!GATE_EVENTS.has(ev)) continue; // release / issue_comment / workflow_run ... do not run the gate on code changes
|
|
796
|
+
const fa = ea.get(ev);
|
|
797
|
+
for (const key of ['branches', 'tags', 'paths', 'types']) {
|
|
798
|
+
const sb = asSet(fb[key]), sa = asSet(fa[key]);
|
|
799
|
+
if (sa && !sb && key === 'types' && /^pull_request/.test(ev) && PR_DEFAULT_TYPES.every((t) => sa.has(t))) continue; // covers GitHub's defaults
|
|
800
|
+
if (sa && !sb && key !== 'types' && everything(sa)) continue; // '**' = all refs / paths
|
|
801
|
+
if (sa && !sb && key !== 'types' && fb[key + '-ignore'] != null) { // branches-ignore: [x] -> branches: ['**', '!x']
|
|
802
|
+
const ig = asSet(fb[key + '-ignore']); const negs = new Set([...sa].filter((x) => String(x).startsWith('!')).map((x) => String(x).slice(1)));
|
|
803
|
+
if ([...sa].some((g) => g === '**') && [...negs].every((x) => ig.has(x))) continue;
|
|
804
|
+
}
|
|
805
|
+
if (sa && !sb) {
|
|
806
|
+
// GitHub: with only a tags filter a push no longer runs for branches (and the reverse). If the other kind of
|
|
807
|
+
// ref filter already existed, adding this one only adds cases (broadening).
|
|
808
|
+
const other = key === 'branches' ? ['tags', 'tags-ignore'] : key === 'tags' ? ['branches', 'branches-ignore'] : [];
|
|
809
|
+
if (!other.some((o) => fb[o] != null)) return `CI trigger filter added: ${ev}.${key}: [${[...sa].join(', ')}]`;
|
|
810
|
+
}
|
|
811
|
+
if (sb && sa) {
|
|
812
|
+
const gone = [...sb].filter((x) => !String(x).startsWith('!') && !covered(x, sa)); if (gone.length) return `CI trigger filter narrowed: ${ev}.${key} lost ${gone.join(', ')}`;
|
|
813
|
+
const neg = [...sa].filter((x) => String(x).startsWith('!') && !sb.has(x)); if (neg.length) return `CI trigger filter narrowed: ${ev}.${key} added ${neg.join(', ')}`;
|
|
814
|
+
}
|
|
815
|
+
if (sb && !sa && (key === 'branches' || key === 'tags')) { // dropping one ref filter while the other stays: those refs stop running
|
|
816
|
+
const other = key === 'branches' ? ['tags', 'tags-ignore'] : ['branches', 'branches-ignore'];
|
|
817
|
+
if (other.some((o) => fa[o] != null)) return `CI trigger filter narrowed: ${ev}.${key} removed`;
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
for (const key of ['branches-ignore', 'tags-ignore', 'paths-ignore']) {
|
|
821
|
+
const sb = asSet(fb[key]) || new Set(), sa = asSet(fa[key]) || new Set();
|
|
822
|
+
const extra = [...sa].filter((x) => !sb.has(x));
|
|
823
|
+
if (extra.length) return `CI trigger filter narrowed: ${ev}.${key} added ${extra.join(', ')}`;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
return null;
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// ---------- BP_3131 rule 3: a NEW test file that only talks to mocks of the changed code ----------
|
|
830
|
+
// Flagged only when the new JS/TS test fully mocks code changed in this change AND loads no project code for real.
|
|
831
|
+
// A new test that mocks changed ./db but runs the real ./service (changed or not) is ordinary and stays fine.
|
|
832
|
+
// Anything we cannot resolve (an alias, a computed require path) means "maybe real code": not flagged.
|
|
833
|
+
const BUILTINS = new Set(require('module').builtinModules);
|
|
834
|
+
const TEST_LIBS = /^(vitest|jest|@jest\/globals|mocha|chai|sinon|ava|tap|uvu|expect|supertest|nock|msw|react|react-dom|@testing-library\/[\w-]+|@vue\/test-utils|@playwright\/test|@vitest\/[\w-]+)$/;
|
|
835
|
+
const _deps = new Map();
|
|
836
|
+
function declaredDeps(root) { // the packages the project itself declares (outside packages, not its own code)
|
|
837
|
+
if (!root) return new Set(); if (_deps.has(root)) return _deps.get(root);
|
|
838
|
+
let set = new Set();
|
|
839
|
+
try { const pj = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); set = new Set(Object.keys({ ...(pj.dependencies || {}), ...(pj.devDependencies || {}), ...(pj.peerDependencies || {}) })); if (pj.workspaces) for (const k of [...set]) { /* workspace deps may be local */ } } catch {}
|
|
840
|
+
if (_deps.size > 50) _deps.clear(); _deps.set(root, set); return set;
|
|
841
|
+
}
|
|
842
|
+
const MOCK_CALL_RE = /\b(?:jest|vi)\s*\.\s*(?:mock|doMock|unstable_mockModule|setMock)\s*\(|\bmock\s*\.\s*module\s*\(/g;
|
|
843
|
+
|
|
844
|
+
function mockCalls(code, blank) {
|
|
845
|
+
const out = []; let m; MOCK_CALL_RE.lastIndex = 0;
|
|
846
|
+
while ((m = MOCK_CALL_RE.exec(blank)) && out.length < 300) {
|
|
847
|
+
const open = m.index + m[0].length; let d = 1, k = open; const lim = Math.min(blank.length, open + 20000);
|
|
848
|
+
for (; k < lim && d > 0; k++) { if (blank[k] === '(') d++; else if (blank[k] === ')') d--; }
|
|
849
|
+
const args = code.slice(open, k - 1);
|
|
850
|
+
const spec = args.match(/^\s*(?:import\s*\(\s*|require\s*\.\s*resolve\s*\(\s*)?(['"`])([^'"`$\n]+)\1/);
|
|
851
|
+
const argsBlank = blank.slice(open, k - 1);
|
|
852
|
+
const partial = (/\b(requireActual|importActual)\s*\(|\bimportOriginal\s*\(/.test(argsBlank) || /\bspy\s*:\s*true\b/.test(args)) && !/\bsetMock\b/.test(m[0]); // vi.mock(p, { spy: true }) keeps the real code
|
|
853
|
+
out.push({ start: m.index, end: k, spec: spec ? spec[2] : null, partial, text: code.slice(m.index, k).replace(/\s+/g, ' ') });
|
|
854
|
+
}
|
|
855
|
+
return out;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
function mockOnlyNewTest(src, changedFiles, testRel, root) {
|
|
859
|
+
const t = String(testRel).replace(/\\/g, '/');
|
|
860
|
+
if (!/\.(c|m)?[jt]sx?$/i.test(t)) return null;
|
|
861
|
+
const strip = (f) => f.replace(/\\/g, '/').replace(/\.(c|m)?[jt]sx?$/i, '').replace(/\/index$/i, '').toLowerCase();
|
|
862
|
+
const changed = new Set(changedFiles.filter((f) => /\.(c|m)?[jt]sx?$/i.test(f)).map(strip));
|
|
863
|
+
if (!changed.size) return null;
|
|
864
|
+
const { code, blank } = codeViews(src, false);
|
|
865
|
+
const calls = mockCalls(code, blank);
|
|
866
|
+
if (!calls.length) return null;
|
|
867
|
+
const rel = (spec) => strip(path.posix.normalize(path.posix.join(path.posix.dirname(t), spec)));
|
|
868
|
+
const full = new Map();
|
|
869
|
+
for (const c of calls) {
|
|
870
|
+
if (!c.spec) return null; // a computed path: cannot tell
|
|
871
|
+
if (c.partial || !/^[./]/.test(c.spec)) continue;
|
|
872
|
+
const tg = rel(c.spec); if (changed.has(tg) && !full.has(tg)) full.set(tg, c.text.slice(0, 160));
|
|
873
|
+
}
|
|
874
|
+
if (!full.size) return null;
|
|
875
|
+
// what the test loads, with the mock calls themselves blanked out (vi.mock(import('./db')) is not a real import)
|
|
876
|
+
let b = blank, c2 = code;
|
|
877
|
+
for (const c of calls) { b = b.slice(0, c.start) + ' '.repeat(c.end - c.start) + b.slice(c.end); c2 = c2.slice(0, c.start) + ' '.repeat(c.end - c.start) + c2.slice(c.end); }
|
|
878
|
+
const specs = []; let m;
|
|
879
|
+
const dyn = /\b(require|import)\s*\(/g;
|
|
880
|
+
while ((m = dyn.exec(b))) {
|
|
881
|
+
if (m[1] === 'require' && /\.\s*$/.test(b.slice(0, m.index))) continue;
|
|
882
|
+
const a = c2.slice(m.index + m[0].length).match(/^\s*(['"`])([^'"`$\n]+)\1\s*\)/);
|
|
883
|
+
if (!a) return null; // require(path.join(...)), import(x): cannot tell
|
|
884
|
+
specs.push(a[2]);
|
|
885
|
+
}
|
|
886
|
+
// jest.requireActual('./db') outside a mock factory loads the real code
|
|
887
|
+
const act = /\b(?:jest|vi)\s*\.\s*(?:requireActual|importActual)\s*(?:<[^>]*>)?\s*\(/g;
|
|
888
|
+
while ((m = act.exec(b))) return null;
|
|
889
|
+
const stat = /(^|[;\n])[ \t]*(import|export)\b([^;'"`]{0,2000}?)\bfrom[ \t]*(['"`])([^'"`\n]+)\4|(^|[;\n])[ \t]*import[ \t]*(['"`])([^'"`\n]+)\7/g;
|
|
890
|
+
while ((m = stat.exec(c2))) {
|
|
891
|
+
if (m[5]) { if (/^\s*type\b/.test(m[3] || '')) continue; specs.push(m[5]); } else specs.push(m[8]);
|
|
892
|
+
}
|
|
893
|
+
for (const s of specs) {
|
|
894
|
+
if (/^[./]/.test(s)) { if (!full.has(rel(s))) return null; continue; } // real project code is loaded
|
|
895
|
+
if (/^node:/.test(s) || BUILTINS.has(s.split('/')[0])) continue;
|
|
896
|
+
if (/^[a-z@]/i.test(s) && !/^[@~#]\//.test(s)) {
|
|
897
|
+
// counts as an outside package only when it is really installed (not a workspace link, not a path alias)
|
|
898
|
+
const pkg = s.startsWith('@') ? s.split('/').slice(0, 2).join('/') : s.split('/')[0];
|
|
899
|
+
if (TEST_LIBS.test(pkg) || declaredDeps(root).has(pkg)) continue;
|
|
900
|
+
let st = null; try { st = root ? fs.lstatSync(path.join(root, 'node_modules', pkg)) : null; } catch { st = null; }
|
|
901
|
+
if (!st || st.isSymbolicLink()) return null;
|
|
902
|
+
continue;
|
|
903
|
+
}
|
|
904
|
+
return null; // @/x, ~/x, #x: an alias into the project, cannot tell
|
|
905
|
+
}
|
|
906
|
+
return [...full.values()][0];
|
|
907
|
+
}
|
|
908
|
+
|
|
537
909
|
function addedMatch(before, after, re) {
|
|
538
910
|
const g = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g');
|
|
539
911
|
const mb = (before.match(g) || []).map(norm);
|
package/core/license.js
CHANGED
|
@@ -17,7 +17,7 @@ const GRACE_DAYS = 3;
|
|
|
17
17
|
const DAY = 864e5;
|
|
18
18
|
|
|
19
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, F.certificates]; // signed certificates are what sets BuildProof apart: in every paid plan
|
|
20
|
+
const BASIC = [F.guard, F.hooks, F.certificates, F.revertCheck, F.claims]; // 3.14: Basic also checks what the AI claims, and has 3 bug hunts a month (counted on the server) // signed certificates are what sets BuildProof apart: in every paid plan
|
|
21
21
|
const PRO = [...BASIC, F.certificates, F.remote, F.revertCheck, F.claims, F.aiFix, F.spec];
|
|
22
22
|
const TEAM = [...PRO, F.ci, F.verifyPage, F.dashboard];
|
|
23
23
|
const PLANS = {
|
|
@@ -112,8 +112,10 @@ function onlineTrial(){
|
|
|
112
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{}
|
|
113
113
|
const device=deviceId();
|
|
114
114
|
const url=new URL('/api/trial/start',base).href;
|
|
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
|
|
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,ev:process.argv[3]||'',v:process.argv[4]||''}))";
|
|
116
|
+
const ev=String(global.__bpTrialEv||process.argv[2]&&!/[\\/]/.test(process.argv[2])&&process.argv[2]||'service').replace(/[^a-z-]/gi,'').slice(0,20).toLowerCase();
|
|
117
|
+
let ver='';try{ver=require('../package.json').version}catch{}
|
|
118
|
+
const r=cp.spawnSync(process.execPath,['-e',childCode,url,device,ev,ver],{encoding:'utf8',timeout:3500,windowsHide:true});
|
|
117
119
|
let result=null;
|
|
118
120
|
if(r.status===0&&!r.error){try{result=JSON.parse(r.stdout)}catch{result=null}}
|
|
119
121
|
if(!result){ // server unreachable: use the local trial clock, never lock a user out because of the network
|
|
@@ -143,7 +145,7 @@ function status() {
|
|
|
143
145
|
const online=onlineTrial();
|
|
144
146
|
if(online){
|
|
145
147
|
const left=online.daysLeft;
|
|
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}:{}) };
|
|
148
|
+
return { status:online.status, plan:'trial',label:'Trial',daysLeft:left,trialStarted:online.started||null,hasEmail:online.hasEmail===true,projects:PLANS.trial.projects,features:online.status==='trial'?PLANS.trial.features:[], ...(online.reason?{reason:online.reason}:{}) };
|
|
147
149
|
}
|
|
148
150
|
const start = trialStart();
|
|
149
151
|
const left = Math.max(0, Math.ceil((start + TRIAL_DAYS * DAY - Math.max(now, start)) / DAY));
|
|
@@ -188,4 +190,16 @@ function publicInfo() {
|
|
|
188
190
|
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 };
|
|
189
191
|
}
|
|
190
192
|
|
|
191
|
-
|
|
193
|
+
/** BP_TRIAL_CARE: an optional email for the trial (a reminder before it ends, and 2 questions after). The server sends a confirmation link first. */
|
|
194
|
+
function trialEmail(email){
|
|
195
|
+
const cfg=require('./config').load();
|
|
196
|
+
const base=process.env.MGR_TRIAL_SERVER||cfg.licenseServer;
|
|
197
|
+
if(!base)return Promise.resolve({ok:false,error:'no_server'});
|
|
198
|
+
const u=new URL('/api/trial/email',base);const m=u.protocol==='https:'?require('https'):require('http');
|
|
199
|
+
return new Promise((resolve)=>{
|
|
200
|
+
const r=m.request(u,{method:'POST',headers:{'content-type':'application/json'},timeout:8000},(s)=>{let b='';s.on('data',(x)=>b+=x);s.on('end',()=>{try{resolve(JSON.parse(b))}catch{resolve({ok:false,error:'bad_answer_'+s.statusCode})}})});
|
|
201
|
+
r.on('timeout',()=>r.destroy(Error('timeout')));r.on('error',(e)=>resolve({ok:false,error:String(e.message||e)}));
|
|
202
|
+
r.end(JSON.stringify({device:deviceId(),email:String(email||'').trim()}));
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
module.exports = { trialEmail, deviceId, status, has, currentKey, activate, renew, parseKey, signKey, publicInfo, PLANS, F, TRIAL_DAYS };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "buildproof",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.14.0",
|
|
4
4
|
"description": "BuildProof - proof gate for AI-written code: test-integrity guard, fail-closed checks, scope lock, full rollback, signed certificates, local AI under supervision.",
|
|
5
5
|
"main": "core/server.js",
|
|
6
6
|
"scripts": {
|