buildproof 3.13.0 → 3.13.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/core/integrity.js +374 -2
- package/package.json +1 -1
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "buildproof",
|
|
3
|
-
"version": "3.13.
|
|
3
|
+
"version": "3.13.1",
|
|
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": {
|