veristack 0.1.0 → 0.1.2
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 +56 -65
- package/dist/cli.mjs +917 -101
- package/lint/index.mjs +91 -0
- package/package.json +3 -1
- package/skill/SKILL.md +61 -57
- package/skill/agents/openai.yaml +1 -1
- package/skill/references/02-linter-and-antislop-stack.md +2 -1
- package/skill/references/04-source-patterns-digest.md +1 -0
package/dist/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/cli.ts
|
|
2
|
-
import
|
|
2
|
+
import fs10 from "node:fs";
|
|
3
3
|
|
|
4
4
|
// src/ci-auditor.ts
|
|
5
5
|
import { spawnSync } from "node:child_process";
|
|
@@ -16,7 +16,7 @@ var RUST_USE = /^\s*use\s+([A-Za-z_][A-Za-z0-9_]*)::/gm;
|
|
|
16
16
|
var RUST_FRAMEWORK_USE = /^(?:std|core|alloc|proptest|rstest|tokio|serde|serde_json|wiremock|mockito|mockall|stateright)$/;
|
|
17
17
|
var PY_IMPORT = /^\s*(?:from\s+([A-Za-z_][A-Za-z0-9_.]*)\s+import|import\s+([A-Za-z_][A-Za-z0-9_.]*))/gm;
|
|
18
18
|
var PY_FRAMEWORK_IMPORT = /^(?:pytest|unittest|hypothesis|mock|respx|httpx|json|os|sys|re|math|time|datetime|pathlib|collections|dataclasses|typing|random|functools|itertools|tempfile|subprocess|asyncio|inspect)$/;
|
|
19
|
-
var CSHARP_PARENT_NS_TEST = /^\s*namespace\s+[A-Za-z_][A-Za-z0-9_.]*\.(?:Tests?|Specs?)\b/m;
|
|
19
|
+
var CSHARP_PARENT_NS_TEST = /^\s*namespace\s+[A-Za-z_][A-Za-z0-9_.]*\.(?:Unit|Integration|Functional|Component)?(?:Tests?|Specs?)\b/m;
|
|
20
20
|
var CSHARP_FRAMEWORK_TYPE = /^(?:Assert|Fact|Theory|Task|DateTime|DateTimeOffset|TimeSpan|Random|Thread|Environment|JsonSerializer|File|Path|Guid|Console|Math|String|Enumerable|List|Dictionary|HashSet|Array|Object|Exception|InvalidOperationException|ArgumentException|StringComparison|CancellationToken|HttpStatusCode|Stopwatch|Mock|Substitute)$/;
|
|
21
21
|
var VITEST_CONFIG_FILE = /^(?:vitest|vite)\.config\.[cm]?[jt]s$/i;
|
|
22
22
|
var PINS_UTC = /\benv\s*:\s*\{[^}]*\bTZ\s*:\s*["']UTC["']/;
|
|
@@ -204,12 +204,22 @@ function hasNonFrameworkImport(raw, language) {
|
|
|
204
204
|
return true;
|
|
205
205
|
}
|
|
206
206
|
if (CSHARP_PARENT_NS_TEST.test(raw)) {
|
|
207
|
-
const masked =
|
|
207
|
+
const masked = maskCode(raw, "csharp");
|
|
208
208
|
for (const match of masked.matchAll(/\bnew\s+([A-Z][A-Za-z0-9_]*)\s*[<(]/g)) {
|
|
209
209
|
const typeName = match[1] ?? "";
|
|
210
210
|
if (!CSHARP_FRAMEWORK_TYPE.test(typeName))
|
|
211
211
|
return true;
|
|
212
212
|
}
|
|
213
|
+
for (const match of masked.matchAll(/\b([A-Z][A-Za-z0-9_]*)\.[A-Z][A-Za-z0-9_]*\s*[<(]/g)) {
|
|
214
|
+
const typeName = match[1] ?? "";
|
|
215
|
+
if (!CSHARP_FRAMEWORK_TYPE.test(typeName))
|
|
216
|
+
return true;
|
|
217
|
+
}
|
|
218
|
+
for (const match of masked.matchAll(/\bclass\s+[A-Za-z0-9_]+\s*:\s*([A-Z][A-Za-z0-9_]*)/g)) {
|
|
219
|
+
const baseName = match[1] ?? "";
|
|
220
|
+
if (!CSHARP_FRAMEWORK_TYPE.test(baseName))
|
|
221
|
+
return true;
|
|
222
|
+
}
|
|
213
223
|
}
|
|
214
224
|
return false;
|
|
215
225
|
}
|
|
@@ -1831,7 +1841,7 @@ function scanGitDiffCheats(repoPath, baseRef = "HEAD") {
|
|
|
1831
1841
|
|
|
1832
1842
|
// src/circuits/index.ts
|
|
1833
1843
|
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
1834
|
-
import
|
|
1844
|
+
import path8 from "node:path";
|
|
1835
1845
|
|
|
1836
1846
|
// src/discover.ts
|
|
1837
1847
|
import fs3 from "node:fs";
|
|
@@ -2042,7 +2052,7 @@ function shouldReadText(rel) {
|
|
|
2042
2052
|
return true;
|
|
2043
2053
|
if (base === "dockerfile" || base.startsWith("dockerfile."))
|
|
2044
2054
|
return true;
|
|
2045
|
-
return base === "package.json" || base === "tsconfig.json" || base === "pyproject.toml" || base === "cargo.toml" || base === "go.mod" || base === "codeowners" || base === "agents.md" || base === "claude.md" || base === "gemini.md" || base === "skill.md" || base === "review.md" || base === "gates.md" || base === "lefthook.yml" || base === ".oxlintrc.json" || base === ".oxlintrc.jsonc" || base === "oxlint.config.ts" || base === "turbo.json" || base === "directory.build.props" || base === "directory.packages.props" || base === ".editorconfig" || base === "stryker-config.json" || base === "clippy.toml" || base === ".clippy.toml" || base === "rustfmt.toml" || base === ".rustfmt.toml" || base === "mutants.toml" || base === "ruff.toml" || base === ".ruff.toml" || base === "mypy.ini" || base === "pyrightconfig.json" || base === "pytest.ini" || base === "control-plan.json" || base === "escapes.json" || base.endsWith(".csproj") || base.endsWith(".tla") || base.endsWith(".qnt") || base.endsWith(".als") || base.endsWith(".dfy") || base.endsWith(".lean") || base.endsWith(".feature") || /^(?:vitest|vite)\.config\.[cm]?[jt]s$/.test(base);
|
|
2055
|
+
return base === "package.json" || base === "tsconfig.json" || base === "pyproject.toml" || base === "cargo.toml" || base === "go.mod" || base === "codeowners" || base === "agents.md" || base === "claude.md" || base === "gemini.md" || base === ".cursorrules" || base === "copilot-instructions.md" || base === "skill.md" || base === "review.md" || base === "gates.md" || base === "lefthook.yml" || base === ".oxlintrc.json" || base === ".oxlintrc.jsonc" || base === "oxlint.config.ts" || base === "turbo.json" || base === "directory.build.props" || base === "directory.packages.props" || base === ".editorconfig" || base === "stryker-config.json" || base === "clippy.toml" || base === ".clippy.toml" || base === "rustfmt.toml" || base === ".rustfmt.toml" || base === "mutants.toml" || base === "ruff.toml" || base === ".ruff.toml" || base === "mypy.ini" || base === "pyrightconfig.json" || base === "pytest.ini" || base === "control-plan.json" || base === "escapes.json" || base.endsWith(".csproj") || base.endsWith(".tla") || base.endsWith(".qnt") || base.endsWith(".als") || base.endsWith(".dfy") || base.endsWith(".lean") || base.endsWith(".feature") || /^(?:vitest|vite)\.config\.[cm]?[jt]s$/.test(base);
|
|
2046
2056
|
}
|
|
2047
2057
|
function readSafe(abs) {
|
|
2048
2058
|
try {
|
|
@@ -2169,8 +2179,10 @@ function discoverRepo(repoPath) {
|
|
|
2169
2179
|
`);
|
|
2170
2180
|
const configText = files.filter((f) => !f.isTest && (!f.language && !f.rel.toLowerCase().endsWith(".md") || f.rel.includes("config") || f.isWorkflow)).map((f) => f.content).join(`
|
|
2171
2181
|
`);
|
|
2172
|
-
const
|
|
2173
|
-
|
|
2182
|
+
const manifestText = files.filter((f) => !f.isTest && !f.isWorkflow && !f.language && !f.rel.toLowerCase().endsWith(".md")).map((f) => f.content).join(`
|
|
2183
|
+
`);
|
|
2184
|
+
const hasReactOrUi = /(?:["'](?:react|next|vue|svelte|@angular\/core|solid-js)["']|\b(?:react-dom|next\.config)\b)/i.test(manifestText) || lowerPaths.some((p) => p.endsWith(".tsx") || p.endsWith(".jsx") || p.endsWith(".vue") || p.endsWith(".svelte"));
|
|
2185
|
+
const hasBackendService = /\b(?:express|fastify|hono|nestjs|koa|fastapi|django|flask|actix-web|axum|gin-gonic|microsoft\.aspnetcore)\b/i.test(manifestText) || files.some((f) => f.language === "csharp" && !f.isTest && /\bWebApplication\.CreateBuilder\b/.test(f.content)) || lowerPaths.some((p) => p.includes("dockerfile") || p.includes("controllers/") || p.includes("routes/"));
|
|
2174
2186
|
let archetype = "library";
|
|
2175
2187
|
if (hasReactOrUi && hasBackendService)
|
|
2176
2188
|
archetype = "fullstack";
|
|
@@ -2224,10 +2236,176 @@ function discoverRepo(repoPath) {
|
|
|
2224
2236
|
|
|
2225
2237
|
// src/system1-classifier.ts
|
|
2226
2238
|
import { createHash } from "node:crypto";
|
|
2227
|
-
import
|
|
2239
|
+
import path7 from "node:path";
|
|
2228
2240
|
|
|
2229
2241
|
// src/test-analyzer.ts
|
|
2242
|
+
import path6 from "node:path";
|
|
2243
|
+
|
|
2244
|
+
// src/anti-slop/oxc-antislop-landmines.ts
|
|
2230
2245
|
import path5 from "node:path";
|
|
2246
|
+
var UNSAFE_DICT_CS = /\b(?:I?Dictionary|ConcurrentDictionary)\s*<\s*string\s*,\s*(?:object|dynamic)\s*>/g;
|
|
2247
|
+
var UNSAFE_DICT_PY = /\b(?:dict|Dict|Mapping)\s*\[\s*str\s*,\s*Any\s*\]/g;
|
|
2248
|
+
var UNSAFE_DICT_GO = /\bmap\s*\[\s*string\s*\]\s*(?:any|interface\s*\{\s*\})/g;
|
|
2249
|
+
var IMPORT_SPEC_PY = /^\s*(?:from\s+([A-Za-z0-9_.]+)\s+import|import\s+([A-Za-z0-9_.]+))/gm;
|
|
2250
|
+
var UNSIGNALED_POLL_LOOP = /\bwhile\s*\(\s*(?:Date\.now\s*\(\s*\)|performance\.now\s*\(\s*\)|Stopwatch\.GetTimestamp|[A-Za-z_][A-Za-z0-9_.]*\.Elapsed(?:Milliseconds)?)\s*</g;
|
|
2251
|
+
var UNSIGNALED_POLL_PY = /\bwhile\s+(?:time\.time|time\.monotonic)\s*\(\s*\)\s*</g;
|
|
2252
|
+
var UNSIGNALED_POLL_EXPECT = /\bexpect\.poll\s*\(\s*\(\s*\)\s*=>\s*[A-Za-z_$][A-Za-z0-9_$.]*\.mock\b/g;
|
|
2253
|
+
var COLD_IMPORT_IN_TEST = /\b(?:it|test)\s*\([^{]*\{[\s\S]{0,400}?\bawait\s+import\s*\(/g;
|
|
2254
|
+
var STRICT_MSW_UNCONFIGURED = /\b(?:server|mswServer)\s*\.\s*listen\s*\(\s*\)/g;
|
|
2255
|
+
function pushFinding(findings, file, offset, rule, category, rung, severity, message, fix) {
|
|
2256
|
+
const line = lineOf(file.content, offset);
|
|
2257
|
+
findings.push({
|
|
2258
|
+
id: `AS:${rule}:${file.rel}:${line}`,
|
|
2259
|
+
rule,
|
|
2260
|
+
category,
|
|
2261
|
+
rung,
|
|
2262
|
+
severity,
|
|
2263
|
+
file: file.rel,
|
|
2264
|
+
line,
|
|
2265
|
+
message,
|
|
2266
|
+
fix
|
|
2267
|
+
});
|
|
2268
|
+
}
|
|
2269
|
+
function violatesInternalBoundary(fromRel, targetRel) {
|
|
2270
|
+
const normFrom = fromRel.replace(/\\/g, "/");
|
|
2271
|
+
const normTarget = targetRel.replace(/\\/g, "/");
|
|
2272
|
+
const parts = normTarget.split("/");
|
|
2273
|
+
const internalIdx = parts.lastIndexOf("internal");
|
|
2274
|
+
if (internalIdx <= 0)
|
|
2275
|
+
return null;
|
|
2276
|
+
const ownerPrefix = parts.slice(0, internalIdx).join("/");
|
|
2277
|
+
if (normFrom === ownerPrefix || normFrom.startsWith(`${ownerPrefix}/`))
|
|
2278
|
+
return null;
|
|
2279
|
+
return ownerPrefix;
|
|
2280
|
+
}
|
|
2281
|
+
function checkInternalBoundaryImports(file, code, ast, findings) {
|
|
2282
|
+
if ((file.language === "typescript" || file.language === "javascript") && ast) {
|
|
2283
|
+
const dir = path5.posix.dirname(file.rel.replace(/\\/g, "/"));
|
|
2284
|
+
const checkSpec = (spec, offset) => {
|
|
2285
|
+
if (!spec.startsWith("."))
|
|
2286
|
+
return;
|
|
2287
|
+
if (!spec.includes("/internal/") && !spec.endsWith("/internal"))
|
|
2288
|
+
return;
|
|
2289
|
+
const resolved = path5.posix.normalize(path5.posix.join(dir, spec));
|
|
2290
|
+
const owner = violatesInternalBoundary(file.rel, resolved);
|
|
2291
|
+
if (owner) {
|
|
2292
|
+
pushFinding(findings, file, offset, "no-cross-feature-internal-import", "structure", "R1", "error", `Cross-feature import '${spec}' reaches into '${owner}/internal/' from outside '${owner}/'.`, `Import from '${owner}' public entry point instead of reaching into '${owner}/internal/'.`);
|
|
2293
|
+
}
|
|
2294
|
+
};
|
|
2295
|
+
walkAst(ast, (node) => {
|
|
2296
|
+
if ((node.type === "ImportDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") && isAstNode(node.source) && node.source.type === "Literal" && typeof node.source.value === "string") {
|
|
2297
|
+
checkSpec(node.source.value, node.start ?? 0);
|
|
2298
|
+
} else if (node.type === "CallExpression" && isAstNode(node.callee) && node.callee.type === "Identifier" && node.callee.name === "require" && Array.isArray(node.arguments) && isAstNode(node.arguments[0]) && node.arguments[0].type === "Literal" && typeof node.arguments[0].value === "string") {
|
|
2299
|
+
checkSpec(node.arguments[0].value, node.start ?? 0);
|
|
2300
|
+
}
|
|
2301
|
+
});
|
|
2302
|
+
} else if (file.language === "python") {
|
|
2303
|
+
for (const m of code.matchAll(IMPORT_SPEC_PY)) {
|
|
2304
|
+
const mod = m[1] ?? m[2] ?? "";
|
|
2305
|
+
if (!mod.includes(".internal.") && !mod.endsWith(".internal"))
|
|
2306
|
+
continue;
|
|
2307
|
+
if (mod.startsWith("."))
|
|
2308
|
+
continue;
|
|
2309
|
+
const targetRel = mod.replace(/\./g, "/");
|
|
2310
|
+
const owner = violatesInternalBoundary(file.rel, targetRel);
|
|
2311
|
+
if (owner) {
|
|
2312
|
+
pushFinding(findings, file, m.index ?? 0, "no-cross-feature-internal-import", "structure", "R1", "error", `Cross-package Python import '${mod}' reaches into '${owner}/internal/' from outside '${owner}/'.`, `Import from '${owner.replace(/\//g, ".")}' public API instead of internal modules.`);
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
function analyzeUniversalAntiSlopProd(file, ast) {
|
|
2318
|
+
if (!file.language || file.isTest)
|
|
2319
|
+
return [];
|
|
2320
|
+
const findings = [];
|
|
2321
|
+
const raw = file.content;
|
|
2322
|
+
const code = maskCode(raw, file.language);
|
|
2323
|
+
checkInternalBoundaryImports(file, code, ast, findings);
|
|
2324
|
+
if (ast && (file.language === "typescript" || file.language === "javascript")) {
|
|
2325
|
+
let dictCount = 0;
|
|
2326
|
+
let objParamCount = 0;
|
|
2327
|
+
walkAst(ast, (node) => {
|
|
2328
|
+
if (node.type === "CallExpression" && isAstNode(node.callee) && node.callee.type === "MemberExpression") {
|
|
2329
|
+
const obj = isAstNode(node.callee.object) ? node.callee.object : null;
|
|
2330
|
+
const prop = isAstNode(node.callee.property) ? node.callee.property : null;
|
|
2331
|
+
if (obj?.type === "Identifier" && obj.name === "Reflect" && prop?.type === "Identifier" && (prop.name === "apply" || prop.name === "get" || prop.name === "set")) {
|
|
2332
|
+
pushFinding(findings, file, node.start ?? 0, "no-reflect-dynamic-invoke", "structure", "R0", "error", `Dynamic Reflect.${prop.name}() bypasses static typing and hides property/call contracts.`, "Use direct typed function calls or explicit property access / Map lookups.");
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
if (file.language === "typescript") {
|
|
2336
|
+
if (node.type === "TSTypeAliasDeclaration" && isAstNode(node.typeAnnotation)) {
|
|
2337
|
+
if (node.typeAnnotation.type === "TSUnknownKeyword" || node.typeAnnotation.type === "TSAnyKeyword") {
|
|
2338
|
+
const name = isAstNode(node.id) && typeof node.id.name === "string" ? node.id.name : "alias";
|
|
2339
|
+
pushFinding(findings, file, node.start ?? 0, "no-unknown-type-alias", "structure", "R1", "warn", `Type alias '${name}' masks '${node.typeAnnotation.type === "TSAnyKeyword" ? "any" : "unknown"}' behind a domain-sounding name.`, "Model the actual discriminated union, interface, or schema-inferred type instead of aliasing unknown/any.");
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
if (node.type === "TSTypeReference" && isAstNode(node.typeName) && node.typeName.type === "Identifier") {
|
|
2343
|
+
const refName = typeof node.typeName.name === "string" ? node.typeName.name : "";
|
|
2344
|
+
if (refName === "Record" && isAstNode(node.typeArguments) && Array.isArray(node.typeArguments.params)) {
|
|
2345
|
+
const valType = node.typeArguments.params[1];
|
|
2346
|
+
if (isAstNode(valType) && valType.type === "TSAnyKeyword" && ++dictCount <= 5) {
|
|
2347
|
+
pushFinding(findings, file, node.start ?? 0, "no-unsafe-dictionary-type", "structure", "R1", "warn", "Record<string, any> disables value type checking across every lookup.", "Use an explicit interface, Map<K, V>, or Record<K, unknown> parsed at the boundary.");
|
|
2348
|
+
}
|
|
2349
|
+
}
|
|
2350
|
+
if ((refName === "Object" || refName === "Function") && ++objParamCount <= 5) {
|
|
2351
|
+
pushFinding(findings, file, node.start ?? 0, "no-object-type-escape", "structure", "R1", "warn", `Boxed '${refName}' type accepts almost any value and disables structural type checking.`, refName === "Function" ? "Declare an explicit callable signature '(arg: A) => B' instead of 'Function'." : "Declare an explicit interface, record type, or generic constraint instead of 'Object'.");
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
});
|
|
2356
|
+
}
|
|
2357
|
+
const dictRe = file.language === "csharp" ? UNSAFE_DICT_CS : file.language === "python" ? UNSAFE_DICT_PY : file.language === "go" ? UNSAFE_DICT_GO : null;
|
|
2358
|
+
if (dictRe) {
|
|
2359
|
+
let count = 0;
|
|
2360
|
+
for (const m of code.matchAll(dictRe)) {
|
|
2361
|
+
if (++count > 5)
|
|
2362
|
+
break;
|
|
2363
|
+
pushFinding(findings, file, m.index ?? 0, "no-unsafe-dictionary-type", "structure", "R1", "warn", `Untyped string dictionary '${m[0].trim()}' discards value contracts.`, "Replace with a typed struct/record/TypedDict/dataclass or a strongly typed map value.");
|
|
2364
|
+
}
|
|
2365
|
+
}
|
|
2366
|
+
return findings;
|
|
2367
|
+
}
|
|
2368
|
+
function analyzeUniversalLandminesTest(file, code, ast) {
|
|
2369
|
+
if (!file.language || !file.isTest)
|
|
2370
|
+
return [];
|
|
2371
|
+
const findings = [];
|
|
2372
|
+
for (const m of code.matchAll(UNSIGNALED_POLL_LOOP)) {
|
|
2373
|
+
pushFinding(findings, file, m.index ?? 0, "no-unsignaled-poll", "test-smell", "R0", "error", "Clock-driven busy-poll loop in test races wall-clock deadlines and causes CI flakes.", "Await an explicit completion signal, promise, channel, or web-first locator assertion.");
|
|
2374
|
+
}
|
|
2375
|
+
if (file.language === "python") {
|
|
2376
|
+
for (const m of code.matchAll(UNSIGNALED_POLL_PY)) {
|
|
2377
|
+
pushFinding(findings, file, m.index ?? 0, "no-unsignaled-poll", "test-smell", "R0", "error", "Clock-driven busy-poll loop in Python test causes flaky timeouts.", "Wait on an asyncio.Event, threading.Event, or explicit queue completion instead.");
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
if (file.language === "typescript" || file.language === "javascript") {
|
|
2381
|
+
for (const m of code.matchAll(UNSIGNALED_POLL_EXPECT)) {
|
|
2382
|
+
pushFinding(findings, file, m.index ?? 0, "no-unsignaled-poll", "test-smell", "R0", "error", "Polling mock call state with expect.poll masks race conditions.", "Await the observable async operation or explicit event directly.");
|
|
2383
|
+
}
|
|
2384
|
+
for (const m of code.matchAll(STRICT_MSW_UNCONFIGURED)) {
|
|
2385
|
+
pushFinding(findings, file, m.index ?? 0, "strict-msw", "test-smell", "R0", "warn", "MSW server.listen() called without { onUnhandledRequest: 'error' }; unexpected HTTP calls pass silently.", "Pass server.listen({ onUnhandledRequest: 'error' }) so unhandled network calls fail immediately.");
|
|
2386
|
+
}
|
|
2387
|
+
for (const m of code.matchAll(COLD_IMPORT_IN_TEST)) {
|
|
2388
|
+
if (/\bresetModules\b/.test(m[0]))
|
|
2389
|
+
continue;
|
|
2390
|
+
pushFinding(findings, file, m.index ?? 0, "no-cold-import-in-test", "test-smell", "R0", "warn", "Dynamic await import() inside a test body pays cold-module startup cost inside the test timer.", "Move static imports to module scope so test bodies measure only behavior.");
|
|
2391
|
+
}
|
|
2392
|
+
if (ast && Array.isArray(ast.body)) {
|
|
2393
|
+
for (const stmt of ast.body) {
|
|
2394
|
+
if (!isAstNode(stmt) || stmt.type !== "VariableDeclaration" || !Array.isArray(stmt.declarations))
|
|
2395
|
+
continue;
|
|
2396
|
+
for (const decl of stmt.declarations) {
|
|
2397
|
+
if (!isAstNode(decl) || !isAstNode(decl.init))
|
|
2398
|
+
continue;
|
|
2399
|
+
const initSrc = file.content.slice(decl.init.start ?? 0, decl.init.end ?? 0);
|
|
2400
|
+
if (/\bAbortSignal\.timeout\s*\(|\bnew\s+AbortController\s*\(/.test(initSrc)) {
|
|
2401
|
+
pushFinding(findings, file, decl.start ?? 0, "no-shared-abort-signal", "test-smell", "R0", "warn", "Module-scoped AbortSignal/AbortController shares timeout and cancellation state across tests.", "Create a fresh AbortController or AbortSignal.timeout() inside each test case.");
|
|
2402
|
+
}
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
}
|
|
2407
|
+
return findings;
|
|
2408
|
+
}
|
|
2231
2409
|
|
|
2232
2410
|
// src/ast/t3-immune-rules.ts
|
|
2233
2411
|
var SH_PKILL_PATTERN = /\bpkill\s+-[a-zA-Z]*f\b|\bpgrep\b[^\n|]*\|\s*(?:xargs\s+)?kill\b/g;
|
|
@@ -2441,12 +2619,14 @@ function scanSingleTestFile(file, repoHasEmulator) {
|
|
|
2441
2619
|
const hasRealBus = REAL_BUS_SIGNAL.test(code);
|
|
2442
2620
|
const hasNetworkMock = NETWORK_MOCK_SIGNAL.test(code);
|
|
2443
2621
|
const isConfigFile = /(?:config|playwright|vitest|jest)\.[cm]?[jt]s$/i.test(file.rel);
|
|
2444
|
-
const addMatches = (target, regex, rule, category, severity, message, fix, limit = 5) => {
|
|
2622
|
+
const addMatches = (target, regex, rule, category, severity, message, fix, limit = 5, skip) => {
|
|
2445
2623
|
let count = 0;
|
|
2446
2624
|
for (const m of target.matchAll(regex)) {
|
|
2447
2625
|
const idx = m.index ?? 0;
|
|
2448
2626
|
if (target === raw && code[idx] === " ")
|
|
2449
2627
|
continue;
|
|
2628
|
+
if (skip?.(m))
|
|
2629
|
+
continue;
|
|
2450
2630
|
count += 1;
|
|
2451
2631
|
if (count <= limit) {
|
|
2452
2632
|
const line = lineOf(target, idx);
|
|
@@ -2465,7 +2645,7 @@ function scanSingleTestFile(file, repoHasEmulator) {
|
|
|
2465
2645
|
}
|
|
2466
2646
|
return count;
|
|
2467
2647
|
};
|
|
2468
|
-
const baseName =
|
|
2648
|
+
const baseName = path6.posix.basename(file.rel);
|
|
2469
2649
|
if (COVERAGE_FARM_NAME.test(baseName) && !COVERAGE_POLICY_TOOLING.test(baseName)) {
|
|
2470
2650
|
findings.push({
|
|
2471
2651
|
id: `TS:coverage-farm:${file.rel}:1`,
|
|
@@ -2513,7 +2693,10 @@ function scanSingleTestFile(file, repoHasEmulator) {
|
|
|
2513
2693
|
addMatches(code, SKIP_OR_ONLY, "test-discipline", "cheat", "error", "Focused (.only) or disabled (.todo/.fixme/Ignore) test committed.", "Restore a deterministic assertion or remove dead tests; never silently skip gating checks.");
|
|
2514
2694
|
addMatches(raw, UNCONDITIONAL_SKIP, "test-discipline", "cheat", "error", "Unconditionally skipped test (.skip) committed.", "Fix, delete, or track in a known-defect ledger; a skipped test proves nothing.");
|
|
2515
2695
|
addMatches(code, MULTI_STATUS_ASSERT, "no-multi-status-assertion", "test-smell", "error", "Assertion accepts multiple HTTP statuses and passes whether the call succeeded or failed.", "Assert the single exact HTTP status promised by the contract.");
|
|
2516
|
-
addMatches(code, TAUTOLOGY, "weak-asserts-tautology", "test-smell", "error", "Tautological assertion cannot fail when behavior breaks.", "Compare a computed SUT output against an independently derived expected value.")
|
|
2696
|
+
addMatches(code, TAUTOLOGY, "weak-asserts-tautology", "test-smell", "error", "Tautological assertion cannot fail when behavior breaks.", "Compare a computed SUT output against an independently derived expected value.", 5, (m) => {
|
|
2697
|
+
const idx = m.index ?? 0;
|
|
2698
|
+
return /^Assert\.Pass\b/.test(m[0]) && /\bAssert\.Fail\s*\(/.test(code.slice(Math.max(0, idx - 300), idx + 300));
|
|
2699
|
+
});
|
|
2517
2700
|
addMatches(code, SAME_CALL_EXPECT, "self-derived-expectation", "test-smell", "error", "Actual and expected values invoke the exact same function call.", "Replace the expected side with a known literal or independent oracle.");
|
|
2518
2701
|
addMatches(code, CONDITIONAL_EXPECT, "no-conditional-expect", "test-smell", "error", "Assertion inside conditional branch silently passes if branch is skipped.", "Split into explicit test cases with unconditional assertions.");
|
|
2519
2702
|
addMatches(code, WALL_CLOCK, "no-elapsed-time-bound", "test-smell", "warn", "Wall-clock elapsed-time assertion flakes on shared CI runners.", "Assert logical ordering or move performance bounds to a dedicated R6 benchmark.");
|
|
@@ -2537,6 +2720,7 @@ function scanSingleTestFile(file, repoHasEmulator) {
|
|
|
2537
2720
|
});
|
|
2538
2721
|
}
|
|
2539
2722
|
findings.push(...scanTestHarnessGuards(file, raw, code, repoHasEmulator));
|
|
2723
|
+
findings.push(...analyzeUniversalLandminesTest(file, code, parseTsAst(file)));
|
|
2540
2724
|
if (boundary === "e2e" && hasNetworkMock) {
|
|
2541
2725
|
pushDowns.push({
|
|
2542
2726
|
file: file.rel,
|
|
@@ -2768,7 +2952,7 @@ function selectRoundRobin(items, maxCandidates) {
|
|
|
2768
2952
|
function buildTestFacts(file, ordinal, boundary, testCaseCount, hasTableOrPbt, networkMock) {
|
|
2769
2953
|
const code = maskStrings(file.content);
|
|
2770
2954
|
const hasSutImport = hasNonFrameworkImport(file.content, file.language);
|
|
2771
|
-
const coverageFarmName = COVERAGE_FARM.test(
|
|
2955
|
+
const coverageFarmName = COVERAGE_FARM.test(path7.posix.basename(file.rel));
|
|
2772
2956
|
const literalOnlyAssertion = LITERAL_EXPECT.test(file.content);
|
|
2773
2957
|
const selfDerivedExpectation = SELF_DERIVED.test(code);
|
|
2774
2958
|
const multiStatusCount = code.match(MULTI_STATUS)?.length ?? 0;
|
|
@@ -4009,7 +4193,7 @@ function collectInstructionInputs(repoPath) {
|
|
|
4009
4193
|
const repo = discoverRepo(repoPath);
|
|
4010
4194
|
const items = [];
|
|
4011
4195
|
for (const file of repo.files) {
|
|
4012
|
-
const base =
|
|
4196
|
+
const base = path8.posix.basename(file.rel).toLowerCase();
|
|
4013
4197
|
if (base !== "agents.md" && base !== "claude.md" && base !== "skill.md")
|
|
4014
4198
|
continue;
|
|
4015
4199
|
const lines = file.content.split(/\r?\n/);
|
|
@@ -4539,10 +4723,10 @@ function lintNoComments(file, source, language, options = {}) {
|
|
|
4539
4723
|
}
|
|
4540
4724
|
|
|
4541
4725
|
// src/structure.ts
|
|
4542
|
-
import
|
|
4726
|
+
import path15 from "node:path";
|
|
4543
4727
|
|
|
4544
4728
|
// src/oracle-audit.ts
|
|
4545
|
-
import
|
|
4729
|
+
import path9 from "node:path";
|
|
4546
4730
|
var INSTRUCTION_NAMES = new Set(["agents.md", "claude.md", "gemini.md", "skill.md"]);
|
|
4547
4731
|
var ORACLE_NO_EDIT_TOPIC = /\b(?:oracle|gherkin|feature files?|acceptance tests?|contracts\.lock)\b|(?:features|tests\/acceptance)\/|\.feature\b/i;
|
|
4548
4732
|
var ORACLE_LOCK_VERB = /\b(?:read[- ]only|locked|immutable)\b|\b(?:do not|don't|must not|never)\s+(?:be\s+)?(?:edit|modify|change|rewrite|delete|touch)(?:ed)?\b/i;
|
|
@@ -4597,7 +4781,7 @@ function parseCodeowners(text) {
|
|
|
4597
4781
|
}
|
|
4598
4782
|
function analyzeOracleAndInstructions(repo) {
|
|
4599
4783
|
const findings = [];
|
|
4600
|
-
const codeownersFiles = repo.files.filter((f) =>
|
|
4784
|
+
const codeownersFiles = repo.files.filter((f) => path9.posix.basename(f.rel).toLowerCase() === "codeowners");
|
|
4601
4785
|
const ownerRules = codeownersFiles.flatMap((f) => parseCodeowners(f.content));
|
|
4602
4786
|
const oracleArtifacts = repo.allRelPaths.filter((rel) => /\.feature$/i.test(rel) || /(?:^|\/)tests\/acceptance\//i.test(rel) || /(?:^|\/)contracts\.lock\.json$/i.test(rel));
|
|
4603
4787
|
if (oracleArtifacts.length > 0 && ownerRules.length > 0) {
|
|
@@ -4619,7 +4803,7 @@ function analyzeOracleAndInstructions(repo) {
|
|
|
4619
4803
|
}
|
|
4620
4804
|
}
|
|
4621
4805
|
}
|
|
4622
|
-
const instructionFiles = repo.files.filter((f) => INSTRUCTION_NAMES.has(
|
|
4806
|
+
const instructionFiles = repo.files.filter((f) => INSTRUCTION_NAMES.has(path9.posix.basename(f.rel).toLowerCase()));
|
|
4623
4807
|
let forbidFile;
|
|
4624
4808
|
let allowFile;
|
|
4625
4809
|
let allowLine = 1;
|
|
@@ -4668,6 +4852,150 @@ function analyzeOracleAndInstructions(repo) {
|
|
|
4668
4852
|
return findings;
|
|
4669
4853
|
}
|
|
4670
4854
|
|
|
4855
|
+
// src/anti-slop/universal-laws.ts
|
|
4856
|
+
var TERMINAL_STATES = "(?:Shipped|Completed|Cancelled|Canceled|Closed|Refunded|Archived|Settled|Terminated|Finalized|Deleted|Disposed)";
|
|
4857
|
+
var NON_TERMINAL_STATES = "(?:Pending|Draft|Open|Queued|Processing|Active|Running|InProgress|Created|Submitted|New)";
|
|
4858
|
+
var TERMINAL_CASE_RESURRECT = new RegExp(`\\bcase\\b[^\\n:;{=>]{0,40}["']?\\b${TERMINAL_STATES}\\b["']?[^\\n{]{0,30}[:=>]\\s*(?:return\\s+)?(?:new\\s+)?["']?[A-Za-z0-9_.:]*(?:\\.|::)?${NON_TERMINAL_STATES}\\b["']?`, "g");
|
|
4859
|
+
var RUST_MATCH_TERMINAL_RESURRECT = new RegExp(`\\b[A-Za-z0-9_:]*::${TERMINAL_STATES}\\b[^\\n=>]{0,30}=>\\s*(?:Ok\\s*\\(\\s*)?[A-Za-z0-9_:]*::${NON_TERMINAL_STATES}\\b`, "g");
|
|
4860
|
+
var NON_NEG_COUNTER = "(?:balance|credits|creditBalance|stock|inventory|remaining|quota|allowance|available|budget|availableStock|remainingBudget|remainingQuota)";
|
|
4861
|
+
var UNGUARDED_COUNTER_SUB = new RegExp(`\\b(${NON_NEG_COUNTER})\\s*(?:-=|=\\s*\\1\\s*-)\\s*([A-Za-z_][A-Za-z0-9_.]*)`, "g");
|
|
4862
|
+
var SATURATING_OR_GUARD = /\b(?:Math\.max\s*\(\s*0|Math\.Clamp|saturating_sub|checked_sub|max\s*\(\s*0|clamp|>=|<=|>|<|throw\b|raise\b|return\s+(?:Err|null|false|undefined)|InvalidOperationException|ArgumentOutOfRangeException)\b/;
|
|
4863
|
+
var ZERO_CAP_OR_FALLBACK_JS = /\b(cap|limit|maxRetries|maxAttempts|maxItems|maxCount|maxConcurrency|quota|budget|pageSize)\s*\|\|\s*(?:[1-9]\d*|[A-Za-z_][A-Za-z0-9_]*)\b/g;
|
|
4864
|
+
var ZERO_CAP_OR_FALLBACK_PY = /\b(cap|limit|max_retries|max_attempts|max_items|max_count|quota|budget|page_size)\s+or\s+(?:[1-9]\d*|[A-Za-z_][A-Za-z0-9_]*)\b/g;
|
|
4865
|
+
var ENCODE_FN = /\b(?:function|def|fn|func|public\s+(?:static\s+)?[A-Za-z0-9_<>,.?]+\s+)\s*(encode[A-Za-z0-9_]*|serialize[A-Za-z0-9_]*|to_wire[A-Za-z0-9_]*|toWire[A-Za-z0-9_]*)\s*\(/g;
|
|
4866
|
+
var DECODE_FN = /\b(?:function|def|fn|func|public\s+(?:static\s+)?[A-Za-z0-9_<>,.?]+\s+)\s*(decode[A-Za-z0-9_]*|deserialize[A-Za-z0-9_]*|from_wire[A-Za-z0-9_]*|fromWire[A-Za-z0-9_]*)\s*\(/g;
|
|
4867
|
+
var UNPAIRED_LOCK_CS_GO_PY = [
|
|
4868
|
+
{ open: /\b([A-Za-z_][A-Za-z0-9_.]*)\.(?:EnterWriteLock|EnterReadLock|Acquire|Wait)\s*\(/g, close: /\.(?:ExitWriteLock|ExitReadLock|Release)\s*\(/, label: "lock/semaphore" },
|
|
4869
|
+
{ open: /\b([A-Za-z_][A-Za-z0-9_.]*)\.(?:Lock|RLock)\s*\(\s*\)/g, close: /\.(?:Unlock|RUnlock)\s*\(\s*\)/, label: "mutex" },
|
|
4870
|
+
{ open: /\b([A-Za-z_][A-Za-z0-9_.]*)\.acquire\s*\(/g, close: /\.release\s*\(/, label: "lock" }
|
|
4871
|
+
];
|
|
4872
|
+
var GO_WALL_CLOCK_SUB = /\btime\.Now\s*\(\s*\)\s*\.\s*Unix(?:Milli|Micro|Nano)?\s*\(\s*\)\s*-\s*[A-Za-z_][A-Za-z0-9_.]*/g;
|
|
4873
|
+
var GO_TEST_ONLY_EXPORT = /\bfunc\s+[A-Z][A-Za-z0-9_]*(?:ForTesting|TestOnly)\s*\(/g;
|
|
4874
|
+
function pushLaw(findings, file, offset, rule, rung, severity, message, fix) {
|
|
4875
|
+
const line = lineOf(file.content, offset);
|
|
4876
|
+
findings.push({
|
|
4877
|
+
id: `LAW:${rule}:${file.rel}:${line}`,
|
|
4878
|
+
rule,
|
|
4879
|
+
category: "structure",
|
|
4880
|
+
rung,
|
|
4881
|
+
severity,
|
|
4882
|
+
file: file.rel,
|
|
4883
|
+
line,
|
|
4884
|
+
message,
|
|
4885
|
+
fix
|
|
4886
|
+
});
|
|
4887
|
+
}
|
|
4888
|
+
function extractBodySlice(code, startIdx) {
|
|
4889
|
+
const openBrace = code.indexOf("{", startIdx);
|
|
4890
|
+
if (openBrace >= 0 && openBrace - startIdx < 160) {
|
|
4891
|
+
let depth = 0;
|
|
4892
|
+
for (let i = openBrace;i < Math.min(code.length, openBrace + 3000); i++) {
|
|
4893
|
+
if (code[i] === "{")
|
|
4894
|
+
depth += 1;
|
|
4895
|
+
else if (code[i] === "}") {
|
|
4896
|
+
depth -= 1;
|
|
4897
|
+
if (depth === 0)
|
|
4898
|
+
return code.slice(openBrace, i + 1);
|
|
4899
|
+
}
|
|
4900
|
+
}
|
|
4901
|
+
}
|
|
4902
|
+
return code.slice(startIdx, Math.min(code.length, startIdx + 1200));
|
|
4903
|
+
}
|
|
4904
|
+
function countSwitchArms(body, lang) {
|
|
4905
|
+
if (lang === "rust") {
|
|
4906
|
+
return (body.match(/=>/g)?.length ?? 0) - (body.match(/\b_\s*=>/g)?.length ?? 0);
|
|
4907
|
+
}
|
|
4908
|
+
const cases = body.match(/\bcase\b/g)?.length ?? 0;
|
|
4909
|
+
if (cases > 0)
|
|
4910
|
+
return cases;
|
|
4911
|
+
if (lang === "csharp") {
|
|
4912
|
+
return (body.match(/=>/g)?.length ?? 0) - (body.match(/\b_\s*=>/g)?.length ?? 0);
|
|
4913
|
+
}
|
|
4914
|
+
return 0;
|
|
4915
|
+
}
|
|
4916
|
+
function stripLineAndBlockComments(raw, lang) {
|
|
4917
|
+
const re = lang === "python" ? /#[^\r\n]*/g : /\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g;
|
|
4918
|
+
return raw.replace(re, (m) => m.replace(/[^\r\n]/g, " "));
|
|
4919
|
+
}
|
|
4920
|
+
function analyzeUniversalBendLaws(file) {
|
|
4921
|
+
if (!file.language || file.isTest)
|
|
4922
|
+
return [];
|
|
4923
|
+
const findings = [];
|
|
4924
|
+
const raw = file.content;
|
|
4925
|
+
const maskedAll = maskCode(raw, file.language);
|
|
4926
|
+
const cfgTestIdx = file.language === "rust" ? raw.search(/#\[cfg\(test\)\]/) : -1;
|
|
4927
|
+
const code = cfgTestIdx >= 0 ? maskedAll.slice(0, cfgTestIdx) : maskedAll;
|
|
4928
|
+
const uncommentedAll = stripLineAndBlockComments(raw, file.language);
|
|
4929
|
+
const uncommented = cfgTestIdx >= 0 ? uncommentedAll.slice(0, cfgTestIdx) : uncommentedAll;
|
|
4930
|
+
const resurrectRe = file.language === "rust" ? RUST_MATCH_TERMINAL_RESURRECT : TERMINAL_CASE_RESURRECT;
|
|
4931
|
+
for (const m of uncommented.matchAll(resurrectRe)) {
|
|
4932
|
+
pushLaw(findings, file, m.index ?? 0, "law-monotonic-terminal-state", "R1", "error", "Transition reverts a terminal state back to a non-terminal state (violates Bend 2 monotonic terminal-state law).", "Keep terminal states absorbing (return the terminal state unchanged or return a typed rejection error).");
|
|
4933
|
+
}
|
|
4934
|
+
for (const m of code.matchAll(UNGUARDED_COUNTER_SUB)) {
|
|
4935
|
+
const idx = m.index ?? 0;
|
|
4936
|
+
const window = code.slice(Math.max(0, idx - 220), idx + 180);
|
|
4937
|
+
if (SATURATING_OR_GUARD.test(window))
|
|
4938
|
+
continue;
|
|
4939
|
+
pushLaw(findings, file, idx, "law-saturating-underflow", "R1", "warn", `Unguarded subtraction on non-negative counter '${m[1]}' can underflow below zero (violates Bend 2 sat_sub_zero_left law).`, "Use total saturating arithmetic (Math.max(0, ...), saturating_sub, Math.Clamp) or validate amount <= available first.");
|
|
4940
|
+
}
|
|
4941
|
+
const zeroCapRe = file.language === "python" ? ZERO_CAP_OR_FALLBACK_PY : file.language === "typescript" || file.language === "javascript" ? ZERO_CAP_OR_FALLBACK_JS : null;
|
|
4942
|
+
if (zeroCapRe) {
|
|
4943
|
+
for (const m of code.matchAll(zeroCapRe)) {
|
|
4944
|
+
const idx = m.index ?? 0;
|
|
4945
|
+
const lineStart = code.lastIndexOf(`
|
|
4946
|
+
`, idx) + 1;
|
|
4947
|
+
const lineEnd = code.indexOf(`
|
|
4948
|
+
`, idx);
|
|
4949
|
+
const lineText = code.slice(lineStart, lineEnd >= 0 ? lineEnd : code.length);
|
|
4950
|
+
if (/\b(?:if|while)\s*\(/.test(lineText) || /\breturn\s+[^\n]*[=<>!]/.test(lineText))
|
|
4951
|
+
continue;
|
|
4952
|
+
if (file.language === "python" && /^\s*(?:if|elif|while|assert)\b/.test(lineText))
|
|
4953
|
+
continue;
|
|
4954
|
+
pushLaw(findings, file, idx, "law-zero-cap-clamp", "R1", "warn", `Truthy fallback on cap/limit '${m[1]}' silently overrides an explicit 0 cap (violates Bend 2 clamp_respects_zero_cap law).`, file.language === "python" ? `Check 'if ${m[1]} is None:' instead of '${m[1]} or ...' so 0 stays 0.` : `Use nullish coalescing ('${m[1]} ?? defaultVal') instead of '${m[1]} || defaultVal' so 0 stays 0.`);
|
|
4955
|
+
}
|
|
4956
|
+
}
|
|
4957
|
+
const encodeMatches = [...code.matchAll(ENCODE_FN)];
|
|
4958
|
+
const decodeMatches = [...code.matchAll(DECODE_FN)];
|
|
4959
|
+
const enc = encodeMatches.length === 1 ? encodeMatches[0] : undefined;
|
|
4960
|
+
const dec = decodeMatches.length === 1 ? decodeMatches[0] : undefined;
|
|
4961
|
+
if (enc && dec) {
|
|
4962
|
+
const encBody = extractBodySlice(code, enc.index ?? 0);
|
|
4963
|
+
const decBody = extractBodySlice(code, dec.index ?? 0);
|
|
4964
|
+
const encArms = countSwitchArms(encBody, file.language);
|
|
4965
|
+
const decArms = countSwitchArms(decBody, file.language);
|
|
4966
|
+
if (Math.max(encArms, decArms) >= 3 && encArms > 0 && decArms > 0 && encArms !== decArms) {
|
|
4967
|
+
pushLaw(findings, file, dec.index ?? 0, "law-codec-roundtrip-asymmetry", "R1", "warn", `Codec pair '${enc[1]}' (${encArms} branches) and '${dec[1]}' (${decArms} branches) handle different variant counts (violates Bend 2 status_roundtrip law).`, "Handle identical variant sets in encode and decode (or derive both from one lookup table) and add a round-trip test.");
|
|
4968
|
+
}
|
|
4969
|
+
}
|
|
4970
|
+
if (file.language === "csharp" || file.language === "go" || file.language === "python") {
|
|
4971
|
+
for (const pair of UNPAIRED_LOCK_CS_GO_PY) {
|
|
4972
|
+
for (const m of code.matchAll(pair.open)) {
|
|
4973
|
+
const idx = m.index ?? 0;
|
|
4974
|
+
const target = m[1] ?? "";
|
|
4975
|
+
const after = code.slice(idx, Math.min(code.length, idx + 900));
|
|
4976
|
+
if (!pair.close.test(after))
|
|
4977
|
+
continue;
|
|
4978
|
+
if (file.language === "go" && /\bdefer\b/.test(after))
|
|
4979
|
+
continue;
|
|
4980
|
+
if ((file.language === "csharp" || file.language === "python") && /\b(?:finally|using|with)\b/.test(code.slice(Math.max(0, idx - 60), idx + 900))) {
|
|
4981
|
+
continue;
|
|
4982
|
+
}
|
|
4983
|
+
pushLaw(findings, file, idx, "law-unwind-unpaired", "R1", "warn", `Paired ${pair.label} acquisition on '${target}' lacks try/finally or defer cleanup (violates Bend 2 unwind_restores_empty law).`, file.language === "go" ? `Call 'defer ${target}.Unlock()' immediately after acquiring the lock.` : "Wrap the critical section in try/finally (or a scoped using/with guard) so cleanup runs on every unwind path.");
|
|
4984
|
+
break;
|
|
4985
|
+
}
|
|
4986
|
+
}
|
|
4987
|
+
}
|
|
4988
|
+
if (file.language === "go") {
|
|
4989
|
+
for (const m of code.matchAll(GO_WALL_CLOCK_SUB)) {
|
|
4990
|
+
pushLaw(findings, file, m.index ?? 0, "cdc-wall-clock-duration", "R1", "warn", `Wall-clock Unix timestamp subtraction (${m[0].trim()}) breaks on NTP clock jumps (V30 Clock CDC).`, "Use time.Since(start) or time.Now().Sub(start) which reads Go's monotonic clock.");
|
|
4991
|
+
}
|
|
4992
|
+
for (const m of code.matchAll(GO_TEST_ONLY_EXPORT)) {
|
|
4993
|
+
pushLaw(findings, file, m.index ?? 0, "no-test-only-production-seam", "R1", "warn", `Test-only exported function in Go production file: ${m[0].trim()}.`, "Remove test-only exports and verify behavior through the public package interface.");
|
|
4994
|
+
}
|
|
4995
|
+
}
|
|
4996
|
+
return findings;
|
|
4997
|
+
}
|
|
4998
|
+
|
|
4671
4999
|
// src/ast/blackhole-replay-guards.ts
|
|
4672
5000
|
var GO_ERR_TYPE_ASSERT = /\b([A-Za-z_][A-Za-z0-9_]*[Ee]rr[A-Za-z0-9_]*|err)\.\(\s*\*?[A-Za-z_][A-Za-z0-9_.]*(?:Error|Err)\b/g;
|
|
4673
5001
|
var GO_SLICE_LEN_PLUS = /\[len\(\s*([A-Za-z_][A-Za-z0-9_.]*)\s*\)\s*\+\s*[1-9]\d*\s*:/g;
|
|
@@ -4853,7 +5181,7 @@ function analyzeBlackHoleReplayGuards(file, ast) {
|
|
|
4853
5181
|
}
|
|
4854
5182
|
|
|
4855
5183
|
// src/ast/cross-file-graph.ts
|
|
4856
|
-
import
|
|
5184
|
+
import path10 from "node:path";
|
|
4857
5185
|
var DANGEROUS_SINKS = new Set([
|
|
4858
5186
|
"eval",
|
|
4859
5187
|
"Function",
|
|
@@ -4888,8 +5216,8 @@ function push5(findings, file, line, rule, rung, severity, message, fix) {
|
|
|
4888
5216
|
function resolveImport(fromRel, spec, allFiles) {
|
|
4889
5217
|
if (!spec.startsWith("."))
|
|
4890
5218
|
return null;
|
|
4891
|
-
const dir =
|
|
4892
|
-
const base =
|
|
5219
|
+
const dir = path10.posix.dirname(fromRel);
|
|
5220
|
+
const base = path10.posix.normalize(path10.posix.join(dir, spec));
|
|
4893
5221
|
const candidates = [
|
|
4894
5222
|
base,
|
|
4895
5223
|
`${base}.ts`,
|
|
@@ -5201,7 +5529,7 @@ function analyzeBlackHoleArchGates(repo) {
|
|
|
5201
5529
|
}
|
|
5202
5530
|
|
|
5203
5531
|
// src/ast/deviant-invariants.ts
|
|
5204
|
-
import
|
|
5532
|
+
import path11 from "node:path";
|
|
5205
5533
|
var GENERATED_PATH2 = /(?:^|\/)(?:generated|generated-clients?|codegen|__snapshots__)\/|\.(?:gen|generated)\.[cm]?[jt]sx?$/i;
|
|
5206
5534
|
var SKIP_NULL_CALLEE = new Set([
|
|
5207
5535
|
"get",
|
|
@@ -5396,10 +5724,10 @@ function minePairedCleanupBeliefs(files, findings) {
|
|
|
5396
5724
|
function mineRouteAuthBeliefs(files, findings) {
|
|
5397
5725
|
const routeGroups = new Map;
|
|
5398
5726
|
for (const file of files) {
|
|
5399
|
-
const dir =
|
|
5727
|
+
const dir = path11.posix.dirname(file.rel);
|
|
5400
5728
|
if (!ROUTE_DIR_RE.test(dir))
|
|
5401
5729
|
continue;
|
|
5402
|
-
const base =
|
|
5730
|
+
const base = path11.posix.basename(file.rel, path11.posix.extname(file.rel));
|
|
5403
5731
|
if (PUBLIC_ROUTE_FILE.test(base))
|
|
5404
5732
|
continue;
|
|
5405
5733
|
const list = routeGroups.get(dir) ?? [];
|
|
@@ -6593,7 +6921,7 @@ function analyzeCveAndPostmortemGuards(file) {
|
|
|
6593
6921
|
}
|
|
6594
6922
|
|
|
6595
6923
|
// src/zero-defect/ecosystem-guards.ts
|
|
6596
|
-
import
|
|
6924
|
+
import path12 from "node:path";
|
|
6597
6925
|
var TS_ANY_ANNOTATION = /(?:[,({]\s*[A-Za-z_$][A-Za-z0-9_$]*\??\s*:\s*any\b|\)\s*:\s*any\b|<\s*any\s*>)/g;
|
|
6598
6926
|
var UNBOUNDED_FETCH = /\bfetch\s*\(\s*[^,)\n]+\s*\)/g;
|
|
6599
6927
|
var DYNAMIC_IMPORT_VAR = /\bimport\s*\(\s*([A-Za-z_$][A-Za-z0-9_$.]*)\s*\)/g;
|
|
@@ -6624,8 +6952,8 @@ function scanMigrationDuplicates(repo, findings) {
|
|
|
6624
6952
|
for (const rel of repo.allRelPaths) {
|
|
6625
6953
|
if (!/(?:^|\/)migrations?\//i.test(rel) || !/\.sql$/i.test(rel))
|
|
6626
6954
|
continue;
|
|
6627
|
-
const dir =
|
|
6628
|
-
const base =
|
|
6955
|
+
const dir = path12.posix.dirname(rel);
|
|
6956
|
+
const base = path12.posix.basename(rel);
|
|
6629
6957
|
const prefixMatch = /^(\d{2,})[_-]/.exec(base);
|
|
6630
6958
|
if (!prefixMatch?.[1])
|
|
6631
6959
|
continue;
|
|
@@ -6646,7 +6974,7 @@ function scanMigrationDuplicates(repo, findings) {
|
|
|
6646
6974
|
}
|
|
6647
6975
|
function scanFileEcosystemGuards(file, hasTsRepo, findings) {
|
|
6648
6976
|
const raw = file.content;
|
|
6649
|
-
const baseLower =
|
|
6977
|
+
const baseLower = path12.posix.basename(file.rel).toLowerCase();
|
|
6650
6978
|
if (/^\.env\.(?:example|sample|template|dist)$/i.test(baseLower)) {
|
|
6651
6979
|
for (const m of raw.matchAll(ENV_REAL_SECRET)) {
|
|
6652
6980
|
const tok = m[0] ?? "";
|
|
@@ -6822,6 +7150,16 @@ var RUST_INSTANT_ARITH = /\bInstant::now\s*\(\s*\)\s*[+-]\s*[A-Za-z0-9_.:]+|\.\s
|
|
|
6822
7150
|
var RUST_POLL_FN = /\bfn\s+poll(?:_next|_read|_write)?\s*\([^)]*\)[^{]*\{/g;
|
|
6823
7151
|
var RUST_HASHMAP_ENVS = /\.\s*envs\s*\(\s*&?\s*[A-Za-z0-9_.]*hash_?map[A-Za-z0-9_]*\s*\)/gi;
|
|
6824
7152
|
var CS_UNORDERED_SKIP = /\.\s*Skip\s*\(\s*[^)\n]+\)/g;
|
|
7153
|
+
var CS_EF_CONTEXT = /\b(?:Microsoft\.EntityFrameworkCore|DbContext|DbSet|IQueryable|AsNoTracking|ToListAsync|FirstOrDefaultAsync|SingleOrDefaultAsync)\b/;
|
|
7154
|
+
function isSymmetricBoundMath(callText) {
|
|
7155
|
+
const open = callText.indexOf("(");
|
|
7156
|
+
const comma = callText.indexOf(",", open + 1);
|
|
7157
|
+
if (open < 0 || comma < 0)
|
|
7158
|
+
return false;
|
|
7159
|
+
const firstArg = callText.slice(open + 1, comma);
|
|
7160
|
+
const isMin = /\bMath\.(?:min|Min)\b/.test(callText.slice(0, open));
|
|
7161
|
+
return isMin ? /(?:min|Min|floor|Floor)/.test(firstArg) : /(?:max|Max|cap|Cap|ceiling|Ceiling)/.test(firstArg);
|
|
7162
|
+
}
|
|
6825
7163
|
var CS_UNDISPOSED_NEW = /^[ \t]*(?!using\b|await\s+using\b|return\b)(?:var|[A-Za-z0-9_.<>]+)\s+[A-Za-z_][A-Za-z0-9_]*\s*=\s*new\s+(?:SqlConnection|NpgsqlConnection|FileStream|StreamReader|StreamWriter|DbCommand|SqlCommand)\s*\(/gm;
|
|
6826
7164
|
var GO_HTTP_CALL = /\b(?:http\.(?:Get|Post|PostForm|Head)|[A-Za-z_][A-Za-z0-9_]*\.Do)\s*\(/g;
|
|
6827
7165
|
function push14(findings, file, line, rule, rung, severity, message, fix) {
|
|
@@ -6966,11 +7304,13 @@ function analyzeOssGuards(file) {
|
|
|
6966
7304
|
return findings;
|
|
6967
7305
|
}
|
|
6968
7306
|
if (file.language === "csharp") {
|
|
6969
|
-
|
|
6970
|
-
const
|
|
6971
|
-
|
|
6972
|
-
|
|
6973
|
-
|
|
7307
|
+
if (CS_EF_CONTEXT.test(masked)) {
|
|
7308
|
+
for (const m of masked.matchAll(CS_UNORDERED_SKIP)) {
|
|
7309
|
+
const idx = m.index ?? 0;
|
|
7310
|
+
if (/\.\s*OrderBy(?:Descending)?\s*\(/.test(masked.slice(Math.max(0, idx - 220), idx)))
|
|
7311
|
+
continue;
|
|
7312
|
+
push14(findings, file.rel, lineOf(raw, idx), "efcore-unordered-skip-or-assert", "R1", "warn", ".Skip() called without a preceding .OrderBy() produces non-deterministic query pagination across DB engines.", "Chain a deterministic .OrderBy(...) (with a unique tie-breaker) before .Skip()/.Take().");
|
|
7313
|
+
}
|
|
6974
7314
|
}
|
|
6975
7315
|
for (const m of masked.matchAll(CS_UNDISPOSED_NEW)) {
|
|
6976
7316
|
const idx = m.index ?? 0;
|
|
@@ -6979,6 +7319,8 @@ function analyzeOssGuards(file) {
|
|
|
6979
7319
|
push14(findings, file.rel, lineOf(raw, idx), "csharp-undisposed-local-idisp", "R1", "warn", "Local IDisposable resource constructed without 'using' risks connection/file-handle leaks.", "Declare with 'using var' or 'await using var' so disposal runs deterministically even on exceptions.");
|
|
6980
7320
|
}
|
|
6981
7321
|
for (const m of masked.matchAll(FLOOR_CEILING_INVERSION)) {
|
|
7322
|
+
if (isSymmetricBoundMath(m[0]))
|
|
7323
|
+
continue;
|
|
6982
7324
|
push14(findings, file.rel, lineOf(raw, m.index ?? 0), "math-floor-ceiling-inversion", "R1", "warn", `Possible floor/ceiling clamp inversion (${m[0].trim()}).`, "Verify Math.Max is used for lower bounds (floors) and Math.Min is used for upper bounds (ceilings).");
|
|
6983
7325
|
}
|
|
6984
7326
|
return findings;
|
|
@@ -7137,6 +7479,8 @@ function analyzeOssGuards(file) {
|
|
|
7137
7479
|
push14(findings, file.rel, lineOf(raw, idx), "require-try-finally-around-teardown", "R1", "warn", "Sequential flush/export before close/dispose lacks try...finally — an export error skips close() and leaks resources.", "Wrap export/flush in try { ... } finally { await close(); } so teardown always executes.");
|
|
7138
7480
|
}
|
|
7139
7481
|
for (const m of masked.matchAll(FLOOR_CEILING_INVERSION)) {
|
|
7482
|
+
if (isSymmetricBoundMath(m[0]))
|
|
7483
|
+
continue;
|
|
7140
7484
|
push14(findings, file.rel, lineOf(raw, m.index ?? 0), "math-floor-ceiling-inversion", "R1", "warn", `Possible floor/ceiling clamp inversion (${m[0].trim()}).`, "Verify Math.max is used for lower bounds (floors) and Math.min is used for upper bounds (ceilings).");
|
|
7141
7485
|
}
|
|
7142
7486
|
for (const m of masked.matchAll(/\.(?:includes)\s*\(/g)) {
|
|
@@ -7662,6 +8006,8 @@ function analyzeProdZeroDefectRules(repo) {
|
|
|
7662
8006
|
findings.push(...analyzeWave6TitansAGuards(file));
|
|
7663
8007
|
findings.push(...analyzeWave7TitansBGuards(file));
|
|
7664
8008
|
const ast = parseTsAst(file);
|
|
8009
|
+
findings.push(...analyzeUniversalBendLaws(file));
|
|
8010
|
+
findings.push(...analyzeUniversalAntiSlopProd(file, ast));
|
|
7665
8011
|
findings.push(...analyzeTsAstGuards(file, ast));
|
|
7666
8012
|
findings.push(...analyzeLinearObligations(file, ast));
|
|
7667
8013
|
findings.push(...analyzeBlackHoleReplayGuards(file, ast));
|
|
@@ -7969,6 +8315,11 @@ function checkCsharpScatteredMutations(file, masked) {
|
|
|
7969
8315
|
const before = masked.slice(Math.max(0, pos - 40), pos);
|
|
7970
8316
|
if (/\b(?:new\s+[A-Za-z_]|with\s*\{|var\s+|bool\s+|string\s+|int\s+)/.test(before))
|
|
7971
8317
|
continue;
|
|
8318
|
+
const lineEnd = masked.indexOf(`
|
|
8319
|
+
`, pos);
|
|
8320
|
+
const restOfLine = masked.slice(pos, lineEnd < 0 ? pos + 120 : lineEnd);
|
|
8321
|
+
if (/,\s*$/.test(restOfLine) || /\bEntityState\./.test(restOfLine) || /\bAddress\.State\b/.test(restOfLine))
|
|
8322
|
+
continue;
|
|
7972
8323
|
const containing = spans.filter((s) => s.start < pos && pos < s.end).sort((a, b) => a.end - a.start - (b.end - b.start))[0];
|
|
7973
8324
|
if (!containing || CANONICAL_TRANSITION.test(containing.name))
|
|
7974
8325
|
continue;
|
|
@@ -8915,7 +9266,7 @@ function analyzeStateMachines(repo) {
|
|
|
8915
9266
|
import { spawnSync as spawnSync6 } from "node:child_process";
|
|
8916
9267
|
import fs5 from "node:fs";
|
|
8917
9268
|
import os2 from "node:os";
|
|
8918
|
-
import
|
|
9269
|
+
import path14 from "node:path";
|
|
8919
9270
|
|
|
8920
9271
|
// src/zero-defect/formal-sync.ts
|
|
8921
9272
|
import { spawnSync as spawnSync4 } from "node:child_process";
|
|
@@ -9049,18 +9400,18 @@ function formatFormalSyncReport(findings) {
|
|
|
9049
9400
|
import { spawnSync as spawnSync5 } from "node:child_process";
|
|
9050
9401
|
import fs4 from "node:fs";
|
|
9051
9402
|
import os from "node:os";
|
|
9052
|
-
import
|
|
9403
|
+
import path13 from "node:path";
|
|
9053
9404
|
var BEND_LAW_DECL = /^\s*(?:law|theorem)\s+([A-Za-z_][A-Za-z0-9_]*)\b/gm;
|
|
9054
9405
|
var BEND_DEF_DECL = /^\s*def\s+(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\b/gm;
|
|
9055
9406
|
var BEND_UNSAFE_ESCAPE = /(?:@unsafe\b|\?[A-Za-z_][A-Za-z0-9_]*|\b(?:unsafe|sorry|admit|todo!|panic!)\b)/g;
|
|
9056
9407
|
function resolveBendBinary() {
|
|
9057
|
-
const localBin =
|
|
9408
|
+
const localBin = path13.join(os.homedir(), ".bend", "bin", "bend");
|
|
9058
9409
|
if (fs4.existsSync(localBin))
|
|
9059
9410
|
return localBin;
|
|
9060
9411
|
return "bend";
|
|
9061
9412
|
}
|
|
9062
9413
|
function isLawFile(rel) {
|
|
9063
|
-
const base =
|
|
9414
|
+
const base = path13.posix.basename(rel);
|
|
9064
9415
|
return base === "LAWS.bend" || base === "PROOF.bend" || base.endsWith(".laws.bend") || base.endsWith(".laws.json") || /(?:^|\/)\.verification\/laws\//.test(rel);
|
|
9065
9416
|
}
|
|
9066
9417
|
function hasCodeownersCoverage(repo, lawRel) {
|
|
@@ -9130,11 +9481,11 @@ ${pairedProof.content}` : file.content;
|
|
|
9130
9481
|
}
|
|
9131
9482
|
function runBendVerdict(repoRoot, relPath, findings, verifiedBackends) {
|
|
9132
9483
|
const bendBin = resolveBendBinary();
|
|
9133
|
-
const absFile =
|
|
9484
|
+
const absFile = path13.join(repoRoot, relPath);
|
|
9134
9485
|
const useKernel = Boolean(process.env.BENDTT);
|
|
9135
9486
|
const flag = useKernel ? "--verdict" : "--check-only";
|
|
9136
9487
|
const probe = spawnSync5(bendBin, [absFile, flag], {
|
|
9137
|
-
cwd:
|
|
9488
|
+
cwd: path13.dirname(absFile),
|
|
9138
9489
|
encoding: "utf8",
|
|
9139
9490
|
timeout: 30000
|
|
9140
9491
|
});
|
|
@@ -9189,7 +9540,7 @@ function auditJsonLawFile(file, repo, findings, verifiedBackends, verify) {
|
|
|
9189
9540
|
runBendVerdict(repo.root, ref, findings, verifiedBackends);
|
|
9190
9541
|
continue;
|
|
9191
9542
|
}
|
|
9192
|
-
const cmdArgs = Array.isArray(law.verifyArgs) && law.verifyArgs.length > 0 && typeof law.verifyArgs[0] === "string" ? [law.verifyArgs[0], law.verifyArgs.slice(1), repo.root] : /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(ref) ? ["bun", ["test",
|
|
9543
|
+
const cmdArgs = Array.isArray(law.verifyArgs) && law.verifyArgs.length > 0 && typeof law.verifyArgs[0] === "string" ? [law.verifyArgs[0], law.verifyArgs.slice(1), repo.root] : /\.(?:test|spec)\.[cm]?[jt]sx?$/.test(ref) ? ["bun", ["test", path13.join(repo.root, ref)], repo.root] : /(?:^|\/)test_[^/]+\.py$|_test\.py$/.test(ref) ? ["pytest", [path13.join(repo.root, ref)], repo.root] : ref.endsWith("_test.go") ? ["go", ["test", "."], path13.dirname(path13.join(repo.root, ref))] : null;
|
|
9193
9544
|
if (cmdArgs) {
|
|
9194
9545
|
const run = spawnSync5(cmdArgs[0], cmdArgs[1], { cwd: cmdArgs[2], encoding: "utf8", timeout: 45000 });
|
|
9195
9546
|
if (run.error) {
|
|
@@ -9242,8 +9593,8 @@ function auditLaws(repo, options) {
|
|
|
9242
9593
|
for (const file of repo.files) {
|
|
9243
9594
|
if (!isLawFile(file.rel))
|
|
9244
9595
|
continue;
|
|
9245
|
-
const base =
|
|
9246
|
-
const dir =
|
|
9596
|
+
const base = path13.posix.basename(file.rel);
|
|
9597
|
+
const dir = path13.posix.dirname(file.rel);
|
|
9247
9598
|
const siblingLaws = dir === "." ? "LAWS.bend" : `${dir}/LAWS.bend`;
|
|
9248
9599
|
if (base === "PROOF.bend" && filesByRel.has(siblingLaws)) {
|
|
9249
9600
|
continue;
|
|
@@ -9668,7 +10019,7 @@ function runRedBeforeFix(repoPath, baseRef, testCmd) {
|
|
|
9668
10019
|
if (!baseRef || baseRef.startsWith("-")) {
|
|
9669
10020
|
throw new Error(`Invalid git baseRef "${baseRef}".`);
|
|
9670
10021
|
}
|
|
9671
|
-
const root =
|
|
10022
|
+
const root = path14.resolve(repoPath);
|
|
9672
10023
|
const changed = spawnSync6("git", ["status", "--porcelain"], { cwd: root, encoding: "utf8" });
|
|
9673
10024
|
const diffNames = spawnSync6("git", ["diff", "--name-only", baseRef, "--"], { cwd: root, encoding: "utf8" });
|
|
9674
10025
|
const candidates = new Set;
|
|
@@ -9681,7 +10032,7 @@ ${diffNames.stdout ?? ""}`.split(/\r?\n/)) {
|
|
|
9681
10032
|
candidates.add(cleaned);
|
|
9682
10033
|
}
|
|
9683
10034
|
}
|
|
9684
|
-
const copiedTestFiles = [...candidates].filter((rel) => fs5.existsSync(
|
|
10035
|
+
const copiedTestFiles = [...candidates].filter((rel) => fs5.existsSync(path14.join(root, rel)));
|
|
9685
10036
|
if (copiedTestFiles.length === 0) {
|
|
9686
10037
|
return {
|
|
9687
10038
|
passed: false,
|
|
@@ -9692,8 +10043,8 @@ ${diffNames.stdout ?? ""}`.split(/\r?\n/)) {
|
|
|
9692
10043
|
reason: "No modified or added test files found to prove red-before-fix."
|
|
9693
10044
|
};
|
|
9694
10045
|
}
|
|
9695
|
-
const tmpDir = fs5.mkdtempSync(
|
|
9696
|
-
const worktreeDir =
|
|
10046
|
+
const tmpDir = fs5.mkdtempSync(path14.join(os2.tmpdir(), "vstack-rbf-"));
|
|
10047
|
+
const worktreeDir = path14.join(tmpDir, "base");
|
|
9697
10048
|
try {
|
|
9698
10049
|
const addWt = spawnSync6("git", ["worktree", "add", "--detach", worktreeDir, baseRef], {
|
|
9699
10050
|
cwd: root,
|
|
@@ -9709,14 +10060,14 @@ ${diffNames.stdout ?? ""}`.split(/\r?\n/)) {
|
|
|
9709
10060
|
reason: `Failed to create base worktree at ${baseRef}: ${(addWt.stderr ?? "").trim()}`
|
|
9710
10061
|
};
|
|
9711
10062
|
}
|
|
9712
|
-
const resolvedWorktree =
|
|
10063
|
+
const resolvedWorktree = path14.resolve(worktreeDir);
|
|
9713
10064
|
for (const rel of copiedTestFiles) {
|
|
9714
|
-
const dest =
|
|
9715
|
-
if (!dest.startsWith(`${resolvedWorktree}${
|
|
10065
|
+
const dest = path14.resolve(resolvedWorktree, rel);
|
|
10066
|
+
if (!dest.startsWith(`${resolvedWorktree}${path14.sep}`)) {
|
|
9716
10067
|
throw new Error(`Refusing to copy test file outside worktree: ${rel}`);
|
|
9717
10068
|
}
|
|
9718
|
-
fs5.mkdirSync(
|
|
9719
|
-
fs5.copyFileSync(
|
|
10069
|
+
fs5.mkdirSync(path14.dirname(dest), { recursive: true });
|
|
10070
|
+
fs5.copyFileSync(path14.join(root, rel), dest);
|
|
9720
10071
|
}
|
|
9721
10072
|
const baseRun = spawnSync6(testCmd, [], { cwd: worktreeDir, shell: true, encoding: "utf8", timeout: 120000 });
|
|
9722
10073
|
const headRun = spawnSync6(testCmd, [], { cwd: root, shell: true, encoding: "utf8", timeout: 120000 });
|
|
@@ -9775,8 +10126,8 @@ function analyzeStructure(repo) {
|
|
|
9775
10126
|
const dirMembers = new Map;
|
|
9776
10127
|
const dirSourceFiles = new Map;
|
|
9777
10128
|
for (const rel of repo.allRelPaths) {
|
|
9778
|
-
const dir =
|
|
9779
|
-
const base =
|
|
10129
|
+
const dir = path15.posix.dirname(rel);
|
|
10130
|
+
const base = path15.posix.basename(rel);
|
|
9780
10131
|
const members = dirMembers.get(dir) ?? new Set;
|
|
9781
10132
|
members.add(base);
|
|
9782
10133
|
dirMembers.set(dir, members);
|
|
@@ -9784,9 +10135,9 @@ function analyzeStructure(repo) {
|
|
|
9784
10135
|
for (const file of repo.files) {
|
|
9785
10136
|
const isGenerated = GENERATED_PATH5.test(file.rel);
|
|
9786
10137
|
if (file.language && !file.isTest && !isGenerated) {
|
|
9787
|
-
const dir =
|
|
10138
|
+
const dir = path15.posix.dirname(file.rel);
|
|
9788
10139
|
const list = dirSourceFiles.get(dir) ?? [];
|
|
9789
|
-
list.push(
|
|
10140
|
+
list.push(path15.posix.basename(file.rel));
|
|
9790
10141
|
dirSourceFiles.set(dir, list);
|
|
9791
10142
|
}
|
|
9792
10143
|
if (file.language && !file.isTest && !isGenerated && file.lines > WARN_FILE_LINES) {
|
|
@@ -9865,7 +10216,8 @@ function analyzeStructure(repo) {
|
|
|
9865
10216
|
}
|
|
9866
10217
|
}
|
|
9867
10218
|
if (file.language === "csharp" && !file.isTest && !isGenerated) {
|
|
9868
|
-
|
|
10219
|
+
const csharpCode = maskCode(file.content, "csharp");
|
|
10220
|
+
for (const match of csharpCode.matchAll(CSHARP_TEST_ONLY_EXPORT)) {
|
|
9869
10221
|
const line = lineOf5(file.content, match.index ?? 0);
|
|
9870
10222
|
findings.push({
|
|
9871
10223
|
id: `ST:cs-test-seam:${file.rel}:${line}`,
|
|
@@ -9879,7 +10231,7 @@ function analyzeStructure(repo) {
|
|
|
9879
10231
|
fix: "Remove test-only production backdoors and verify behavior through the public contract."
|
|
9880
10232
|
});
|
|
9881
10233
|
}
|
|
9882
|
-
for (const match of
|
|
10234
|
+
for (const match of csharpCode.matchAll(SWALLOWING_CATCH)) {
|
|
9883
10235
|
const line = lineOf5(file.content, match.index ?? 0);
|
|
9884
10236
|
findings.push({
|
|
9885
10237
|
id: `ST:cs-swallow-catch:${file.rel}:${line}`,
|
|
@@ -9893,7 +10245,7 @@ function analyzeStructure(repo) {
|
|
|
9893
10245
|
fix: "Rethrow, return a typed result/error variant, or handle the specific expected exception explicitly."
|
|
9894
10246
|
});
|
|
9895
10247
|
}
|
|
9896
|
-
for (const match of
|
|
10248
|
+
for (const match of csharpCode.matchAll(CSHARP_DYNAMIC)) {
|
|
9897
10249
|
const line = lineOf5(file.content, match.index ?? 0);
|
|
9898
10250
|
findings.push({
|
|
9899
10251
|
id: `AS:cs-dynamic:${file.rel}:${line}`,
|
|
@@ -10035,7 +10387,7 @@ function analyzeStructure(repo) {
|
|
|
10035
10387
|
}
|
|
10036
10388
|
}
|
|
10037
10389
|
}
|
|
10038
|
-
const baseLower =
|
|
10390
|
+
const baseLower = path15.posix.basename(file.rel).toLowerCase();
|
|
10039
10391
|
if (baseLower.endsWith(".csproj") || baseLower === "directory.build.props") {
|
|
10040
10392
|
for (const match of file.content.matchAll(CSPROJ_WARN_FALSE)) {
|
|
10041
10393
|
const line = lineOf5(file.content, match.index ?? 0);
|
|
@@ -10152,6 +10504,130 @@ function analyzeStructure(repo) {
|
|
|
10152
10504
|
return findings;
|
|
10153
10505
|
}
|
|
10154
10506
|
|
|
10507
|
+
// src/anti-slop/agent-docs.ts
|
|
10508
|
+
import fs6 from "node:fs";
|
|
10509
|
+
import path16 from "node:path";
|
|
10510
|
+
var AGENT_DOC_BASENAME = /^(?:agents\.md|claude\.md|gemini\.md|review\.md|\.cursorrules|copilot-instructions\.md)$/i;
|
|
10511
|
+
var MAX_AGENT_DOC_LINES = 400;
|
|
10512
|
+
var BACKTICK_TOKEN = /`([^`\r\n]+)`/g;
|
|
10513
|
+
var KNOWN_FILE_EXT = /\.(?:[cm]?[jt]sx?|cs|py|rs|go|jsonc?|ya?ml|toml|sql|sh|bash|md|mdx|bend|csproj|slnx)$/i;
|
|
10514
|
+
var MECHANICAL_PROHIBITION = /\b(?:never|must not|do not|don't|ban|forbid)\s+(?:use|call|import|add|commit|skip|weaken|pipe|disable)\b/i;
|
|
10515
|
+
function isAgentInstructionFile(rel) {
|
|
10516
|
+
const norm = rel.replace(/\\/g, "/");
|
|
10517
|
+
if (/^(?:examples|templates|tests\/fixtures)\//i.test(norm))
|
|
10518
|
+
return false;
|
|
10519
|
+
const base = path16.posix.basename(norm);
|
|
10520
|
+
return AGENT_DOC_BASENAME.test(base);
|
|
10521
|
+
}
|
|
10522
|
+
function collectTopLevelDirs(repoRoot) {
|
|
10523
|
+
const dirs = new Set;
|
|
10524
|
+
try {
|
|
10525
|
+
for (const entry of fs6.readdirSync(repoRoot, { withFileTypes: true })) {
|
|
10526
|
+
if (entry.isDirectory() && entry.name !== ".git" && entry.name !== "node_modules") {
|
|
10527
|
+
dirs.add(entry.name);
|
|
10528
|
+
}
|
|
10529
|
+
}
|
|
10530
|
+
} catch {
|
|
10531
|
+
return dirs;
|
|
10532
|
+
}
|
|
10533
|
+
return dirs;
|
|
10534
|
+
}
|
|
10535
|
+
function auditAgentDocs(repo) {
|
|
10536
|
+
const findings = [];
|
|
10537
|
+
const topDirs = collectTopLevelDirs(repo.root);
|
|
10538
|
+
const hasMechanicalEnforcementRegistry = repo.allRelPaths.some((p) => /^\.verification\/(?:chokepoints|escapes)\.json$/i.test(p));
|
|
10539
|
+
for (const file of repo.files) {
|
|
10540
|
+
if (!isAgentInstructionFile(file.rel))
|
|
10541
|
+
continue;
|
|
10542
|
+
if (file.lines > MAX_AGENT_DOC_LINES) {
|
|
10543
|
+
findings.push({
|
|
10544
|
+
id: `AD:bloat:${file.rel}:1`,
|
|
10545
|
+
rule: "agent-doc-bloat",
|
|
10546
|
+
category: "structure",
|
|
10547
|
+
rung: "R0",
|
|
10548
|
+
severity: "warn",
|
|
10549
|
+
file: file.rel,
|
|
10550
|
+
line: 1,
|
|
10551
|
+
message: `Agent instruction file ${file.rel} has ${file.lines} lines (budget: <= ${MAX_AGENT_DOC_LINES}); oversized instruction files dilute context and compound slop.`,
|
|
10552
|
+
fix: "Trim stale prose, move topic details into progressive-disclosure docs, and promote mechanical rules into R0/R1 linters."
|
|
10553
|
+
});
|
|
10554
|
+
}
|
|
10555
|
+
const lines = file.content.split(/\r?\n/);
|
|
10556
|
+
const seenStale = new Set;
|
|
10557
|
+
let inFence = false;
|
|
10558
|
+
let staleCount = 0;
|
|
10559
|
+
let mechanicalProseCount = 0;
|
|
10560
|
+
for (let idx = 0;idx < lines.length; idx++) {
|
|
10561
|
+
const line = lines[idx] ?? "";
|
|
10562
|
+
if (/^\s*```/.test(line)) {
|
|
10563
|
+
inFence = !inFence;
|
|
10564
|
+
continue;
|
|
10565
|
+
}
|
|
10566
|
+
if (inFence)
|
|
10567
|
+
continue;
|
|
10568
|
+
if (MECHANICAL_PROHIBITION.test(line)) {
|
|
10569
|
+
mechanicalProseCount += 1;
|
|
10570
|
+
}
|
|
10571
|
+
if (staleCount >= 5)
|
|
10572
|
+
continue;
|
|
10573
|
+
for (const m of line.matchAll(BACKTICK_TOKEN)) {
|
|
10574
|
+
const rawToken = (m[1] ?? "").trim();
|
|
10575
|
+
if (!rawToken || /\s|[*?<>:${}()|]|:\/\//.test(rawToken))
|
|
10576
|
+
continue;
|
|
10577
|
+
if (rawToken.startsWith("/") || rawToken.startsWith("~") || rawToken.startsWith("-"))
|
|
10578
|
+
continue;
|
|
10579
|
+
const clean = rawToken.replace(/^\.\//, "").split("#")[0]?.split(":")[0] ?? "";
|
|
10580
|
+
if (!clean || !clean.includes("/") || clean.endsWith("/"))
|
|
10581
|
+
continue;
|
|
10582
|
+
if (!KNOWN_FILE_EXT.test(clean))
|
|
10583
|
+
continue;
|
|
10584
|
+
const firstSegment = clean.split("/")[0] ?? "";
|
|
10585
|
+
if (!topDirs.has(firstSegment))
|
|
10586
|
+
continue;
|
|
10587
|
+
if (seenStale.has(clean))
|
|
10588
|
+
continue;
|
|
10589
|
+
const resolved = path16.resolve(repo.root, clean);
|
|
10590
|
+
if (!resolved.startsWith(`${repo.root}${path16.sep}`))
|
|
10591
|
+
continue;
|
|
10592
|
+
if (fs6.existsSync(resolved))
|
|
10593
|
+
continue;
|
|
10594
|
+
const siblingResolved = path16.resolve(path16.dirname(file.abs), clean);
|
|
10595
|
+
if (siblingResolved.startsWith(`${repo.root}${path16.sep}`) && fs6.existsSync(siblingResolved))
|
|
10596
|
+
continue;
|
|
10597
|
+
seenStale.add(clean);
|
|
10598
|
+
staleCount += 1;
|
|
10599
|
+
findings.push({
|
|
10600
|
+
id: `AD:stale-path:${file.rel}:${idx + 1}:${clean}`,
|
|
10601
|
+
rule: "agent-doc-stale-path",
|
|
10602
|
+
category: "structure",
|
|
10603
|
+
rung: "R0",
|
|
10604
|
+
severity: "warn",
|
|
10605
|
+
file: file.rel,
|
|
10606
|
+
line: idx + 1,
|
|
10607
|
+
message: `Agent instruction file references missing path '${clean}'; stale knowledge-base pointers cause agents to hallucinate or copy obsolete patterns.`,
|
|
10608
|
+
fix: `Update or remove the stale reference to '${clean}' in ${file.rel}.`
|
|
10609
|
+
});
|
|
10610
|
+
if (staleCount >= 5)
|
|
10611
|
+
break;
|
|
10612
|
+
}
|
|
10613
|
+
}
|
|
10614
|
+
if (mechanicalProseCount >= 4 && !hasMechanicalEnforcementRegistry) {
|
|
10615
|
+
findings.push({
|
|
10616
|
+
id: `AD:unpromoted:${file.rel}:1`,
|
|
10617
|
+
rule: "agent-doc-unpromoted-rules",
|
|
10618
|
+
category: "structure",
|
|
10619
|
+
rung: "R1",
|
|
10620
|
+
severity: "info",
|
|
10621
|
+
file: file.rel,
|
|
10622
|
+
line: 1,
|
|
10623
|
+
message: `${file.rel} states ${mechanicalProseCount} mechanical prohibition(s) in prose without a .verification/chokepoints.json or escapes.json enforcement registry.`,
|
|
10624
|
+
fix: "Run 'vstack circuit run instruction-lint-promoter .' and promote repeatable bans into deterministic R0/R1 linters."
|
|
10625
|
+
});
|
|
10626
|
+
}
|
|
10627
|
+
}
|
|
10628
|
+
return findings;
|
|
10629
|
+
}
|
|
10630
|
+
|
|
10155
10631
|
// src/ladder.ts
|
|
10156
10632
|
var E2E_CAP_BY_ARCHETYPE = {
|
|
10157
10633
|
library: { max: 0, label: "0 (not applicable)" },
|
|
@@ -10362,6 +10838,7 @@ function scanRepo(repoPath, options = {}) {
|
|
|
10362
10838
|
}
|
|
10363
10839
|
}
|
|
10364
10840
|
rawFindings.push(...analyzeStructure(repo));
|
|
10841
|
+
rawFindings.push(...auditAgentDocs(repo));
|
|
10365
10842
|
const testResult = analyzeTests(repo);
|
|
10366
10843
|
rawFindings.push(...testResult.findings);
|
|
10367
10844
|
rawFindings.push(...auditCiWorkflows(repo));
|
|
@@ -10413,8 +10890,8 @@ function scanRepo(repoPath, options = {}) {
|
|
|
10413
10890
|
}
|
|
10414
10891
|
|
|
10415
10892
|
// src/ratchet.ts
|
|
10416
|
-
import
|
|
10417
|
-
import
|
|
10893
|
+
import fs7 from "node:fs";
|
|
10894
|
+
import path17 from "node:path";
|
|
10418
10895
|
function buildRatchetBaseline(findings) {
|
|
10419
10896
|
const counts = new Map;
|
|
10420
10897
|
for (const f of findings) {
|
|
@@ -10450,16 +10927,16 @@ function evaluateRatchet(findings, baseline) {
|
|
|
10450
10927
|
};
|
|
10451
10928
|
}
|
|
10452
10929
|
function writeRatchetBaseline(filePath, baseline) {
|
|
10453
|
-
const resolved =
|
|
10454
|
-
|
|
10455
|
-
|
|
10930
|
+
const resolved = path17.resolve(filePath);
|
|
10931
|
+
fs7.mkdirSync(path17.dirname(resolved), { recursive: true });
|
|
10932
|
+
fs7.writeFileSync(resolved, `${JSON.stringify(baseline, null, 2)}
|
|
10456
10933
|
`, "utf8");
|
|
10457
10934
|
}
|
|
10458
10935
|
|
|
10459
10936
|
// src/zero-defect/bench.ts
|
|
10460
|
-
import
|
|
10937
|
+
import fs8 from "node:fs";
|
|
10461
10938
|
import os3 from "node:os";
|
|
10462
|
-
import
|
|
10939
|
+
import path18 from "node:path";
|
|
10463
10940
|
function commentPrefix(lang) {
|
|
10464
10941
|
if (lang === "python" || lang === "shell")
|
|
10465
10942
|
return "# ";
|
|
@@ -10493,16 +10970,16 @@ const Doc = "${escaped}"
|
|
|
10493
10970
|
`;
|
|
10494
10971
|
}
|
|
10495
10972
|
function runInTempDir(files) {
|
|
10496
|
-
const dir =
|
|
10973
|
+
const dir = fs8.mkdtempSync(path18.join(os3.tmpdir(), "vstack-bench-"));
|
|
10497
10974
|
try {
|
|
10498
10975
|
for (const [rel, content] of Object.entries(files)) {
|
|
10499
|
-
const full =
|
|
10500
|
-
|
|
10501
|
-
|
|
10976
|
+
const full = path18.join(dir, rel);
|
|
10977
|
+
fs8.mkdirSync(path18.dirname(full), { recursive: true });
|
|
10978
|
+
fs8.writeFileSync(full, content, "utf8");
|
|
10502
10979
|
}
|
|
10503
10980
|
return scanRepo(dir);
|
|
10504
10981
|
} finally {
|
|
10505
|
-
|
|
10982
|
+
fs8.rmSync(dir, { recursive: true, force: true });
|
|
10506
10983
|
}
|
|
10507
10984
|
}
|
|
10508
10985
|
function countRuleMap(findings) {
|
|
@@ -10516,11 +10993,11 @@ function countRuleMap(findings) {
|
|
|
10516
10993
|
return m;
|
|
10517
10994
|
}
|
|
10518
10995
|
function runHistoricalReplayBench(replayDir) {
|
|
10519
|
-
const manifestPath =
|
|
10520
|
-
const entries = JSON.parse(
|
|
10996
|
+
const manifestPath = path18.join(replayDir, "manifest.json");
|
|
10997
|
+
const entries = JSON.parse(fs8.readFileSync(manifestPath, "utf8"));
|
|
10521
10998
|
const t0 = performance.now();
|
|
10522
|
-
const beforeScan = scanRepo(
|
|
10523
|
-
const afterScan = scanRepo(
|
|
10999
|
+
const beforeScan = scanRepo(path18.join(replayDir, "before"));
|
|
11000
|
+
const afterScan = scanRepo(path18.join(replayDir, "after"));
|
|
10524
11001
|
const scanMs = Number((performance.now() - t0).toFixed(2));
|
|
10525
11002
|
const beforeByFile = new Map;
|
|
10526
11003
|
for (const f of beforeScan.findings) {
|
|
@@ -10558,8 +11035,8 @@ function runHistoricalReplayBench(replayDir) {
|
|
|
10558
11035
|
if (aCnt > (bMap.get(rule) ?? 0))
|
|
10559
11036
|
regressedRules.push(rule);
|
|
10560
11037
|
}
|
|
10561
|
-
const beforeRaw =
|
|
10562
|
-
const afterRaw =
|
|
11038
|
+
const beforeRaw = fs8.readFileSync(path18.join(replayDir, "before", entry.beforeRel), "utf8");
|
|
11039
|
+
const afterRaw = fs8.readFileSync(path18.join(replayDir, "after", entry.afterRel), "utf8");
|
|
10563
11040
|
const revertEvents = buildSyntheticRevertEvents(entry.afterRel, afterRaw, beforeRaw);
|
|
10564
11041
|
const revertFindings = [
|
|
10565
11042
|
...auditDiffInvariantLoss(revertEvents),
|
|
@@ -10626,17 +11103,17 @@ function runHistoricalReplayBench(replayDir) {
|
|
|
10626
11103
|
};
|
|
10627
11104
|
}
|
|
10628
11105
|
function runPrecisionBench(repoRoot, corpusDir, replayDir) {
|
|
10629
|
-
const examplesRoot =
|
|
11106
|
+
const examplesRoot = path18.join(repoRoot, "examples");
|
|
10630
11107
|
const langs = ["typescript", "csharp", "rust", "python", "go", "sql", "shell"];
|
|
10631
11108
|
const languages = [];
|
|
10632
11109
|
for (const lang of langs) {
|
|
10633
|
-
const langDir =
|
|
10634
|
-
const manifestPath =
|
|
10635
|
-
if (!
|
|
11110
|
+
const langDir = path18.join(examplesRoot, lang);
|
|
11111
|
+
const manifestPath = path18.join(langDir, "manifest.json");
|
|
11112
|
+
if (!fs8.existsSync(manifestPath))
|
|
10636
11113
|
continue;
|
|
10637
|
-
const manifest = JSON.parse(
|
|
10638
|
-
const caughtDir =
|
|
10639
|
-
const cleanDir =
|
|
11114
|
+
const manifest = JSON.parse(fs8.readFileSync(manifestPath, "utf8"));
|
|
11115
|
+
const caughtDir = path18.join(langDir, "caught");
|
|
11116
|
+
const cleanDir = path18.join(langDir, "clean");
|
|
10640
11117
|
const t0 = performance.now();
|
|
10641
11118
|
const caughtScan = scanRepo(caughtDir);
|
|
10642
11119
|
const cleanScan = scanRepo(cleanDir);
|
|
@@ -10665,7 +11142,7 @@ function runPrecisionBench(repoRoot, corpusDir, replayDir) {
|
|
|
10665
11142
|
for (const relFile of Object.keys(manifest.caught)) {
|
|
10666
11143
|
if (/test|spec/i.test(relFile))
|
|
10667
11144
|
continue;
|
|
10668
|
-
const content =
|
|
11145
|
+
const content = fs8.readFileSync(path18.join(caughtDir, relFile), "utf8");
|
|
10669
11146
|
commentedFiles[relFile] = wrapInComments(content, lang);
|
|
10670
11147
|
const wrappedStr = wrapInStringLiteral(content, lang);
|
|
10671
11148
|
if (wrappedStr !== null)
|
|
@@ -10689,7 +11166,7 @@ function runPrecisionBench(repoRoot, corpusDir, replayDir) {
|
|
|
10689
11166
|
});
|
|
10690
11167
|
}
|
|
10691
11168
|
let corpusFindingsPer10kLoc;
|
|
10692
|
-
if (corpusDir &&
|
|
11169
|
+
if (corpusDir && fs8.existsSync(corpusDir)) {
|
|
10693
11170
|
const corpusReport = scanRepo(corpusDir);
|
|
10694
11171
|
const loc = Math.max(1, corpusReport.summary.prodLines + corpusReport.summary.testLines);
|
|
10695
11172
|
corpusFindingsPer10kLoc = Number((corpusReport.findings.length / loc * 1e4).toFixed(2));
|
|
@@ -10699,7 +11176,7 @@ function runPrecisionBench(repoRoot, corpusDir, replayDir) {
|
|
|
10699
11176
|
const totalCleanFps = languages.reduce((s, l) => s + l.cleanFalsePositives.length, 0);
|
|
10700
11177
|
const totalAdversarialFps = languages.reduce((s, l) => s + l.commentWrappedFps.length + l.stringWrappedFps.length, 0);
|
|
10701
11178
|
const totalScanMs = Number(languages.reduce((s, l) => s + l.scanMs, 0).toFixed(2));
|
|
10702
|
-
const replay = replayDir &&
|
|
11179
|
+
const replay = replayDir && fs8.existsSync(path18.join(replayDir, "manifest.json")) ? runHistoricalReplayBench(replayDir) : undefined;
|
|
10703
11180
|
return {
|
|
10704
11181
|
passed: totalExpectedRules === totalMatchedRules && totalCleanFps === 0 && totalAdversarialFps === 0,
|
|
10705
11182
|
totalExpectedRules,
|
|
@@ -10835,8 +11312,8 @@ function fitEmpiricalBigO(samples, thresholds = { maxTimeExponent: 1.45 }) {
|
|
|
10835
11312
|
}
|
|
10836
11313
|
|
|
10837
11314
|
// src/zero-defect/daikon-invariants.ts
|
|
10838
|
-
import
|
|
10839
|
-
import
|
|
11315
|
+
import fs9 from "node:fs";
|
|
11316
|
+
import path19 from "node:path";
|
|
10840
11317
|
function runtimeType(val) {
|
|
10841
11318
|
if (val === null)
|
|
10842
11319
|
return "null";
|
|
@@ -10997,9 +11474,9 @@ function compareInvariantSnapshots(baseline, current, baselineFile = ".verificat
|
|
|
10997
11474
|
};
|
|
10998
11475
|
}
|
|
10999
11476
|
function writeInvariantSnapshot(filePath, snapshot) {
|
|
11000
|
-
const resolved =
|
|
11001
|
-
|
|
11002
|
-
|
|
11477
|
+
const resolved = path19.resolve(filePath);
|
|
11478
|
+
fs9.mkdirSync(path19.dirname(resolved), { recursive: true });
|
|
11479
|
+
fs9.writeFileSync(resolved, `${JSON.stringify(snapshot, null, 2)}
|
|
11003
11480
|
`, "utf8");
|
|
11004
11481
|
}
|
|
11005
11482
|
function formatInvariantDiffReport(snapshot, diff) {
|
|
@@ -11025,6 +11502,320 @@ function formatInvariantDiffReport(snapshot, diff) {
|
|
|
11025
11502
|
`);
|
|
11026
11503
|
}
|
|
11027
11504
|
|
|
11505
|
+
// src/anti-slop/review-brief.ts
|
|
11506
|
+
import { spawnSync as spawnSync7 } from "node:child_process";
|
|
11507
|
+
import path20 from "node:path";
|
|
11508
|
+
var LOCK_OR_GENERATED = /(?:^|\/)(?:pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lockb?|cargo\.lock|uv\.lock|poetry\.lock|go\.sum)$|\.(?:snap|generated\.[a-z]+)$/i;
|
|
11509
|
+
var DOC_FILE = /\.(?:md|mdx|txt|rst)$/i;
|
|
11510
|
+
var CRITICAL_PATH = /(?:^|\/)(?:\.github\/workflows\/|codeowners$|migrations\/|schema|rls|policies\/|auth|security|billing|payment|permission|crypto|token|secret|openapi|contracts|state-machines?\/|tsconfig(?:\.[^/]+)?\.json$|\.?vstack\.json$|\.verification\/|package\.json$|cargo\.toml$|pyproject\.toml$|directory\.build\.props$)/i;
|
|
11511
|
+
var WORKAROUND_MARKER = /\b(?:HACK|WORKAROUND|TEMP(?:ORARY)?|KLUDGE|FIXME)\b/;
|
|
11512
|
+
var FALLBACK_SWALLOW_CATCH = /\bcatch\b[^{]*\{\s*return\s+(?:null|undefined|false|true|\[\s*\]|\{\s*\}|""|''|0)\s*;?\s*\}/;
|
|
11513
|
+
var TIER_ORDER = { critical: 0, core: 1, verify: 2, low: 3 };
|
|
11514
|
+
function validateBaseRef(baseRef) {
|
|
11515
|
+
if (!baseRef || baseRef.startsWith("-")) {
|
|
11516
|
+
throw new Error(`Invalid git baseRef "${baseRef}".`);
|
|
11517
|
+
}
|
|
11518
|
+
}
|
|
11519
|
+
function classifyFileStakes(file, cheatCount, workaroundCount) {
|
|
11520
|
+
if (cheatCount > 0) {
|
|
11521
|
+
return { tier: "critical", reason: `${cheatCount} diff-cheat / invariant-loss finding(s)` };
|
|
11522
|
+
}
|
|
11523
|
+
if (CRITICAL_PATH.test(file)) {
|
|
11524
|
+
return { tier: "critical", reason: "high-stakes boundary (security, schema, CI, contract, or strictness config)" };
|
|
11525
|
+
}
|
|
11526
|
+
if (workaroundCount > 0) {
|
|
11527
|
+
return { tier: "critical", reason: `${workaroundCount} workaround/fallback signal(s) added` };
|
|
11528
|
+
}
|
|
11529
|
+
if (LOCK_OR_GENERATED.test(file)) {
|
|
11530
|
+
return { tier: "low", reason: "lockfile or generated artifact" };
|
|
11531
|
+
}
|
|
11532
|
+
if (DOC_FILE.test(file)) {
|
|
11533
|
+
return { tier: "low", reason: "documentation / prose" };
|
|
11534
|
+
}
|
|
11535
|
+
if (isTestFilePath(file)) {
|
|
11536
|
+
return { tier: "verify", reason: "test oracle / verification suite" };
|
|
11537
|
+
}
|
|
11538
|
+
return { tier: "core", reason: "production logic" };
|
|
11539
|
+
}
|
|
11540
|
+
function collectWorkaroundSignals(repoRoot, baseRef) {
|
|
11541
|
+
const diff = spawnSync7("git", ["-C", repoRoot, "diff", baseRef, "--unified=0", "--no-color"], {
|
|
11542
|
+
encoding: "utf8"
|
|
11543
|
+
});
|
|
11544
|
+
if (diff.status !== 0)
|
|
11545
|
+
return [];
|
|
11546
|
+
const signals = [];
|
|
11547
|
+
let currentFile = "";
|
|
11548
|
+
let currentLine = 1;
|
|
11549
|
+
for (const raw of diff.stdout.split(/\r?\n/)) {
|
|
11550
|
+
if (raw.startsWith("+++ b/")) {
|
|
11551
|
+
currentFile = raw.slice(6);
|
|
11552
|
+
continue;
|
|
11553
|
+
}
|
|
11554
|
+
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(raw);
|
|
11555
|
+
if (hunk) {
|
|
11556
|
+
currentLine = Number(hunk[1]);
|
|
11557
|
+
continue;
|
|
11558
|
+
}
|
|
11559
|
+
if (!raw.startsWith("+") || raw.startsWith("+++"))
|
|
11560
|
+
continue;
|
|
11561
|
+
const added = raw.slice(1);
|
|
11562
|
+
if (!DOC_FILE.test(currentFile) && !LOCK_OR_GENERATED.test(currentFile) && !isTestFilePath(currentFile)) {
|
|
11563
|
+
if (WORKAROUND_MARKER.test(added)) {
|
|
11564
|
+
signals.push({ file: currentFile, line: currentLine, signal: "workaround-marker" });
|
|
11565
|
+
} else if (FALLBACK_SWALLOW_CATCH.test(added)) {
|
|
11566
|
+
signals.push({ file: currentFile, line: currentLine, signal: "fallback-swallow-catch" });
|
|
11567
|
+
}
|
|
11568
|
+
}
|
|
11569
|
+
currentLine += 1;
|
|
11570
|
+
}
|
|
11571
|
+
return signals;
|
|
11572
|
+
}
|
|
11573
|
+
function buildBlindSpots(files, docLinesAdded, additionBias) {
|
|
11574
|
+
const spots = [
|
|
11575
|
+
"Static gates and agent reviews verify mechanics, not whether this change solves the right user problem."
|
|
11576
|
+
];
|
|
11577
|
+
if (files.some((f) => f.tier === "critical")) {
|
|
11578
|
+
spots.push("High-stakes paths changed: verify business intent, threat assumptions, and rollback safety by hand.");
|
|
11579
|
+
}
|
|
11580
|
+
if (additionBias) {
|
|
11581
|
+
spots.push("Diff is heavily additive: check whether existing code could be simplified or deleted instead of layered on.");
|
|
11582
|
+
}
|
|
11583
|
+
if (docLinesAdded > 0) {
|
|
11584
|
+
spots.push("Prose/docs were added: verify every paragraph earns the reader's time and reflects real code.");
|
|
11585
|
+
}
|
|
11586
|
+
if (files.some((f) => f.tier === "verify")) {
|
|
11587
|
+
spots.push("Tests were modified: confirm oracles come from an independent spec and failed before the fix.");
|
|
11588
|
+
}
|
|
11589
|
+
return spots;
|
|
11590
|
+
}
|
|
11591
|
+
function buildReviewBrief(repoPath, options = {}) {
|
|
11592
|
+
const repoRoot = path20.resolve(repoPath);
|
|
11593
|
+
const baseRef = options.baseRef ?? "HEAD";
|
|
11594
|
+
validateBaseRef(baseRef);
|
|
11595
|
+
const maxLines = options.maxLines ?? 600;
|
|
11596
|
+
const maxDirs = options.maxDirs ?? 8;
|
|
11597
|
+
const maxDocLines = options.maxDocLines ?? 250;
|
|
11598
|
+
const numstat = spawnSync7("git", ["-C", repoRoot, "diff", baseRef, "--numstat", "--no-renames"], {
|
|
11599
|
+
encoding: "utf8"
|
|
11600
|
+
});
|
|
11601
|
+
if (numstat.status !== 0) {
|
|
11602
|
+
throw new Error(`git diff failed for base "${baseRef}": ${(numstat.stderr ?? "").trim()}`);
|
|
11603
|
+
}
|
|
11604
|
+
const cheatFindings = scanGitDiffCheats(repoRoot, baseRef);
|
|
11605
|
+
const workaroundSignals = collectWorkaroundSignals(repoRoot, baseRef);
|
|
11606
|
+
const cheatsByFile = new Map;
|
|
11607
|
+
for (const f of cheatFindings) {
|
|
11608
|
+
cheatsByFile.set(f.file, (cheatsByFile.get(f.file) ?? 0) + 1);
|
|
11609
|
+
}
|
|
11610
|
+
const workaroundsByFile = new Map;
|
|
11611
|
+
for (const w of workaroundSignals) {
|
|
11612
|
+
workaroundsByFile.set(w.file, (workaroundsByFile.get(w.file) ?? 0) + 1);
|
|
11613
|
+
}
|
|
11614
|
+
const items = [];
|
|
11615
|
+
const dirs = new Set;
|
|
11616
|
+
let linesAdded = 0;
|
|
11617
|
+
let linesDeleted = 0;
|
|
11618
|
+
let nonLockfileLinesAdded = 0;
|
|
11619
|
+
let docLinesAdded = 0;
|
|
11620
|
+
for (const line of numstat.stdout.split(/\r?\n/)) {
|
|
11621
|
+
if (!line.trim())
|
|
11622
|
+
continue;
|
|
11623
|
+
const [rawAdd, rawDel, ...restPath] = line.split("\t");
|
|
11624
|
+
const file = restPath.join("\t").trim();
|
|
11625
|
+
if (!file)
|
|
11626
|
+
continue;
|
|
11627
|
+
const added = rawAdd === "-" ? 0 : Number(rawAdd) || 0;
|
|
11628
|
+
const deleted = rawDel === "-" ? 0 : Number(rawDel) || 0;
|
|
11629
|
+
linesAdded += added;
|
|
11630
|
+
linesDeleted += deleted;
|
|
11631
|
+
if (!LOCK_OR_GENERATED.test(file)) {
|
|
11632
|
+
nonLockfileLinesAdded += added;
|
|
11633
|
+
const dir = path20.posix.dirname(file);
|
|
11634
|
+
dirs.add(dir === "." ? "<root>" : dir);
|
|
11635
|
+
}
|
|
11636
|
+
if (DOC_FILE.test(file))
|
|
11637
|
+
docLinesAdded += added;
|
|
11638
|
+
const cheatCount = cheatsByFile.get(file) ?? 0;
|
|
11639
|
+
const workaroundCount = workaroundsByFile.get(file) ?? 0;
|
|
11640
|
+
const classified = classifyFileStakes(file, cheatCount, workaroundCount);
|
|
11641
|
+
items.push({
|
|
11642
|
+
file,
|
|
11643
|
+
tier: classified.tier,
|
|
11644
|
+
added,
|
|
11645
|
+
deleted,
|
|
11646
|
+
reason: classified.reason,
|
|
11647
|
+
cheatCount
|
|
11648
|
+
});
|
|
11649
|
+
}
|
|
11650
|
+
items.sort((a, b) => {
|
|
11651
|
+
const tierDiff = TIER_ORDER[a.tier] - TIER_ORDER[b.tier];
|
|
11652
|
+
if (tierDiff !== 0)
|
|
11653
|
+
return tierDiff;
|
|
11654
|
+
return b.added + b.deleted - (a.added + a.deleted);
|
|
11655
|
+
});
|
|
11656
|
+
const totalChurn = linesAdded + linesDeleted;
|
|
11657
|
+
const deletionRatio = totalChurn > 0 ? Number((linesDeleted / totalChurn).toFixed(3)) : 0;
|
|
11658
|
+
const dirsTouched = dirs.size;
|
|
11659
|
+
const additionBias = nonLockfileLinesAdded >= 300 && deletionRatio < 0.05 && items.length >= 5;
|
|
11660
|
+
const budgetBreaches = [];
|
|
11661
|
+
if (cheatFindings.length > 0) {
|
|
11662
|
+
budgetBreaches.push({
|
|
11663
|
+
rule: "review-budget-diff-cheats",
|
|
11664
|
+
actual: cheatFindings.length,
|
|
11665
|
+
limit: 0,
|
|
11666
|
+
message: `${cheatFindings.length} anti-cheat / dropped-invariant violation(s) found in diff.`,
|
|
11667
|
+
fix: "Resolve every diff-cheats finding before requesting human review."
|
|
11668
|
+
});
|
|
11669
|
+
}
|
|
11670
|
+
if (nonLockfileLinesAdded > maxLines) {
|
|
11671
|
+
budgetBreaches.push({
|
|
11672
|
+
rule: "review-budget-diff-size",
|
|
11673
|
+
actual: nonLockfileLinesAdded,
|
|
11674
|
+
limit: maxLines,
|
|
11675
|
+
message: `Diff adds ${nonLockfileLinesAdded} non-lockfile lines (review budget: <= ${maxLines}).`,
|
|
11676
|
+
fix: "Split into stacked, independently reviewable PRs or delete redundant code before asking for review."
|
|
11677
|
+
});
|
|
11678
|
+
}
|
|
11679
|
+
if (dirsTouched > maxDirs) {
|
|
11680
|
+
budgetBreaches.push({
|
|
11681
|
+
rule: "review-budget-shotgun-spread",
|
|
11682
|
+
actual: dirsTouched,
|
|
11683
|
+
limit: maxDirs,
|
|
11684
|
+
message: `Diff scatters changes across ${dirsTouched} directories (budget: <= ${maxDirs}).`,
|
|
11685
|
+
fix: "Isolate unrelated refactors or consolidate leaky abstractions into a deeper module."
|
|
11686
|
+
});
|
|
11687
|
+
}
|
|
11688
|
+
if (docLinesAdded > maxDocLines) {
|
|
11689
|
+
budgetBreaches.push({
|
|
11690
|
+
rule: "review-budget-doc-dump",
|
|
11691
|
+
actual: docLinesAdded,
|
|
11692
|
+
limit: maxDocLines,
|
|
11693
|
+
message: `Diff adds ${docLinesAdded} lines of prose/docs (budget: <= ${maxDocLines}).`,
|
|
11694
|
+
fix: "Trim AI-generated prose so every line respects the reader's time."
|
|
11695
|
+
});
|
|
11696
|
+
}
|
|
11697
|
+
if (additionBias) {
|
|
11698
|
+
budgetBreaches.push({
|
|
11699
|
+
rule: "review-budget-addition-bias",
|
|
11700
|
+
actual: Math.round(deletionRatio * 100),
|
|
11701
|
+
limit: 5,
|
|
11702
|
+
message: `Heavily additive diff (+${nonLockfileLinesAdded}/-${linesDeleted}, ${(deletionRatio * 100).toFixed(1)}% deletions across ${items.length} files).`,
|
|
11703
|
+
fix: "Check for workarounds or parallel wrappers that should replace or delete existing code instead."
|
|
11704
|
+
});
|
|
11705
|
+
}
|
|
11706
|
+
if (workaroundSignals.length > 0) {
|
|
11707
|
+
budgetBreaches.push({
|
|
11708
|
+
rule: "review-budget-workarounds",
|
|
11709
|
+
actual: workaroundSignals.length,
|
|
11710
|
+
limit: 0,
|
|
11711
|
+
message: `Added ${workaroundSignals.length} workaround/fallback-swallow signal(s) in production diff.`,
|
|
11712
|
+
fix: "Fix the root cause instead of layering HACK/WORKAROUND markers or silent fallback catches."
|
|
11713
|
+
});
|
|
11714
|
+
}
|
|
11715
|
+
return {
|
|
11716
|
+
schemaVersion: 1,
|
|
11717
|
+
repo: repoRoot,
|
|
11718
|
+
baseRef,
|
|
11719
|
+
passed: budgetBreaches.length === 0,
|
|
11720
|
+
metrics: {
|
|
11721
|
+
filesChanged: items.length,
|
|
11722
|
+
dirsTouched,
|
|
11723
|
+
linesAdded,
|
|
11724
|
+
linesDeleted,
|
|
11725
|
+
netLines: linesAdded - linesDeleted,
|
|
11726
|
+
nonLockfileLinesAdded,
|
|
11727
|
+
docLinesAdded,
|
|
11728
|
+
deletionRatio
|
|
11729
|
+
},
|
|
11730
|
+
budgets: { maxLines, maxDirs, maxDocLines },
|
|
11731
|
+
budgetBreaches,
|
|
11732
|
+
cheatFindings,
|
|
11733
|
+
workaroundSignals,
|
|
11734
|
+
reviewQueue: {
|
|
11735
|
+
mustReview: items.filter((i) => i.tier === "critical"),
|
|
11736
|
+
coreLogic: items.filter((i) => i.tier === "core"),
|
|
11737
|
+
verifyOracles: items.filter((i) => i.tier === "verify"),
|
|
11738
|
+
lowStakes: items.filter((i) => i.tier === "low")
|
|
11739
|
+
},
|
|
11740
|
+
blindSpots: buildBlindSpots(items, docLinesAdded, additionBias),
|
|
11741
|
+
ownershipChecklist: [
|
|
11742
|
+
"Problem & prior art understood before generation (no unreviewed first-draft pass-through).",
|
|
11743
|
+
"High-stakes slice (Must-Review queue above) verified directly by a human owner.",
|
|
11744
|
+
"Prefer subtraction: confirmed no workaround or parallel layer could be deleted/simplified.",
|
|
11745
|
+
"AI-authored code/docs explicitly disclosed and checked where stakes are highest."
|
|
11746
|
+
]
|
|
11747
|
+
};
|
|
11748
|
+
}
|
|
11749
|
+
function formatReviewBriefTerminal(report) {
|
|
11750
|
+
const m = report.metrics;
|
|
11751
|
+
const out = [];
|
|
11752
|
+
out.push(`Review Brief (${report.baseRef}) — ${report.passed ? "WITHIN BUDGET" : "OVER REVIEW BUDGET"}`);
|
|
11753
|
+
out.push(`Scope: ${m.filesChanged} file(s) across ${m.dirsTouched} dir(s) | +${m.linesAdded} / -${m.linesDeleted} (net ${m.netLines >= 0 ? "+" : ""}${m.netLines}, deletion ratio ${(m.deletionRatio * 100).toFixed(1)}%) | docs +${m.docLinesAdded}`);
|
|
11754
|
+
if (report.budgetBreaches.length > 0) {
|
|
11755
|
+
out.push("");
|
|
11756
|
+
out.push(`SLOP-ASYMMETRY & BUDGET BREACHES (${report.budgetBreaches.length})`);
|
|
11757
|
+
for (const b of report.budgetBreaches) {
|
|
11758
|
+
out.push(` - [${b.rule}] ${b.message}`);
|
|
11759
|
+
out.push(` Fix: ${b.fix}`);
|
|
11760
|
+
}
|
|
11761
|
+
}
|
|
11762
|
+
const emitGroup = (label, items, cap) => {
|
|
11763
|
+
if (items.length === 0)
|
|
11764
|
+
return;
|
|
11765
|
+
out.push("");
|
|
11766
|
+
out.push(`${label} (${items.length})`);
|
|
11767
|
+
for (const item of items.slice(0, cap)) {
|
|
11768
|
+
out.push(` - ${item.file} (+${item.added}/-${item.deleted}) — ${item.reason}`);
|
|
11769
|
+
}
|
|
11770
|
+
if (items.length > cap)
|
|
11771
|
+
out.push(` ... and ${items.length - cap} more`);
|
|
11772
|
+
};
|
|
11773
|
+
emitGroup("MUST REVIEW FIRST (HIGH STAKES)", report.reviewQueue.mustReview, 15);
|
|
11774
|
+
emitGroup("CORE LOGIC", report.reviewQueue.coreLogic, 12);
|
|
11775
|
+
emitGroup("TEST ORACLES", report.reviewQueue.verifyOracles, 8);
|
|
11776
|
+
emitGroup("LOW STAKES / MECHANICAL", report.reviewQueue.lowStakes, 6);
|
|
11777
|
+
out.push("");
|
|
11778
|
+
out.push("WHERE AUTOMATED CHECKS ARE BLIND (HUMAN JUDGMENT REQUIRED)");
|
|
11779
|
+
for (const spot of report.blindSpots)
|
|
11780
|
+
out.push(` - ${spot}`);
|
|
11781
|
+
return out.join(`
|
|
11782
|
+
`);
|
|
11783
|
+
}
|
|
11784
|
+
function formatReviewBriefMarkdown(report) {
|
|
11785
|
+
const m = report.metrics;
|
|
11786
|
+
const out = [];
|
|
11787
|
+
out.push(`## Human Review Brief (\`${report.baseRef}\`) — ${report.passed ? "Within Budget" : "Attention Required"}`);
|
|
11788
|
+
out.push("");
|
|
11789
|
+
out.push(`- **Diff Shape:** ${m.filesChanged} files · ${m.dirsTouched} dirs · \`+${m.linesAdded} / -${m.linesDeleted}\` (deletion ratio \`${(m.deletionRatio * 100).toFixed(1)}%\`) · docs \`+${m.docLinesAdded}\``);
|
|
11790
|
+
if (report.budgetBreaches.length > 0) {
|
|
11791
|
+
out.push("");
|
|
11792
|
+
out.push("### Slop-Asymmetry Warnings");
|
|
11793
|
+
for (const b of report.budgetBreaches) {
|
|
11794
|
+
out.push(`- **\`${b.rule}\`**: ${b.message} *Fix:* ${b.fix}`);
|
|
11795
|
+
}
|
|
11796
|
+
}
|
|
11797
|
+
const topFocus = [...report.reviewQueue.mustReview, ...report.reviewQueue.coreLogic].slice(0, 12);
|
|
11798
|
+
if (topFocus.length > 0) {
|
|
11799
|
+
out.push("");
|
|
11800
|
+
out.push("### Highest-Stakes Files to Read First");
|
|
11801
|
+
out.push("| Priority | File | Churn | Why |");
|
|
11802
|
+
out.push("| :---: | :--- | :---: | :--- |");
|
|
11803
|
+
for (const f of topFocus) {
|
|
11804
|
+
out.push(`| \`${f.tier}\` | \`${f.file}\` | \`+${f.added}/-${f.deleted}\` | ${f.reason} |`);
|
|
11805
|
+
}
|
|
11806
|
+
}
|
|
11807
|
+
out.push("");
|
|
11808
|
+
out.push("### Where Linters & Tests Are Blind");
|
|
11809
|
+
for (const spot of report.blindSpots)
|
|
11810
|
+
out.push(`- ${spot}`);
|
|
11811
|
+
out.push("");
|
|
11812
|
+
out.push("### Human Ownership Checklist");
|
|
11813
|
+
for (const item of report.ownershipChecklist)
|
|
11814
|
+
out.push(`- [ ] ${item}`);
|
|
11815
|
+
return out.join(`
|
|
11816
|
+
`);
|
|
11817
|
+
}
|
|
11818
|
+
|
|
11028
11819
|
// src/cli.ts
|
|
11029
11820
|
var VALID_PROVIDERS = new Set(["laya", "jev", "local", "command", "fixture"]);
|
|
11030
11821
|
var VALID_CIRCUITS = new Set([
|
|
@@ -11042,6 +11833,7 @@ function usage() {
|
|
|
11042
11833
|
" vstack no-comments [dir] [--json] [--fail]",
|
|
11043
11834
|
" vstack state-machines [dir] [--json] [--fail]",
|
|
11044
11835
|
" vstack diff-cheats [dir] [--base <ref>] [--json] [--fail]",
|
|
11836
|
+
" vstack review-brief [dir] [--base <ref>] [--max-lines <n>] [--max-dirs <n>] [--max-doc-lines <n>] [--json | --md] [--fail]",
|
|
11045
11837
|
" vstack formal-sync [dir] [--json] [--fail]",
|
|
11046
11838
|
" vstack laws [dir] [--verify] [--json] [--fail]",
|
|
11047
11839
|
" vstack bench [dir] [--corpus <dir>] [--replay <dir>] [--json] [--fail]",
|
|
@@ -11066,6 +11858,9 @@ function firstPositional(args) {
|
|
|
11066
11858
|
const valueFlags = new Set([
|
|
11067
11859
|
"--base",
|
|
11068
11860
|
"--max",
|
|
11861
|
+
"--max-lines",
|
|
11862
|
+
"--max-dirs",
|
|
11863
|
+
"--max-doc-lines",
|
|
11069
11864
|
"--corroborate",
|
|
11070
11865
|
"--provider",
|
|
11071
11866
|
"--endpoint",
|
|
@@ -11127,12 +11922,12 @@ async function run() {
|
|
|
11127
11922
|
const updateRatchet = rest.includes("--update-ratchet");
|
|
11128
11923
|
let ratchetEval;
|
|
11129
11924
|
if (ratchetPath) {
|
|
11130
|
-
if (updateRatchet || !
|
|
11925
|
+
if (updateRatchet || !fs10.existsSync(ratchetPath)) {
|
|
11131
11926
|
const nextBaseline = buildRatchetBaseline(report.findings);
|
|
11132
11927
|
writeRatchetBaseline(ratchetPath, nextBaseline);
|
|
11133
11928
|
ratchetEval = evaluateRatchet(report.findings, nextBaseline);
|
|
11134
11929
|
} else {
|
|
11135
|
-
const baseline = JSON.parse(
|
|
11930
|
+
const baseline = JSON.parse(fs10.readFileSync(ratchetPath, "utf8"));
|
|
11136
11931
|
ratchetEval = evaluateRatchet(report.findings, baseline);
|
|
11137
11932
|
}
|
|
11138
11933
|
}
|
|
@@ -11213,6 +12008,25 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
|
|
|
11213
12008
|
console.log(formatFindingsList(`diff-cheats (${baseRef})`, findings, asJson));
|
|
11214
12009
|
return rest.includes("--fail") && findings.length > 0 ? 1 : 0;
|
|
11215
12010
|
}
|
|
12011
|
+
if (cmd === "review-brief") {
|
|
12012
|
+
const baseRef = parseFlagValue(rest, "--base") ?? "HEAD";
|
|
12013
|
+
const maxLinesRaw = parseFlagValue(rest, "--max-lines");
|
|
12014
|
+
const maxDirsRaw = parseFlagValue(rest, "--max-dirs");
|
|
12015
|
+
const maxDocRaw = parseFlagValue(rest, "--max-doc-lines");
|
|
12016
|
+
const report = buildReviewBrief(target, {
|
|
12017
|
+
baseRef,
|
|
12018
|
+
maxLines: maxLinesRaw ? Number(maxLinesRaw) : undefined,
|
|
12019
|
+
maxDirs: maxDirsRaw ? Number(maxDirsRaw) : undefined,
|
|
12020
|
+
maxDocLines: maxDocRaw ? Number(maxDocRaw) : undefined
|
|
12021
|
+
});
|
|
12022
|
+
if (asJson)
|
|
12023
|
+
console.log(JSON.stringify(report, null, 2));
|
|
12024
|
+
else if (asMd)
|
|
12025
|
+
console.log(formatReviewBriefMarkdown(report));
|
|
12026
|
+
else
|
|
12027
|
+
console.log(formatReviewBriefTerminal(report));
|
|
12028
|
+
return rest.includes("--fail") && !report.passed ? 1 : 0;
|
|
12029
|
+
}
|
|
11216
12030
|
if (cmd === "classify") {
|
|
11217
12031
|
const maxRaw = parseFlagValue(rest, "--max");
|
|
11218
12032
|
const maxCandidates = maxRaw ? Number(maxRaw) : 30;
|
|
@@ -11229,7 +12043,7 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
|
|
|
11229
12043
|
});
|
|
11230
12044
|
packet = { ...corroborateSystem1Batch(packet, answers), provider };
|
|
11231
12045
|
} else if (corroboratePath) {
|
|
11232
|
-
const answers = JSON.parse(
|
|
12046
|
+
const answers = JSON.parse(fs10.readFileSync(corroboratePath, "utf8"));
|
|
11233
12047
|
packet = corroborateSystem1Batch(packet, answers);
|
|
11234
12048
|
}
|
|
11235
12049
|
if (rest.includes("--emit-requests")) {
|
|
@@ -11320,7 +12134,7 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
|
|
|
11320
12134
|
const metricsPath = rest.find((a) => !a.startsWith("-"));
|
|
11321
12135
|
if (!metricsPath)
|
|
11322
12136
|
throw new Error("vstack spc requires a JSON metrics file ({ metric, upperSpecLimit, values }).");
|
|
11323
|
-
const parsed = JSON.parse(
|
|
12137
|
+
const parsed = JSON.parse(fs10.readFileSync(metricsPath, "utf8"));
|
|
11324
12138
|
const result = evaluateSpcSeries(parsed.metric, parsed.values, parsed.upperSpecLimit);
|
|
11325
12139
|
if (asJson)
|
|
11326
12140
|
console.log(JSON.stringify(result, null, 2));
|
|
@@ -11336,7 +12150,7 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
|
|
|
11336
12150
|
if (!samplesPath) {
|
|
11337
12151
|
throw new Error("vstack big-o requires a JSON samples file ({ samples: [{ n, timeMs, memoryBytes? }], maxTimeExponent? }).");
|
|
11338
12152
|
}
|
|
11339
|
-
const parsed = JSON.parse(
|
|
12153
|
+
const parsed = JSON.parse(fs10.readFileSync(samplesPath, "utf8"));
|
|
11340
12154
|
const maxTimeRaw = parseFlagValue(rest, "--max-time-exp");
|
|
11341
12155
|
const maxSpaceRaw = parseFlagValue(rest, "--max-space-exp");
|
|
11342
12156
|
const result = fitEmpiricalBigO(parsed.samples, {
|
|
@@ -11358,18 +12172,18 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
|
|
|
11358
12172
|
if (!tracesPath || tracesPath === ".") {
|
|
11359
12173
|
throw new Error("vstack invariants requires a JSON traces file ({ samples: [{ fn, args?, result?, throws? }] }).");
|
|
11360
12174
|
}
|
|
11361
|
-
const parsed = JSON.parse(
|
|
12175
|
+
const parsed = JSON.parse(fs10.readFileSync(tracesPath, "utf8"));
|
|
11362
12176
|
const samples = Array.isArray(parsed) ? parsed : parsed.samples ?? [];
|
|
11363
12177
|
const current = inferDynamicInvariants(samples);
|
|
11364
12178
|
const baselinePath = parseFlagValue(rest, "--baseline");
|
|
11365
12179
|
const update = rest.includes("--update");
|
|
11366
12180
|
let diff;
|
|
11367
12181
|
if (baselinePath) {
|
|
11368
|
-
if (update || !
|
|
12182
|
+
if (update || !fs10.existsSync(baselinePath)) {
|
|
11369
12183
|
writeInvariantSnapshot(baselinePath, current);
|
|
11370
12184
|
diff = compareInvariantSnapshots(current, current, baselinePath);
|
|
11371
12185
|
} else {
|
|
11372
|
-
const baseline = JSON.parse(
|
|
12186
|
+
const baseline = JSON.parse(fs10.readFileSync(baselinePath, "utf8"));
|
|
11373
12187
|
diff = compareInvariantSnapshots(baseline, current, baselinePath);
|
|
11374
12188
|
}
|
|
11375
12189
|
}
|
|
@@ -11384,8 +12198,10 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
|
|
|
11384
12198
|
console.error(usage());
|
|
11385
12199
|
return 2;
|
|
11386
12200
|
}
|
|
11387
|
-
run().then((code) =>
|
|
12201
|
+
run().then((code) => {
|
|
12202
|
+
process.exitCode = code;
|
|
12203
|
+
}).catch((err) => {
|
|
11388
12204
|
const message = err instanceof Error ? err.message : String(err);
|
|
11389
12205
|
console.error(`vstack error: ${message}`);
|
|
11390
|
-
process.
|
|
12206
|
+
process.exitCode = 1;
|
|
11391
12207
|
});
|