veristack 0.1.4 → 0.1.5

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.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.mjs +1041 -462
  3. package/package.json +3 -2
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/cli.ts
2
- import fs15 from "node:fs";
2
+ import fs16 from "node:fs";
3
3
 
4
4
  // src/ci-auditor.ts
5
5
  import { spawnSync } from "node:child_process";
@@ -1841,27 +1841,268 @@ function scanGitDiffCheats(repoPath, baseRef = "HEAD") {
1841
1841
 
1842
1842
  // src/circuits/index.ts
1843
1843
  import { spawnSync as spawnSync3 } from "node:child_process";
1844
- import path8 from "node:path";
1844
+ import path9 from "node:path";
1845
1845
 
1846
1846
  // src/discover.ts
1847
1847
  import fs3 from "node:fs";
1848
- import path4 from "node:path";
1848
+ import path5 from "node:path";
1849
+
1850
+ // src/rungs/signals.ts
1851
+ import path3 from "node:path";
1852
+ var MANIFEST_BASENAMES = new Set([
1853
+ "package.json",
1854
+ "cargo.toml",
1855
+ "pyproject.toml",
1856
+ "go.mod",
1857
+ "directory.build.props",
1858
+ "directory.packages.props"
1859
+ ]);
1860
+ function isManifestFile(rel) {
1861
+ const base = path3.posix.basename(rel.replace(/\\/g, "/").toLowerCase());
1862
+ return MANIFEST_BASENAMES.has(base) || base.endsWith(".csproj");
1863
+ }
1864
+ function isConfigFile(file) {
1865
+ const lower = file.rel.replace(/\\/g, "/").toLowerCase();
1866
+ const base = path3.posix.basename(lower);
1867
+ if (file.isWorkflow || isManifestFile(file.rel))
1868
+ return true;
1869
+ if (lower.endsWith(".md"))
1870
+ return false;
1871
+ if (!file.language)
1872
+ return true;
1873
+ return /(?:^|\/)(?:vitest|vite|playwright|jest|oxlint|eslint|stryker|k6|biome|tailwind|next|nuxt|webpack|rollup)\.config\.[cm]?[jt]s$/.test(lower) || base === "oxlint.config.ts" || lower.startsWith(".verification/");
1874
+ }
1875
+ function stripCodeStringsAndComments(content) {
1876
+ return content.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:\\])\/\/[^\n]*/g, "$1 ").replace(/(^|\s)#[^\n]*/g, "$1 ").replace(/"(?:\\.|[^"\\])*"/g, '""').replace(/'(?:\\.|[^'\\])*'/g, "''").replace(/`(?:\\.|[^`\\])*`/g, "``");
1877
+ }
1878
+ function parsePackageScripts(files) {
1879
+ const scripts = new Map;
1880
+ for (const file of files) {
1881
+ if (path3.posix.basename(file.rel).toLowerCase() !== "package.json")
1882
+ continue;
1883
+ try {
1884
+ const parsed = JSON.parse(file.content);
1885
+ if (!parsed.scripts || typeof parsed.scripts !== "object")
1886
+ continue;
1887
+ for (const [name, cmd] of Object.entries(parsed.scripts)) {
1888
+ if (typeof cmd === "string" && cmd.trim().length > 0 && !scripts.has(name)) {
1889
+ scripts.set(name, cmd);
1890
+ }
1891
+ }
1892
+ } catch {
1893
+ continue;
1894
+ }
1895
+ }
1896
+ return scripts;
1897
+ }
1898
+ function collectReferencedScriptNames(text) {
1899
+ const names = [];
1900
+ const runRe = /\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?([a-zA-Z0-9:_-]+)/g;
1901
+ for (const match of text.matchAll(runRe)) {
1902
+ const candidate = match[1];
1903
+ if (candidate && candidate !== "install" && candidate !== "ci" && candidate !== "exec" && candidate !== "dlx") {
1904
+ names.push(candidate);
1905
+ }
1906
+ }
1907
+ return names;
1908
+ }
1909
+ function buildEffectiveCiText(files) {
1910
+ const workflows = files.filter((f) => f.isWorkflow);
1911
+ if (workflows.length === 0) {
1912
+ return { hasCiWorkflows: false, workflowFiles: [], effectiveCiText: "" };
1913
+ }
1914
+ const pkgScripts = parsePackageScripts(files);
1915
+ const chunks = workflows.map((w) => w.content);
1916
+ const visitedScripts = new Set;
1917
+ let frontier = chunks.join(`
1918
+ `);
1919
+ for (let depth = 0;depth < 4; depth++) {
1920
+ const nextChunks = [];
1921
+ for (const name of collectReferencedScriptNames(frontier)) {
1922
+ if (visitedScripts.has(name))
1923
+ continue;
1924
+ visitedScripts.add(name);
1925
+ const body = pkgScripts.get(name);
1926
+ if (body) {
1927
+ chunks.push(body);
1928
+ nextChunks.push(body);
1929
+ }
1930
+ }
1931
+ if (nextChunks.length === 0)
1932
+ break;
1933
+ frontier = nextChunks.join(`
1934
+ `);
1935
+ }
1936
+ const combinedSoFar = chunks.join(`
1937
+ `);
1938
+ const scriptFileRe = /\b(?:node|bun|tsx|bash|sh|python3?)\s+([a-zA-Z0-9._/-]+\.(?:[cm]?[jt]s|sh|py))\b/g;
1939
+ const fileByRel = new Map(files.map((f) => [f.rel.replace(/\\/g, "/"), f]));
1940
+ const seenScriptFiles = new Set;
1941
+ for (const match of combinedSoFar.matchAll(scriptFileRe)) {
1942
+ const rel = (match[1] ?? "").replace(/^\.\//, "");
1943
+ if (!rel || seenScriptFiles.has(rel))
1944
+ continue;
1945
+ if (!/^(?:scripts|tools|\.github)\//.test(rel))
1946
+ continue;
1947
+ seenScriptFiles.add(rel);
1948
+ const hit = fileByRel.get(rel);
1949
+ if (hit)
1950
+ chunks.push(hit.content);
1951
+ }
1952
+ return {
1953
+ hasCiWorkflows: true,
1954
+ workflowFiles: workflows.map((w) => w.rel).sort(),
1955
+ effectiveCiText: chunks.join(`
1956
+ `)
1957
+ };
1958
+ }
1959
+ function extractSignals(files, allRelPaths, languages) {
1960
+ const lowerPaths = allRelPaths.map((p) => p.toLowerCase());
1961
+ const hasPath = (re) => lowerPaths.some((p) => re.test(p));
1962
+ const manifestText = files.filter((f) => isManifestFile(f.rel)).map((f) => f.content).join(`
1963
+ `);
1964
+ const configText = files.filter((f) => isConfigFile(f)).map((f) => f.content).join(`
1965
+ `);
1966
+ const testFiles = files.filter((f) => f.isTest);
1967
+ const rawTestText = testFiles.map((f) => f.content).join(`
1968
+ `);
1969
+ const codeTestText = testFiles.map((f) => stripCodeStringsAndComments(f.content)).join(`
1970
+ `);
1971
+ const testImportLines = testFiles.flatMap((f) => f.content.split(/\r?\n/)).filter((line) => /^\s*(?:import|from|use|using|require\s*\(|const\s+\w+\s*=\s*require\()/.test(line)).join(`
1972
+ `);
1973
+ const prodImportLines = files.filter((f) => f.language && !f.isTest && !f.rel.startsWith("src/rungs/")).flatMap((f) => f.content.split(/\r?\n/)).filter((line) => /^\s*(?:import|from|use|using)\b/.test(line)).join(`
1974
+ `);
1975
+ const { hasCiWorkflows, workflowFiles, effectiveCiText } = buildEffectiveCiText(files);
1976
+ const configAndCi = `${configText}
1977
+ ${effectiveCiText}`;
1978
+ const manifestAndConfig = `${manifestText}
1979
+ ${configText}`;
1980
+ const testImportAndManifest = `${manifestText}
1981
+ ${testImportLines}`;
1982
+ const testCodeAndManifest = `${manifestText}
1983
+ ${codeTestText}`;
1984
+ const hasFormatter = hasPath(/(?:^|\/)(?:\.?prettier|oxfmt|\.editorconfig|rustfmt\.toml|\.rustfmt\.toml|biome\.jsonc?|ruff\.toml|\.ruff\.toml)/) || /\b(?:prettier|oxfmt|biome|ruff\s+format|\[tool\.ruff\]|dotnet\s+format|gofmt|rustfmt|cargo\s+fmt)\b/i.test(configAndCi);
1985
+ const hasOxlint = hasPath(/(?:^|\/)(?:\.oxlintrc\.jsonc?|oxlint\.config\.[cm]?[jt]s)$/) || /\boxlint\b/i.test(configAndCi);
1986
+ const hasLinter = hasOxlint || hasPath(/(?:^|\/)(?:\.?eslint|biome\.jsonc?|ruff\.toml|\.ruff\.toml|clippy\.toml|\.clippy\.toml|\.golangci\.ya?ml|directory\.build\.props)/) || /\b(?:eslint|oxlint|biome|ruff\s+check|clippy|golangci-lint|roslyn|AnalysisLevel|VStack\.Analyzers|veristack|vstack(?:\.mjs)?\s+(?:scan|no-comments))\b/i.test(configAndCi);
1987
+ const hasVeristackGate = /\b(?:veristack|vstack(?:\.mjs)?\s+scan|cli\.ts\s+scan|lint\/index\.mjs)\b/i.test(configAndCi) || hasPath(/(?:^|\/)lint\/index\.mjs$/);
1988
+ const hasAntiSlop = /\b(?:anti-slop|dmmulroy\/anti-slop|VStack\.Analyzers)\b/i.test(configAndCi) || hasVeristackGate;
1989
+ const hasLandmines = /@interfere\/landmines|landmines-testing|\blandmines\//i.test(configAndCi) || hasVeristackGate;
1990
+ const hasGoInternal = /\boxlint-plugin-go-internal\b/i.test(configAndCi) || hasPath(/(?:^|\/)lint\/index\.mjs$/);
1991
+ const hasDeslopPlease = hasPath(/\.deslop-please\.allow/) || /\bdeslop-please\b/i.test(configAndCi);
1992
+ const hasDesloppify = /\bdesloppify\b/i.test(configAndCi);
1993
+ const hasStrictTypes = /"strict"\s*:\s*true/.test(configText) || /<Nullable>enable<\/Nullable>/i.test(manifestAndConfig) || languages.includes("rust") || languages.includes("go") || /\b(?:mypy|pyright)\b/i.test(configAndCi);
1994
+ const hasTsgo = /\btsgo\b|@typescript\/native-preview/i.test(configAndCi);
1995
+ const hasKnipOrDeadCode = hasPath(/(?:^|\/)knip\.jsonc?$/) || /\bknip\b|"noUnusedLocals"\s*:\s*true|CS0162|IDE0051|dead_code|\bclippy\b|\bruff\s+check\b|\bgo\s+vet\b/i.test(configAndCi);
1996
+ const hasJscpd = hasPath(/jscpd/) || /\bjscpd\b/i.test(configAndCi);
1997
+ const hasArchFitness = /\b(?:dependency-cruiser|archunit|netarchtest|import-linter|deptrac|packwerk|turbo\s+boundaries|check-max-lines)\b/i.test(`${configAndCi}
1998
+ ${testImportLines}`) || hasPath(/(?:check-boundaries|arch-fitness|architecture.*test|check-max-lines)/) || hasVeristackGate;
1999
+ const hasPreCommitHook = hasPath(/(?:^|\/)(?:lefthook\.ya?ml|\.husky\/|\.pre-commit-config\.ya?ml|git-hooks\/pre-commit)/) || /core\.hooksPath/.test(configAndCi);
2000
+ const hasCodeowners = hasPath(/(?:^|\/)codeowners$/);
2001
+ const hasReviewMd = hasPath(/(?:^|\/)review\.md$/);
2002
+ const hasAgentsMd = hasPath(/(?:^|\/)(?:agents|claude)\.md$/);
2003
+ const hasPbt = /\b(?:fast-check|hypothesis|FsCheck|proptest|quickcheck)\b/i.test(testImportAndManifest) || /\b(?:fc\.property|fc\.assert|proptest!|@given\s*\(|\[Property\b)/m.test(codeTestText);
2004
+ const hasMbt = /\b(?:RuleBasedStateMachine|FsCheck\.Experimental|proptest_state_machine|ReferenceStateMachine|state_machine_test!|fc\.commands)\b/.test(codeTestText) || /\bstateright\b/i.test(testImportAndManifest);
2005
+ const hasContractTool = /\b(?:@pact-foundation|pactnet|schemathesis|openapi|asyncapi)\b/i.test(`${manifestAndConfig}
2006
+ ${testImportLines}`) || hasPath(/(?:^|\/)(?:buf\.yaml|openapi\.(?:ya?ml|json)|asyncapi\.(?:ya?ml|json)|.*\.contract\.[cm]?[jt]sx?)$/);
2007
+ const hasComponentUiTool = /@testing-library|playwright\/experimental-ct|\bstorybook\b/i.test(testImportAndManifest);
2008
+ const hasMsw = /\bmsw\b/i.test(testImportAndManifest) || /\b(?:setupServer|setupWorker)\s*\(/.test(codeTestText);
2009
+ const hasMswStrict = /onUnhandledRequest\s*:\s*["']error["']/.test(`${configText}
2010
+ ${rawTestText}`);
2011
+ const hasTestcontainersOrRealDb = /\b(?:testcontainers|@testcontainers|pglite)\b/i.test(testImportAndManifest) || /\b(?:UseNpgsql|UseSqlServer|FIRESTORE_EMULATOR_HOST|FIREBASE_AUTH_EMULATOR_HOST|firebase-emulator|Testcontainers)\b/.test(`${configAndCi}
2012
+ ${codeTestText}`);
2013
+ const hasMigrationTest = /\b(?:MigrateAsync|MigrationBuilder|alembic|flyway|prisma\s+migrate)\b/i.test(`${configAndCi}
2014
+ ${codeTestText}`);
2015
+ const hasBusDlqTest = /\b(?:DeadLetter|MaxDeliveryCount|ServiceBusClient|RabbitMQ|Kafka)\b/.test(`${manifestText}
2016
+ ${codeTestText}`);
2017
+ const hasDst = /\b(?:turmoil|antithesis)\b/i.test(testImportAndManifest) || /\b(?:deterministicSimulation|virtualClock)\b/.test(codeTestText);
2018
+ const hasDryRun = /--dry-run|terraform\s+plan|ansible[^\n]*--check/i.test(configAndCi);
2019
+ const hasMutationTool = hasPath(/(?:^|\/)(?:mutants\.toml|stryker-config\.json|stryker\.conf\.[cm]?[jt]s)$/) || /\b(?:@stryker-mutator|stryker|mutmut|cargo-mutants|pitest)\b/i.test(configAndCi) || /\b(?:vstack(?:\.mjs)?|cli\.ts)\s+bench\b/i.test(effectiveCiText);
2020
+ const hasFormalTool = hasPath(/\.(?:tla|qnt|als|dfy|lean|bend)$|formal_model_check/) || /\b(?:everystate|z3-solver|Microsoft\.Z3|stateright|kani|verus|loom|shuttle|quint|dafny|crosshair)\b/i.test(`${manifestText}
2021
+ ${testImportLines}
2022
+ ${effectiveCiText}`) || hasPath(/(?:^|\/)\.verification\/control-plan\.json$/) && hasPath(/(?:^|\/)\.verification\/laws\/.+\.laws\.json$/);
2023
+ const hasFuzzTool = /\b(?:cargo-fuzz|libFuzzer|jazzer|atheris)\b/i.test(`${manifestAndConfig}
2024
+ ${effectiveCiText}`) || /\bfuzzTest\s*\(/.test(codeTestText);
2025
+ const hasBombadil = /\bbombadil\b/i.test(configAndCi);
2026
+ const hasVisualTool = /\b(?:chromatic|percy|argos|@argos-ci)\b/i.test(configAndCi) || /\btoHaveScreenshot\s*\(/.test(codeTestText);
2027
+ const hasPerfOrLoadTool = hasPath(/(?:^|\/)(?:check-perf-budget\.[cm]?[jt]s|k6\.config\.[cm]?[jt]s|lighthouserc\.(?:json|ya?ml|[cm]?js))$/) || /\b(?:k6|BenchmarkDotNet|criterion|pytest-benchmark|web-vitals|lighthouse|@lhci\/cli)\b/i.test(`${manifestAndConfig}
2028
+ ${effectiveCiText}
2029
+ ${testImportLines}`) || /\b(?:check-perf-budget|perf:check|(?:vstack(?:\.mjs)?|cli\.ts)\s+(?:big-o|spc))\b/i.test(configAndCi);
2030
+ const hasE2eTool = /@playwright\/test|\b(?:playwright|cypress|selenium|puppeteer)\b/i.test(testImportAndManifest) || hasPath(/(?:^|\/)(?:playwright\.config\.[cm]?[jt]s|cypress\.config\.[cm]?[jt]s|maestro\/)/);
2031
+ const hasProdTelemetryOrCanary = /\b(?:@opentelemetry|opentelemetry|launchdarkly|dd-trace|@sentry|sentry-sdk|prometheus|goreplay|chaos-mesh)\b/i.test(`${manifestText}
2032
+ ${prodImportLines}
2033
+ ${effectiveCiText}`) || /\b(?:canary|synthetic|rollback|post-deploy)\b/i.test(effectiveCiText);
2034
+ const hasDiffSelection = /\b(?:testscope|--changed|--affected|affected-projects|turbo\s+run[^\n]*--filter)\b/i.test(configAndCi);
2035
+ const runsUnitTests = hasCiWorkflows && /\b(?:bun\s+test|vitest|jest|node\s+--test|mocha|ava|dotnet\s+test|cargo\s+test|pytest|go\s+test|phpunit|rspec)\b/i.test(effectiveCiText);
2036
+ const ci = {
2037
+ hasCiWorkflows,
2038
+ workflowFiles,
2039
+ runsFormatterOrLint: hasCiWorkflows && /\b(?:oxlint|oxfmt|eslint|prettier|biome|ruff\s+(?:check|format)|cargo\s+(?:fmt|clippy)|dotnet\s+(?:format|build\b[^\n]*warnaserror)|gofmt|golangci-lint|go\s+vet|(?:vstack(?:\.mjs)?|cli\.ts)\s+(?:scan|no-comments|state-machines))\b/i.test(effectiveCiText),
2040
+ runsTypeOrStructureCheck: hasCiWorkflows && /\b(?:tsc\b|tsgo\b|bun\s+(?:run\s+)?build|dotnet\s+build|cargo\s+(?:check|clippy|build)|mypy\b|pyright\b|go\s+(?:vet|build)|knip\b|deslop-please|check-max-lines|(?:vstack(?:\.mjs)?|cli\.ts)\s+scan)\b/i.test(effectiveCiText),
2041
+ runsUnitTests,
2042
+ runsBoundaryOrMbtTests: hasCiWorkflows && (runsUnitTests || /\b(?:pact|storybook|test:contract|test:component|test:mbt)\b/i.test(effectiveCiText)),
2043
+ runsIntegrationOrDbTests: hasCiWorkflows && /\b(?:testcontainers|integration|postgres|firestore|emulator|migrate|prisma\s+migrate|alembic|flyway|test:int|docker\s+compose)\b/i.test(effectiveCiText),
2044
+ runsMutationOrFormal: hasCiWorkflows && (/\b(?:stryker|mutmut|cargo-mutants|pitest|quint|tlc|dafny|kani|formal-sync|chromatic|percy|argos|bombadil)\b/i.test(effectiveCiText) || /\bbend\b[^\n]*--check-only/i.test(effectiveCiText) || /\b(?:vstack(?:\.mjs)?|cli\.ts)\s+(?:laws|bench|formal-sync)\b/i.test(effectiveCiText)),
2045
+ runsPerfOrBench: hasCiWorkflows && /\b(?:k6\b|BenchmarkDotNet|cargo\s+bench|pytest-benchmark|lighthouse|lhci|check-perf-budget|perf:check|(?:vstack(?:\.mjs)?|cli\.ts)\s+(?:big-o|spc)|load-test)\b/i.test(effectiveCiText),
2046
+ runsE2eTests: hasCiWorkflows && /\b(?:playwright|cypress|maestro|test:e2e|e2e)\b/i.test(effectiveCiText),
2047
+ runsProdVerification: hasCiWorkflows && /\b(?:synthetic|canary|rollback|smoke-prod|post-deploy|healthcheck)\b/i.test(effectiveCiText)
2048
+ };
2049
+ const signals = {
2050
+ hasFormatter,
2051
+ hasLinter,
2052
+ hasOxlint,
2053
+ hasAntiSlop,
2054
+ hasLandmines,
2055
+ hasGoInternal,
2056
+ hasDeslopPlease,
2057
+ hasDesloppify,
2058
+ hasStrictTypes,
2059
+ hasTsgo,
2060
+ hasKnipOrDeadCode,
2061
+ hasJscpd,
2062
+ hasArchFitness,
2063
+ hasPreCommitHook,
2064
+ hasCodeowners,
2065
+ hasReviewMd,
2066
+ hasAgentsMd,
2067
+ hasPbt,
2068
+ hasMbt,
2069
+ hasContractTool,
2070
+ hasComponentUiTool,
2071
+ hasMsw,
2072
+ hasMswStrict,
2073
+ hasTestcontainersOrRealDb,
2074
+ hasMigrationTest,
2075
+ hasBusDlqTest,
2076
+ hasDst,
2077
+ hasDryRun,
2078
+ hasMutationTool,
2079
+ hasFormalTool,
2080
+ hasFuzzTool,
2081
+ hasBombadil,
2082
+ hasVisualTool,
2083
+ hasPerfOrLoadTool,
2084
+ hasE2eTool,
2085
+ hasProdTelemetryOrCanary,
2086
+ hasDiffSelection
2087
+ };
2088
+ return { signals, ci };
2089
+ }
1849
2090
 
1850
2091
  // src/zero-defect/repo-config.ts
1851
2092
  import fs2 from "node:fs";
1852
- import path3 from "node:path";
2093
+ import path4 from "node:path";
1853
2094
  var VALID_LEVELS = new Set(["off", "error", "warn", "info"]);
1854
2095
  function resolveConfigFile(repoRoot, explicitConfigPath) {
1855
2096
  if (explicitConfigPath) {
1856
- const resolved = path3.isAbsolute(explicitConfigPath) ? explicitConfigPath : path3.resolve(repoRoot, explicitConfigPath);
2097
+ const resolved = path4.isAbsolute(explicitConfigPath) ? explicitConfigPath : path4.resolve(repoRoot, explicitConfigPath);
1857
2098
  if (!fs2.existsSync(resolved)) {
1858
2099
  throw new Error(`Config file not found: ${explicitConfigPath}`);
1859
2100
  }
1860
2101
  return resolved;
1861
2102
  }
1862
2103
  const candidates = [
1863
- path3.join(repoRoot, ".vstack.json"),
1864
- path3.join(repoRoot, ".verification", "vstack.json")
2104
+ path4.join(repoRoot, ".vstack.json"),
2105
+ path4.join(repoRoot, ".verification", "vstack.json")
1865
2106
  ];
1866
2107
  for (const candidate of candidates) {
1867
2108
  if (fs2.existsSync(candidate))
@@ -1878,10 +2119,10 @@ function loadRepoConfig(repoRoot, explicitConfigPath) {
1878
2119
  raw = JSON.parse(fs2.readFileSync(filePath, "utf8"));
1879
2120
  } catch (err) {
1880
2121
  const msg = err instanceof Error ? err.message : String(err);
1881
- throw new Error(`Invalid JSON in ${path3.relative(repoRoot, filePath) || filePath}: ${msg}`);
2122
+ throw new Error(`Invalid JSON in ${path4.relative(repoRoot, filePath) || filePath}: ${msg}`);
1882
2123
  }
1883
2124
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
1884
- throw new Error(`Config ${path3.relative(repoRoot, filePath)} must be a JSON object.`);
2125
+ throw new Error(`Config ${path4.relative(repoRoot, filePath)} must be a JSON object.`);
1885
2126
  }
1886
2127
  const obj = raw;
1887
2128
  const rules = {};
@@ -1907,8 +2148,8 @@ function loadRepoConfig(repoRoot, explicitConfigPath) {
1907
2148
  }
1908
2149
  }
1909
2150
  }
1910
- const rel = path3.relative(repoRoot, filePath).split(path3.sep).join("/");
1911
- return { configPath: rel || path3.basename(filePath), rules, ignore };
2151
+ const rel = path4.relative(repoRoot, filePath).split(path4.sep).join("/");
2152
+ return { configPath: rel || path4.basename(filePath), rules, ignore };
1912
2153
  }
1913
2154
  function isRuleDisabled(ruleOrCategory, config, extraDisabled) {
1914
2155
  if (extraDisabled?.includes(ruleOrCategory))
@@ -1980,7 +2221,8 @@ var SKIP_DIRS = new Set([
1980
2221
  "vendor"
1981
2222
  ]);
1982
2223
  var MAX_FILE_BYTES = 512000;
1983
- var MAX_FILES = 4000;
2224
+ var MAX_FILES = 12000;
2225
+ var PRIORITY_DIRS = new Set([".github", ".verification", ".circleci", ".husky"]);
1984
2226
  function detectLanguage(rel) {
1985
2227
  const lower = rel.toLowerCase();
1986
2228
  if (lower.endsWith(".d.ts"))
@@ -2004,7 +2246,7 @@ function detectLanguage(rel) {
2004
2246
  function isTestFilePath(rel) {
2005
2247
  const norm = rel.replace(/\\/g, "/");
2006
2248
  const lower = norm.toLowerCase();
2007
- const base = path4.posix.basename(lower);
2249
+ const base = path5.posix.basename(lower);
2008
2250
  if (/\.(?:test|spec|e2e|cy|int|integration|contract)\.[cm]?[jt]sx?$/.test(base))
2009
2251
  return true;
2010
2252
  if (/(?:^|[-_])tests?\.py$|^test[-_].*\.py$/.test(base))
@@ -2026,11 +2268,11 @@ function isTestFilePath(rel) {
2026
2268
  }
2027
2269
  function isWorkflowPath(rel) {
2028
2270
  const lower = rel.replace(/\\/g, "/").toLowerCase();
2029
- return lower.startsWith(".github/workflows/") && (lower.endsWith(".yml") || lower.endsWith(".yaml")) || lower === "azure-pipelines.yml" || lower.endsWith("/azure-pipelines.yml");
2271
+ return lower.startsWith(".github/workflows/") && (lower.endsWith(".yml") || lower.endsWith(".yaml")) || lower === "azure-pipelines.yml" || lower.endsWith("/azure-pipelines.yml") || lower === ".gitlab-ci.yml" || lower === ".circleci/config.yml" || lower === "bitbucket-pipelines.yml";
2030
2272
  }
2031
2273
  function shouldReadText(rel) {
2032
2274
  const lower = rel.replace(/\\/g, "/").toLowerCase();
2033
- const base = path4.posix.basename(lower);
2275
+ const base = path5.posix.basename(lower);
2034
2276
  if (detectLanguage(rel) !== undefined)
2035
2277
  return true;
2036
2278
  if (isWorkflowPath(rel))
@@ -2052,7 +2294,7 @@ function shouldReadText(rel) {
2052
2294
  return true;
2053
2295
  if (base === "dockerfile" || base.startsWith("dockerfile."))
2054
2296
  return true;
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);
2297
+ 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") || base === "knip.json" || base === "knip.jsonc" || /^(?:vitest|vite|playwright|cypress|k6)\.config\.[cm]?[jt]s$/.test(base) || /^\.?lighthouserc\.(?:json|ya?ml|[cm]?js)$/.test(base);
2056
2298
  }
2057
2299
  function readSafe(abs) {
2058
2300
  try {
@@ -2074,7 +2316,7 @@ function compileGlobMatcher(pattern) {
2074
2316
  }
2075
2317
  function loadIgnoreMatchers(root) {
2076
2318
  const matchers = [];
2077
- const ignorePath = path4.join(root, ".vstackignore");
2319
+ const ignorePath = path5.join(root, ".vstackignore");
2078
2320
  if (fs3.existsSync(ignorePath)) {
2079
2321
  try {
2080
2322
  const raw = fs3.readFileSync(ignorePath, "utf8");
@@ -2112,7 +2354,7 @@ function isMinifiedJs(rel, content, lines) {
2112
2354
  return false;
2113
2355
  }
2114
2356
  function discoverRepo(repoPath) {
2115
- const root = path4.resolve(repoPath);
2357
+ const root = path5.resolve(repoPath);
2116
2358
  const ignoreMatchers = loadIgnoreMatchers(root);
2117
2359
  const isIgnored = (rel) => ignoreMatchers.some((re) => re.test(rel));
2118
2360
  const files = [];
@@ -2127,22 +2369,28 @@ function discoverRepo(repoPath) {
2127
2369
  continue;
2128
2370
  }
2129
2371
  entries.sort((a, b) => a.name.localeCompare(b.name));
2372
+ const subdirs = [];
2373
+ const prioritySubdirs = [];
2130
2374
  for (const entry of entries) {
2131
2375
  if (entry.isSymbolicLink())
2132
2376
  continue;
2133
2377
  if (entry.isDirectory()) {
2134
2378
  if (SKIP_DIRS.has(entry.name))
2135
2379
  continue;
2136
- const dirRel = path4.relative(root, path4.join(dir, entry.name)).split(path4.sep).join("/");
2380
+ const dirRel = path5.relative(root, path5.join(dir, entry.name)).split(path5.sep).join("/");
2137
2381
  if (isIgnored(dirRel))
2138
2382
  continue;
2139
- stack.push(path4.join(dir, entry.name));
2383
+ const fullDir = path5.join(dir, entry.name);
2384
+ if (PRIORITY_DIRS.has(entry.name))
2385
+ prioritySubdirs.push(fullDir);
2386
+ else
2387
+ subdirs.push(fullDir);
2140
2388
  continue;
2141
2389
  }
2142
2390
  if (!entry.isFile())
2143
2391
  continue;
2144
- const abs = path4.join(dir, entry.name);
2145
- const rel = path4.relative(root, abs).split(path4.sep).join("/");
2392
+ const abs = path5.join(dir, entry.name);
2393
+ const rel = path5.relative(root, abs).split(path5.sep).join("/");
2146
2394
  if (ARCHIVED_DOCS_PATH.test(rel) || isIgnored(rel))
2147
2395
  continue;
2148
2396
  allRelPaths.push(rel);
@@ -2165,6 +2413,16 @@ function discoverRepo(repoPath) {
2165
2413
  lines
2166
2414
  });
2167
2415
  }
2416
+ for (let i = subdirs.length - 1;i >= 0; i--) {
2417
+ const nextDir = subdirs[i];
2418
+ if (nextDir)
2419
+ stack.push(nextDir);
2420
+ }
2421
+ for (let i = prioritySubdirs.length - 1;i >= 0; i--) {
2422
+ const nextDir = prioritySubdirs[i];
2423
+ if (nextDir)
2424
+ stack.push(nextDir);
2425
+ }
2168
2426
  }
2169
2427
  const languageSet = new Set;
2170
2428
  for (const file of files) {
@@ -2173,12 +2431,6 @@ function discoverRepo(repoPath) {
2173
2431
  }
2174
2432
  const languages = [...languageSet].sort();
2175
2433
  const lowerPaths = allRelPaths.map((p) => p.toLowerCase());
2176
- const allText = files.map((f) => f.content).join(`
2177
- `);
2178
- const nonDocText = files.filter((f) => !f.rel.toLowerCase().endsWith(".md")).map((f) => f.content).join(`
2179
- `);
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(`
2181
- `);
2182
2434
  const manifestText = files.filter((f) => !f.isTest && !f.isWorkflow && !f.language && !f.rel.toLowerCase().endsWith(".md")).map((f) => f.content).join(`
2183
2435
  `);
2184
2436
  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"));
@@ -2190,59 +2442,19 @@ function discoverRepo(repoPath) {
2190
2442
  archetype = "frontend";
2191
2443
  else if (hasBackendService)
2192
2444
  archetype = "service";
2193
- const hasPath = (re) => lowerPaths.some((p) => re.test(p));
2194
- const hasAny = (re) => re.test(allText);
2195
- const signals = {
2196
- hasFormatter: hasPath(/prettier|oxfmt|\.editorconfig|rustfmt|ruff/) || /\b(?:prettier|oxfmt|biome|ruff format|\[tool\.ruff\]|dotnet format|gofmt|rustfmt)\b/i.test(configText),
2197
- hasLinter: hasPath(/eslint|oxlint|biome|ruff|clippy|golangci|directory\.build\.props/) || /\b(?:eslint|oxlint|biome|ruff|clippy|golangci-lint|roslyn|AnalysisLevel|VStack\.Analyzers)\b/i.test(configText),
2198
- hasOxlint: hasPath(/oxlint/) || /\boxlint\b/i.test(configText),
2199
- hasAntiSlop: hasAny(/anti-slop|dmmulroy\/anti-slop/i),
2200
- hasLandmines: hasAny(/@interfere\/landmines|landmines-testing|landmines\//i),
2201
- hasGoInternal: hasAny(/oxlint-plugin-go-internal/i),
2202
- hasDeslopPlease: hasPath(/\.deslop-please\.allow/) || hasAny(/deslop-please/i),
2203
- hasDesloppify: hasAny(/\bdesloppify\b/i),
2204
- hasStrictTypes: /"strict"\s*:\s*true/.test(configText) || /<Nullable>enable<\/Nullable>/i.test(configText) || languages.includes("rust") || languages.includes("go") || /\b(?:mypy|pyright)\b/i.test(configText),
2205
- hasTsgo: hasAny(/\btsgo\b|@typescript\/native-preview/i),
2206
- hasKnipOrDeadCode: hasPath(/knip/) || /\bknip\b|CS0162|IDE0051|dead_code/i.test(allText),
2207
- hasJscpd: hasPath(/jscpd/) || /\bjscpd\b/i.test(configText),
2208
- hasArchFitness: hasAny(/dependency-cruiser|archunit|netarchtest|import-linter|deptrac|packwerk|turbo\s+boundaries/i) || hasPath(/check-boundaries|arch-fitness/),
2209
- hasPreCommitHook: hasPath(/lefthook|\.husky\/|\.pre-commit-config|git-hooks\/pre-commit/) || /core\.hooksPath/.test(configText),
2210
- hasCodeowners: hasPath(/(?:^|\/)codeowners$/),
2211
- hasReviewMd: hasPath(/(?:^|\/)review\.md$/),
2212
- hasAgentsMd: hasPath(/(?:^|\/)(?:agents|claude)\.md$/),
2213
- hasPbt: hasAny(/\b(?:fast-check|fc\.property|hypothesis|fscheck|proptest|quickcheck)\b/i),
2214
- hasMbt: hasAny(/\b(?:fc\.commands|RuleBasedStateMachine|modelRun|PropEr|stateright|FsCheck\.Experimental|ToProperty\s*\(\s*\)\s*\.Check|StateMachine|proptest_state_machine|ReferenceStateMachine|state_machine_test!)\b/i),
2215
- hasContractTool: hasAny(/\b(?:@pact-foundation|pactnet|schemathesis|openapi|asyncapi|buf\.yaml)\b/i),
2216
- hasComponentUiTool: hasAny(/@testing-library|playwright\/experimental-ct|storybook/i),
2217
- hasMsw: hasAny(/\b(?:msw|setupServer|setupWorker)\b/),
2218
- hasMswStrict: /onUnhandledRequest\s*:\s*["']error["']/.test(allText),
2219
- hasTestcontainersOrRealDb: hasAny(/\b(?:testcontainers|UseNpgsql|UseSqlServer|pglite|postgres:|FIRESTORE_EMULATOR_HOST|FIREBASE_AUTH_EMULATOR_HOST|firebase-emulator)\b/i),
2220
- hasMigrationTest: hasAny(/\b(?:MigrateAsync|MigrationBuilder|alembic|flyway|prisma migrate)\b/i),
2221
- hasBusDlqTest: hasAny(/\b(?:DeadLetter|MaxDeliveryCount|ServiceBusClient|RabbitMQ|Kafka)\b/i),
2222
- hasDst: hasAny(/\b(?:turmoil|antithesis|deterministic.simulation|virtualClock)\b/i),
2223
- hasDryRun: hasAny(/--dry-run|terraform plan|ansible.*--check/i),
2224
- hasMutationTool: hasAny(/\b(?:stryker|mutmut|cargo-mutants|mutants\.toml|pitest)\b/i) || hasPath(/mutants\.toml|stryker-config\.json/),
2225
- hasFormalTool: hasPath(/\.(?:tla|qnt|als|dfy|lean)$|formal_model_check/) || /\b(?:everystate|z3-solver|Microsoft\.Z3|z3::|kani|verus|stateright|loom|shuttle|quint|dafny|tlc|crosshair)\b/i.test(nonDocText),
2226
- hasFuzzTool: hasAny(/\b(?:cargo-fuzz|libFuzzer|jazzer|atheris|fuzzTest)\b/i),
2227
- hasBombadil: hasAny(/\bbombadil\b/i),
2228
- hasVisualTool: hasAny(/\b(?:toHaveScreenshot|chromatic|percy|argos|ui-diff)\b/i),
2229
- hasPerfOrLoadTool: hasAny(/\b(?:k6|BenchmarkDotNet|web-vitals|lighthouse|performance\.mark)\b/i),
2230
- hasE2eTool: hasAny(/\b(?:@playwright\/test|playwright|cypress|selenium|puppeteer)\b/i),
2231
- hasProdTelemetryOrCanary: hasAny(/\b(?:opentelemetry|launchdarkly|canary|goreplay|chaos-mesh|synthetic)\b/i),
2232
- hasDiffSelection: hasAny(/\b(?:testscope|--changed|--affected|affected-projects)\b/i)
2233
- };
2234
- return { root, files, allRelPaths, languages, archetype, signals };
2445
+ const { signals, ci } = extractSignals(files, allRelPaths, languages);
2446
+ return { root, files, allRelPaths, languages, archetype, signals, ci };
2235
2447
  }
2236
2448
 
2237
2449
  // src/system1-classifier.ts
2238
2450
  import { createHash } from "node:crypto";
2239
- import path7 from "node:path";
2451
+ import path8 from "node:path";
2240
2452
 
2241
2453
  // src/test-analyzer.ts
2242
- import path6 from "node:path";
2454
+ import path7 from "node:path";
2243
2455
 
2244
2456
  // src/anti-slop/oxc-antislop-landmines.ts
2245
- import path5 from "node:path";
2457
+ import path6 from "node:path";
2246
2458
  var UNSAFE_DICT_CS = /\b(?:I?Dictionary|ConcurrentDictionary)\s*<\s*string\s*,\s*(?:object|dynamic)\s*>/g;
2247
2459
  var UNSAFE_DICT_PY = /\b(?:dict|Dict|Mapping)\s*\[\s*str\s*,\s*Any\s*\]/g;
2248
2460
  var UNSAFE_DICT_GO = /\bmap\s*\[\s*string\s*\]\s*(?:any|interface\s*\{\s*\})/g;
@@ -2280,13 +2492,13 @@ function violatesInternalBoundary(fromRel, targetRel) {
2280
2492
  }
2281
2493
  function checkInternalBoundaryImports(file, code, ast, findings) {
2282
2494
  if ((file.language === "typescript" || file.language === "javascript") && ast) {
2283
- const dir = path5.posix.dirname(file.rel.replace(/\\/g, "/"));
2495
+ const dir = path6.posix.dirname(file.rel.replace(/\\/g, "/"));
2284
2496
  const checkSpec = (spec, offset) => {
2285
2497
  if (!spec.startsWith("."))
2286
2498
  return;
2287
2499
  if (!spec.includes("/internal/") && !spec.endsWith("/internal"))
2288
2500
  return;
2289
- const resolved = path5.posix.normalize(path5.posix.join(dir, spec));
2501
+ const resolved = path6.posix.normalize(path6.posix.join(dir, spec));
2290
2502
  const owner = violatesInternalBoundary(file.rel, resolved);
2291
2503
  if (owner) {
2292
2504
  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/'.`);
@@ -2645,7 +2857,7 @@ function scanSingleTestFile(file, repoHasEmulator) {
2645
2857
  }
2646
2858
  return count;
2647
2859
  };
2648
- const baseName = path6.posix.basename(file.rel);
2860
+ const baseName = path7.posix.basename(file.rel);
2649
2861
  if (COVERAGE_FARM_NAME.test(baseName) && !COVERAGE_POLICY_TOOLING.test(baseName)) {
2650
2862
  findings.push({
2651
2863
  id: `TS:coverage-farm:${file.rel}:1`,
@@ -2952,7 +3164,7 @@ function selectRoundRobin(items, maxCandidates) {
2952
3164
  function buildTestFacts(file, ordinal, boundary, testCaseCount, hasTableOrPbt, networkMock) {
2953
3165
  const code = maskStrings(file.content);
2954
3166
  const hasSutImport = hasNonFrameworkImport(file.content, file.language);
2955
- const coverageFarmName = COVERAGE_FARM.test(path7.posix.basename(file.rel));
3167
+ const coverageFarmName = COVERAGE_FARM.test(path8.posix.basename(file.rel));
2956
3168
  const literalOnlyAssertion = LITERAL_EXPECT.test(file.content);
2957
3169
  const selfDerivedExpectation = SELF_DERIVED.test(code);
2958
3170
  const multiStatusCount = code.match(MULTI_STATUS)?.length ?? 0;
@@ -4193,7 +4405,7 @@ function collectInstructionInputs(repoPath) {
4193
4405
  const repo = discoverRepo(repoPath);
4194
4406
  const items = [];
4195
4407
  for (const file of repo.files) {
4196
- const base = path8.posix.basename(file.rel).toLowerCase();
4408
+ const base = path9.posix.basename(file.rel).toLowerCase();
4197
4409
  if (base !== "agents.md" && base !== "claude.md" && base !== "skill.md")
4198
4410
  continue;
4199
4411
  const lines = file.content.split(/\r?\n/);
@@ -4272,7 +4484,7 @@ function formatTerminalReport(report) {
4272
4484
  const out = [];
4273
4485
  out.push(`Verification Stack Scan: ${report.repo}`);
4274
4486
  out.push(`Archetype: ${report.archetype} | Languages: ${report.languages.join(", ") || "none"} | Prod: ${s.sourceFiles} files (${s.prodLines} L) | Tests: ${s.testFiles} files (${s.testLines} L, ratio ${s.testToProdRatio}x)`);
4275
- out.push(`Summary: ${s.holeCount} rung hole/over-budget | ${s.pushDownCount} push-down opportunities | ${s.errorCount} errors (${s.cheatCount} cheats, ${s.noCommentCount} no-comments) | ${s.warnCount} warnings`);
4487
+ out.push(`Summary: ${s.holeCount} not-covered/over-budget | ${s.poorlyCoveredCount} poorly-covered | ${s.unexecutedRungCount} not running in CI | Ladder: ${s.overallCoverageScore}/100 (${s.wellCoveredCount}/${s.applicableRungCount} well-covered) | ${s.pushDownCount} push-down opportunities | ${s.errorCount} errors (${s.cheatCount} cheats, ${s.noCommentCount} no-comments) | ${s.warnCount} warnings`);
4276
4488
  if (report.config && (report.config.disabledRules.length > 0 || report.config.suppressedCount > 0)) {
4277
4489
  const src = report.config.path ?? "CLI";
4278
4490
  const disabled = report.config.disabledRules.length > 0 ? report.config.disabledRules.join(", ") : "none";
@@ -4281,9 +4493,15 @@ function formatTerminalReport(report) {
4281
4493
  out.push("");
4282
4494
  out.push("9-RUNG VERIFICATION LADDER (R0 -> R8)");
4283
4495
  for (const r of report.rungs) {
4284
- const tag = r.status.toUpperCase().padEnd(14);
4496
+ const tag = r.coverageGrade.toUpperCase().padEnd(14);
4497
+ const score = r.coverageGrade === "not-applicable" ? " -- " : `${String(r.coverageScore).padStart(3)}%`;
4498
+ const ciTag = r.coverageGrade === "not-applicable" ? "CI:N/A" : r.executedInCi ? "CI:YES" : "CI:NO ";
4285
4499
  const ev = r.evidence.length > 0 ? r.evidence.join(", ") : "none";
4286
- out.push(` ${r.rung} [${tag}] ${r.name} (${r.speedBudget} | budget: ${r.targetBudget}) -> ${ev}`);
4500
+ out.push(` ${r.rung} [${tag} ${score} ${ciTag}] ${r.name} (${r.speedBudget} | budget: ${r.targetBudget}) -> ${ev}`);
4501
+ if (r.coverageGrade !== "not-applicable") {
4502
+ out.push(` Ideal: ${r.idealCoverage}`);
4503
+ out.push(` Actual: ${r.observedCoverage}`);
4504
+ }
4287
4505
  for (const gap of r.gaps) {
4288
4506
  out.push(` GAP: ${gap}`);
4289
4507
  }
@@ -4327,14 +4545,16 @@ function formatMarkdownReport(report) {
4327
4545
  out.push("");
4328
4546
  out.push(`- **Repo:** \`${report.repo}\` | **Archetype:** \`${report.archetype}\` | **Languages:** ${report.languages.join(", ") || "none"}`);
4329
4547
  out.push(`- **Counts:** ${s.sourceFiles} prod files (${s.prodLines} L) · ${s.testFiles} test files (${s.testLines} L, ${s.testToProdRatio}x) · ${s.e2eTestCases} E2E cases`);
4330
- out.push(`- **Signals:** ${s.holeCount} rung holes/over-budget · ${s.pushDownCount} push-down opportunities · ${s.errorCount} errors (${s.cheatCount} cheats, ${s.noCommentCount} prose comments) · ${s.warnCount} warnings`);
4548
+ out.push(`- **Signals:** Ladder ${s.overallCoverageScore}/100 (${s.wellCoveredCount}/${s.applicableRungCount} well-covered, ${s.poorlyCoveredCount} poorly-covered, ${s.holeCount} not-covered/over-budget, ${s.unexecutedRungCount} not running in CI) · ${s.pushDownCount} push-down opportunities · ${s.errorCount} errors (${s.cheatCount} cheats, ${s.noCommentCount} prose comments) · ${s.warnCount} warnings`);
4331
4549
  out.push("");
4332
4550
  out.push("## 9-Rung Coverage (R0 → R8)");
4333
4551
  out.push("");
4334
- out.push("| Rung | Layer | Status | Budget | Evidence | Gaps |");
4335
- out.push("| :---: | :--- | :---: | :--- | :--- | :--- |");
4552
+ out.push("| Rung | Layer | Grade | Score | CI | Ideal Coverage | Actual | Gaps |");
4553
+ out.push("| :---: | :--- | :---: | :---: | :---: | :--- | :--- | :--- |");
4336
4554
  for (const r of report.rungs) {
4337
- out.push(`| **${r.rung}** | ${r.name} | \`${r.status}\` | ${r.targetBudget} | ${r.evidence.join("; ") || "—"} | ${r.gaps.join("; ") || "—"} |`);
4555
+ const score = r.coverageGrade === "not-applicable" ? "—" : `${r.coverageScore}%`;
4556
+ const ci = r.coverageGrade === "not-applicable" ? "N/A" : r.executedInCi ? "YES" : "NO";
4557
+ out.push(`| **${r.rung}** | ${r.name} | \`${r.coverageGrade}\` | ${score} | ${ci} | ${r.idealCoverage} | ${r.observedCoverage} | ${r.gaps.join("; ") || "—"} |`);
4338
4558
  }
4339
4559
  if (report.pushDownOpportunities.length > 0) {
4340
4560
  out.push("");
@@ -4398,7 +4618,7 @@ import fs11 from "node:fs";
4398
4618
 
4399
4619
  // src/hooks/check-file.ts
4400
4620
  import fs4 from "node:fs";
4401
- import path9 from "node:path";
4621
+ import path10 from "node:path";
4402
4622
 
4403
4623
  // src/anti-slop/universal-laws.ts
4404
4624
  var TERMINAL_STATES = "(?:Shipped|Completed|Cancelled|Canceled|Closed|Refunded|Archived|Settled|Terminated|Finalized|Deleted|Disposed)";
@@ -7063,14 +7283,27 @@ function makeSingleFileRepo(repoRoot, file) {
7063
7283
  hasE2eTool: false,
7064
7284
  hasProdTelemetryOrCanary: false,
7065
7285
  hasDiffSelection: false
7286
+ },
7287
+ ci: {
7288
+ hasCiWorkflows: false,
7289
+ workflowFiles: [],
7290
+ runsFormatterOrLint: false,
7291
+ runsTypeOrStructureCheck: false,
7292
+ runsUnitTests: false,
7293
+ runsBoundaryOrMbtTests: false,
7294
+ runsIntegrationOrDbTests: false,
7295
+ runsMutationOrFormal: false,
7296
+ runsPerfOrBench: false,
7297
+ runsE2eTests: false,
7298
+ runsProdVerification: false
7066
7299
  }
7067
7300
  };
7068
7301
  }
7069
7302
  function scanSingleFile(filePath, options = {}) {
7070
7303
  const started = performance.now();
7071
- const repoRoot = path9.resolve(options.repoRoot ?? process.cwd());
7072
- const abs = path9.isAbsolute(filePath) ? path9.resolve(filePath) : path9.resolve(repoRoot, filePath);
7073
- const rel = path9.relative(repoRoot, abs).split(path9.sep).join("/");
7304
+ const repoRoot = path10.resolve(options.repoRoot ?? process.cwd());
7305
+ const abs = path10.isAbsolute(filePath) ? path10.resolve(filePath) : path10.resolve(repoRoot, filePath);
7306
+ const rel = path10.relative(repoRoot, abs).split(path10.sep).join("/");
7074
7307
  const tier = options.tier ?? "immediate";
7075
7308
  const maxLines = options.maxLines ?? 500;
7076
7309
  const language = detectLanguage(rel);
@@ -7160,11 +7393,11 @@ function formatSingleFileReport(result) {
7160
7393
 
7161
7394
  // src/hooks/doctor.ts
7162
7395
  import fs10 from "node:fs";
7163
- import path15 from "node:path";
7396
+ import path16 from "node:path";
7164
7397
 
7165
7398
  // src/anti-slop/agent-docs.ts
7166
7399
  import fs5 from "node:fs";
7167
- import path10 from "node:path";
7400
+ import path11 from "node:path";
7168
7401
  var AGENT_DOC_BASENAME = /^(?:agents\.md|claude\.md|gemini\.md|review\.md|\.cursorrules|copilot-instructions\.md)$/i;
7169
7402
  var MAX_AGENT_DOC_LINES = 400;
7170
7403
  var BACKTICK_TOKEN = /`([^`\r\n]+)`/g;
@@ -7174,7 +7407,7 @@ function isAgentInstructionFile(rel) {
7174
7407
  const norm = rel.replace(/\\/g, "/");
7175
7408
  if (/^(?:examples|templates|tests\/fixtures)\//i.test(norm))
7176
7409
  return false;
7177
- const base = path10.posix.basename(norm);
7410
+ const base = path11.posix.basename(norm);
7178
7411
  return AGENT_DOC_BASENAME.test(base);
7179
7412
  }
7180
7413
  function collectTopLevelDirs(repoRoot) {
@@ -7244,13 +7477,13 @@ function auditAgentDocs(repo) {
7244
7477
  continue;
7245
7478
  if (seenStale.has(clean))
7246
7479
  continue;
7247
- const resolved = path10.resolve(repo.root, clean);
7248
- if (!resolved.startsWith(`${repo.root}${path10.sep}`))
7480
+ const resolved = path11.resolve(repo.root, clean);
7481
+ if (!resolved.startsWith(`${repo.root}${path11.sep}`))
7249
7482
  continue;
7250
7483
  if (fs5.existsSync(resolved))
7251
7484
  continue;
7252
- const siblingResolved = path10.resolve(path10.dirname(file.abs), clean);
7253
- if (siblingResolved.startsWith(`${repo.root}${path10.sep}`) && fs5.existsSync(siblingResolved))
7485
+ const siblingResolved = path11.resolve(path11.dirname(file.abs), clean);
7486
+ if (siblingResolved.startsWith(`${repo.root}${path11.sep}`) && fs5.existsSync(siblingResolved))
7254
7487
  continue;
7255
7488
  seenStale.add(clean);
7256
7489
  staleCount += 1;
@@ -7418,24 +7651,24 @@ function formatFormalSyncReport(findings) {
7418
7651
  import { spawnSync as spawnSync6 } from "node:child_process";
7419
7652
  import fs7 from "node:fs";
7420
7653
  import os2 from "node:os";
7421
- import path12 from "node:path";
7654
+ import path13 from "node:path";
7422
7655
 
7423
7656
  // src/zero-defect/laws.ts
7424
7657
  import { spawnSync as spawnSync5 } from "node:child_process";
7425
7658
  import fs6 from "node:fs";
7426
7659
  import os from "node:os";
7427
- import path11 from "node:path";
7660
+ import path12 from "node:path";
7428
7661
  var BEND_LAW_DECL = /^\s*(?:law|theorem)\s+([A-Za-z_][A-Za-z0-9_]*)\b/gm;
7429
7662
  var BEND_DEF_DECL = /^\s*def\s+(?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)\b/gm;
7430
7663
  var BEND_UNSAFE_ESCAPE = /(?:@unsafe\b|\?[A-Za-z_][A-Za-z0-9_]*|\b(?:unsafe|sorry|admit|todo!|panic!)\b)/g;
7431
7664
  function resolveBendBinary() {
7432
- const localBin = path11.join(os.homedir(), ".bend", "bin", "bend");
7665
+ const localBin = path12.join(os.homedir(), ".bend", "bin", "bend");
7433
7666
  if (fs6.existsSync(localBin))
7434
7667
  return localBin;
7435
7668
  return "bend";
7436
7669
  }
7437
7670
  function isLawFile(rel) {
7438
- const base = path11.posix.basename(rel);
7671
+ const base = path12.posix.basename(rel);
7439
7672
  return base === "LAWS.bend" || base === "PROOF.bend" || base.endsWith(".laws.bend") || base.endsWith(".laws.json") || /(?:^|\/)\.verification\/laws\//.test(rel);
7440
7673
  }
7441
7674
  function hasCodeownersCoverage(repo, lawRel) {
@@ -7505,11 +7738,11 @@ ${pairedProof.content}` : file.content;
7505
7738
  }
7506
7739
  function runBendVerdict(repoRoot, relPath, findings, verifiedBackends) {
7507
7740
  const bendBin = resolveBendBinary();
7508
- const absFile = path11.join(repoRoot, relPath);
7741
+ const absFile = path12.join(repoRoot, relPath);
7509
7742
  const useKernel = Boolean(process.env.BENDTT);
7510
7743
  const flag = useKernel ? "--verdict" : "--check-only";
7511
7744
  const probe = spawnSync5(bendBin, [absFile, flag], {
7512
- cwd: path11.dirname(absFile),
7745
+ cwd: path12.dirname(absFile),
7513
7746
  encoding: "utf8",
7514
7747
  timeout: 30000
7515
7748
  });
@@ -7564,7 +7797,7 @@ function auditJsonLawFile(file, repo, findings, verifiedBackends, verify) {
7564
7797
  runBendVerdict(repo.root, ref, findings, verifiedBackends);
7565
7798
  continue;
7566
7799
  }
7567
- 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", path11.join(repo.root, ref)], repo.root] : /(?:^|\/)test_[^/]+\.py$|_test\.py$/.test(ref) ? ["pytest", [path11.join(repo.root, ref)], repo.root] : ref.endsWith("_test.go") ? ["go", ["test", "."], path11.dirname(path11.join(repo.root, ref))] : null;
7800
+ 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", path12.join(repo.root, ref)], repo.root] : /(?:^|\/)test_[^/]+\.py$|_test\.py$/.test(ref) ? ["pytest", [path12.join(repo.root, ref)], repo.root] : ref.endsWith("_test.go") ? ["go", ["test", "."], path12.dirname(path12.join(repo.root, ref))] : null;
7568
7801
  if (cmdArgs) {
7569
7802
  const run = spawnSync5(cmdArgs[0], cmdArgs[1], { cwd: cmdArgs[2], encoding: "utf8", timeout: 45000 });
7570
7803
  if (run.error) {
@@ -7617,8 +7850,8 @@ function auditLaws(repo, options) {
7617
7850
  for (const file of repo.files) {
7618
7851
  if (!isLawFile(file.rel))
7619
7852
  continue;
7620
- const base = path11.posix.basename(file.rel);
7621
- const dir = path11.posix.dirname(file.rel);
7853
+ const base = path12.posix.basename(file.rel);
7854
+ const dir = path12.posix.dirname(file.rel);
7622
7855
  const siblingLaws = dir === "." ? "LAWS.bend" : `${dir}/LAWS.bend`;
7623
7856
  if (base === "PROOF.bend" && filesByRel.has(siblingLaws)) {
7624
7857
  continue;
@@ -8043,7 +8276,7 @@ function runRedBeforeFix(repoPath, baseRef, testCmd) {
8043
8276
  if (!baseRef || baseRef.startsWith("-")) {
8044
8277
  throw new Error(`Invalid git baseRef "${baseRef}".`);
8045
8278
  }
8046
- const root = path12.resolve(repoPath);
8279
+ const root = path13.resolve(repoPath);
8047
8280
  const changed = spawnSync6("git", ["status", "--porcelain"], { cwd: root, encoding: "utf8" });
8048
8281
  const diffNames = spawnSync6("git", ["diff", "--name-only", baseRef, "--"], { cwd: root, encoding: "utf8" });
8049
8282
  const candidates = new Set;
@@ -8056,7 +8289,7 @@ ${diffNames.stdout ?? ""}`.split(/\r?\n/)) {
8056
8289
  candidates.add(cleaned);
8057
8290
  }
8058
8291
  }
8059
- const copiedTestFiles = [...candidates].filter((rel) => fs7.existsSync(path12.join(root, rel)));
8292
+ const copiedTestFiles = [...candidates].filter((rel) => fs7.existsSync(path13.join(root, rel)));
8060
8293
  if (copiedTestFiles.length === 0) {
8061
8294
  return {
8062
8295
  passed: false,
@@ -8067,8 +8300,8 @@ ${diffNames.stdout ?? ""}`.split(/\r?\n/)) {
8067
8300
  reason: "No modified or added test files found to prove red-before-fix."
8068
8301
  };
8069
8302
  }
8070
- const tmpDir = fs7.mkdtempSync(path12.join(os2.tmpdir(), "vstack-rbf-"));
8071
- const worktreeDir = path12.join(tmpDir, "base");
8303
+ const tmpDir = fs7.mkdtempSync(path13.join(os2.tmpdir(), "vstack-rbf-"));
8304
+ const worktreeDir = path13.join(tmpDir, "base");
8072
8305
  try {
8073
8306
  const addWt = spawnSync6("git", ["worktree", "add", "--detach", worktreeDir, baseRef], {
8074
8307
  cwd: root,
@@ -8084,14 +8317,14 @@ ${diffNames.stdout ?? ""}`.split(/\r?\n/)) {
8084
8317
  reason: `Failed to create base worktree at ${baseRef}: ${(addWt.stderr ?? "").trim()}`
8085
8318
  };
8086
8319
  }
8087
- const resolvedWorktree = path12.resolve(worktreeDir);
8320
+ const resolvedWorktree = path13.resolve(worktreeDir);
8088
8321
  for (const rel of copiedTestFiles) {
8089
- const dest = path12.resolve(resolvedWorktree, rel);
8090
- if (!dest.startsWith(`${resolvedWorktree}${path12.sep}`)) {
8322
+ const dest = path13.resolve(resolvedWorktree, rel);
8323
+ if (!dest.startsWith(`${resolvedWorktree}${path13.sep}`)) {
8091
8324
  throw new Error(`Refusing to copy test file outside worktree: ${rel}`);
8092
8325
  }
8093
- fs7.mkdirSync(path12.dirname(dest), { recursive: true });
8094
- fs7.copyFileSync(path12.join(root, rel), dest);
8326
+ fs7.mkdirSync(path13.dirname(dest), { recursive: true });
8327
+ fs7.copyFileSync(path13.join(root, rel), dest);
8095
8328
  }
8096
8329
  const baseRun = spawnSync6(testCmd, [], { cwd: worktreeDir, shell: true, encoding: "utf8", timeout: 120000 });
8097
8330
  const headRun = spawnSync6(testCmd, [], { cwd: root, shell: true, encoding: "utf8", timeout: 120000 });
@@ -8114,18 +8347,18 @@ ${diffNames.stdout ?? ""}`.split(/\r?\n/)) {
8114
8347
 
8115
8348
  // src/hooks/install.ts
8116
8349
  import fs9 from "node:fs";
8117
- import path14 from "node:path";
8350
+ import path15 from "node:path";
8118
8351
 
8119
8352
  // src/hooks/runtime.ts
8120
8353
  import crypto from "node:crypto";
8121
8354
  import fs8 from "node:fs";
8122
8355
  import os3 from "node:os";
8123
- import path13 from "node:path";
8356
+ import path14 from "node:path";
8124
8357
  function isRecord4(v) {
8125
8358
  return typeof v === "object" && v !== null && !Array.isArray(v);
8126
8359
  }
8127
8360
  function loadHookConfig(repoRoot) {
8128
- const cfgPath = path13.join(repoRoot, ".verification", "hooks.json");
8361
+ const cfgPath = path14.join(repoRoot, ".verification", "hooks.json");
8129
8362
  const defaults = { enabled: true, tier: "immediate", harnesses: [] };
8130
8363
  if (!fs8.existsSync(cfgPath))
8131
8364
  return defaults;
@@ -8145,7 +8378,7 @@ function loadHookConfig(repoRoot) {
8145
8378
  }
8146
8379
  function sessionStatePath(repoRoot, sessionId) {
8147
8380
  const hash = crypto.createHash("sha256").update(`${repoRoot}:${sessionId}`).digest("hex").slice(0, 16);
8148
- return path13.join(os3.tmpdir(), "vstack-hook-sessions", `${hash}.json`);
8381
+ return path14.join(os3.tmpdir(), "vstack-hook-sessions", `${hash}.json`);
8149
8382
  }
8150
8383
  function readSessionState(statePath) {
8151
8384
  try {
@@ -8161,7 +8394,7 @@ function readSessionState(statePath) {
8161
8394
  }
8162
8395
  }
8163
8396
  function writeSessionState(statePath, state) {
8164
- fs8.mkdirSync(path13.dirname(statePath), { recursive: true });
8397
+ fs8.mkdirSync(path14.dirname(statePath), { recursive: true });
8165
8398
  fs8.writeFileSync(statePath, `${JSON.stringify(state)}
8166
8399
  `, "utf8");
8167
8400
  }
@@ -8169,9 +8402,9 @@ function appendAuditLog(repoRoot, auditLogPath, entry) {
8169
8402
  const target = process.env.VSTACK_HOOK_LOG || auditLogPath;
8170
8403
  if (!target)
8171
8404
  return;
8172
- const abs = path13.isAbsolute(target) ? target : path13.resolve(repoRoot, target);
8405
+ const abs = path14.isAbsolute(target) ? target : path14.resolve(repoRoot, target);
8173
8406
  try {
8174
- fs8.mkdirSync(path13.dirname(abs), { recursive: true });
8407
+ fs8.mkdirSync(path14.dirname(abs), { recursive: true });
8175
8408
  fs8.appendFileSync(abs, `${JSON.stringify({ ts: new Date().toISOString(), ...entry })}
8176
8409
  `, "utf8");
8177
8410
  } catch {
@@ -8232,7 +8465,7 @@ function executeHookEvent(event, rawStdin, options = {}) {
8232
8465
  }
8233
8466
  }
8234
8467
  const cwd = typeof payload.cwd === "string" && payload.cwd.trim() ? payload.cwd.trim() : options.repoRoot ?? process.cwd();
8235
- const repoRoot = path13.resolve(cwd);
8468
+ const repoRoot = path14.resolve(cwd);
8236
8469
  const config = loadHookConfig(repoRoot);
8237
8470
  if (!config.enabled) {
8238
8471
  return { exitCode: 0, stdout: "", findings: [] };
@@ -8354,7 +8587,7 @@ function readJsonObj(filePath) {
8354
8587
  }
8355
8588
  }
8356
8589
  function writeJsonObj(filePath, data) {
8357
- fs9.mkdirSync(path14.dirname(filePath), { recursive: true });
8590
+ fs9.mkdirSync(path15.dirname(filePath), { recursive: true });
8358
8591
  fs9.writeFileSync(filePath, `${JSON.stringify(data, null, 2)}
8359
8592
  `, "utf8");
8360
8593
  }
@@ -8380,20 +8613,20 @@ function stripHookBucket(existing) {
8380
8613
  function manifestPathFor(repoRoot, harness) {
8381
8614
  switch (harness) {
8382
8615
  case "claude":
8383
- return path14.join(repoRoot, ".claude", "settings.local.json");
8616
+ return path15.join(repoRoot, ".claude", "settings.local.json");
8384
8617
  case "codex":
8385
- return path14.join(repoRoot, ".codex", "hooks.json");
8618
+ return path15.join(repoRoot, ".codex", "hooks.json");
8386
8619
  case "cursor":
8387
- return path14.join(repoRoot, ".cursor", "hooks.json");
8620
+ return path15.join(repoRoot, ".cursor", "hooks.json");
8388
8621
  case "copilot":
8389
- return path14.join(repoRoot, ".github", "hooks", "veristack.json");
8622
+ return path15.join(repoRoot, ".github", "hooks", "veristack.json");
8390
8623
  case "grok":
8391
- return path14.join(repoRoot, ".grok", "hooks", "veristack.json");
8624
+ return path15.join(repoRoot, ".grok", "hooks", "veristack.json");
8392
8625
  }
8393
8626
  }
8394
8627
  function installHarnessManifest(repoRoot, harness, cmdPrefix) {
8395
8628
  const filePath = manifestPathFor(repoRoot, harness);
8396
- const rel = path14.relative(repoRoot, filePath).split(path14.sep).join("/");
8629
+ const rel = path15.relative(repoRoot, filePath).split(path15.sep).join("/");
8397
8630
  const doc = readJsonObj(filePath);
8398
8631
  const hooks = isRecord5(doc.hooks) ? { ...doc.hooks } : {};
8399
8632
  if (harness === "cursor") {
@@ -8428,7 +8661,7 @@ function removeHarnessManifest(repoRoot, harness) {
8428
8661
  const filePath = manifestPathFor(repoRoot, harness);
8429
8662
  if (!fs9.existsSync(filePath))
8430
8663
  return null;
8431
- const rel = path14.relative(repoRoot, filePath).split(path14.sep).join("/");
8664
+ const rel = path15.relative(repoRoot, filePath).split(path15.sep).join("/");
8432
8665
  if (harness === "copilot" || harness === "grok") {
8433
8666
  fs9.unlinkSync(filePath);
8434
8667
  return rel;
@@ -8455,8 +8688,8 @@ function removeHarnessManifest(repoRoot, harness) {
8455
8688
  return rel;
8456
8689
  }
8457
8690
  function manageHooks(repoPath, action, options = {}) {
8458
- const repoRoot = path14.resolve(repoPath);
8459
- const configPath = path14.join(repoRoot, ".verification", "hooks.json");
8691
+ const repoRoot = path15.resolve(repoPath);
8692
+ const configPath = path15.join(repoRoot, ".verification", "hooks.json");
8460
8693
  const configRel = ".verification/hooks.json";
8461
8694
  const current = loadHookConfig(repoRoot);
8462
8695
  const selected = options.harnesses && options.harnesses.length > 0 ? [...options.harnesses] : current.harnesses.length > 0 ? current.harnesses : ["claude", "codex", "cursor"];
@@ -8474,7 +8707,7 @@ function manageHooks(repoPath, action, options = {}) {
8474
8707
  configPath: configRel,
8475
8708
  enabled,
8476
8709
  harnesses: installed,
8477
- touchedManifests: installed.map((h) => path14.relative(repoRoot, manifestPathFor(repoRoot, h)).split(path14.sep).join("/")),
8710
+ touchedManifests: installed.map((h) => path15.relative(repoRoot, manifestPathFor(repoRoot, h)).split(path15.sep).join("/")),
8478
8711
  summary: `hooks: ${enabled ? "ON" : "OFF"} (tier=${current.tier}, installed=[${installed.join(", ") || "none"}]${envDisabled ? ", VSTACK_HOOK_DISABLED=1" : ""})`
8479
8712
  };
8480
8713
  }
@@ -8558,7 +8791,7 @@ function runDoctor(repoPath) {
8558
8791
  const findings = [];
8559
8792
  const hookStatus = manageHooks(repo.root, "status");
8560
8793
  for (const rel of HOOK_MANIFESTS) {
8561
- const abs = path15.join(repo.root, rel);
8794
+ const abs = path16.join(repo.root, rel);
8562
8795
  if (!fs10.existsSync(abs))
8563
8796
  continue;
8564
8797
  try {
@@ -8721,11 +8954,453 @@ function handleHooksAndDoctorCli(cmd, rest, target, asJson) {
8721
8954
  return null;
8722
8955
  }
8723
8956
 
8957
+ // src/rungs/scan-cli.ts
8958
+ import fs13 from "node:fs";
8959
+
8960
+ // src/rungs/coverage.ts
8961
+ var E2E_CAP_BY_ARCHETYPE = {
8962
+ library: { min: 0, max: 0, label: "0 (not applicable)" },
8963
+ service: { min: 1, max: 3, label: "1–3 cross-service tasks" },
8964
+ frontend: { min: 1, max: 10, label: "5–10 golden journeys" },
8965
+ fullstack: { min: 1, max: 15, label: "5–15 golden journeys" }
8966
+ };
8967
+ function finalizeRung(input) {
8968
+ if (input.notApplicable) {
8969
+ return {
8970
+ rung: input.rung,
8971
+ name: input.name,
8972
+ speedBudget: input.speedBudget,
8973
+ targetBudget: input.targetBudget,
8974
+ status: "not-applicable",
8975
+ coverageGrade: "not-applicable",
8976
+ coverageScore: 100,
8977
+ executedInCi: false,
8978
+ idealCoverage: input.idealCoverage,
8979
+ observedCoverage: input.observedCoverage,
8980
+ checks: input.checks,
8981
+ observedCount: input.observedCount,
8982
+ evidence: input.evidence,
8983
+ gaps: []
8984
+ };
8985
+ }
8986
+ const totalWeight = input.checks.reduce((sum, c) => sum + c.weight, 0);
8987
+ const earnedWeight = input.checks.reduce((sum, c) => sum + (c.passed ? c.weight : 0), 0);
8988
+ let score = input.evidence.length === 0 ? 0 : totalWeight > 0 ? Math.round(earnedWeight / totalWeight * 100) : 0;
8989
+ const gaps = [...input.gaps];
8990
+ if (!input.executedInCi && input.evidence.length > 0) {
8991
+ gaps.push(`Rung ${input.rung} is NOT executed in CI workflows — wire it into .github/workflows/ so it runs on the system`);
8992
+ score = Math.min(score, 50);
8993
+ } else if (!input.executedInCi && input.evidence.length === 0) {
8994
+ gaps.push(`Rung ${input.rung} is NOT executed in CI workflows`);
8995
+ }
8996
+ if (input.overBudget) {
8997
+ const penalty = input.overBudgetPenaltyScore ?? Math.min(score, 45);
8998
+ return {
8999
+ rung: input.rung,
9000
+ name: input.name,
9001
+ speedBudget: input.speedBudget,
9002
+ targetBudget: input.targetBudget,
9003
+ status: "over-budget",
9004
+ coverageGrade: "over-budget",
9005
+ coverageScore: Math.min(69, Math.max(0, penalty)),
9006
+ executedInCi: input.executedInCi,
9007
+ idealCoverage: input.idealCoverage,
9008
+ observedCoverage: input.observedCoverage,
9009
+ checks: input.checks,
9010
+ observedCount: input.observedCount,
9011
+ evidence: input.evidence,
9012
+ gaps
9013
+ };
9014
+ }
9015
+ let coverageGrade;
9016
+ let status;
9017
+ if (input.evidence.length === 0 || score < 25) {
9018
+ coverageGrade = "not-covered";
9019
+ status = "hole";
9020
+ } else if (!input.executedInCi || score < 80 || gaps.length > 0) {
9021
+ coverageGrade = "poorly-covered";
9022
+ status = "partial";
9023
+ if (score >= 80)
9024
+ score = 79;
9025
+ } else {
9026
+ coverageGrade = "well-covered";
9027
+ status = "covered";
9028
+ }
9029
+ return {
9030
+ rung: input.rung,
9031
+ name: input.name,
9032
+ speedBudget: input.speedBudget,
9033
+ targetBudget: input.targetBudget,
9034
+ status,
9035
+ coverageGrade,
9036
+ coverageScore: score,
9037
+ executedInCi: input.executedInCi,
9038
+ idealCoverage: input.idealCoverage,
9039
+ observedCoverage: input.observedCoverage,
9040
+ checks: input.checks,
9041
+ observedCount: input.observedCount,
9042
+ evidence: input.evidence,
9043
+ gaps
9044
+ };
9045
+ }
9046
+ function buildRungStatuses(repo, inventory) {
9047
+ const s = repo.signals;
9048
+ const ci = repo.ci;
9049
+ const isLib = repo.archetype === "library";
9050
+ const isFront = repo.archetype === "frontend";
9051
+ const isService = repo.archetype === "service" || repo.archetype === "fullstack";
9052
+ const isTs = repo.languages.includes("typescript") || repo.languages.includes("javascript");
9053
+ const prodFiles = repo.files.filter((f) => f.language && !f.isTest).length;
9054
+ const r2Files = inventory.filter((t) => t.rung === "R2");
9055
+ const r2Cases = r2Files.reduce((sum, t) => sum + Math.max(1, t.testCaseCount), 0);
9056
+ const r3Files = inventory.filter((t) => t.rung === "R3");
9057
+ const r4Files = inventory.filter((t) => t.rung === "R4");
9058
+ const e2eFiles = inventory.filter((t) => t.rung === "R7");
9059
+ const e2eCases = e2eFiles.reduce((sum, t) => sum + Math.max(1, t.testCaseCount), 0);
9060
+ const e2eCap = E2E_CAP_BY_ARCHETYPE[repo.archetype];
9061
+ const r0Evidence = [];
9062
+ const r0Gaps = [];
9063
+ const r0AntiSlopOk = !isTs || s.hasAntiSlop && s.hasLandmines;
9064
+ if (s.hasFormatter)
9065
+ r0Evidence.push("formatter");
9066
+ else
9067
+ r0Gaps.push("Add deterministic formatter (.editorconfig / prettier / oxfmt / ruff / rustfmt)");
9068
+ if (s.hasLinter)
9069
+ r0Evidence.push(s.hasOxlint ? "oxlint" : "linter");
9070
+ else
9071
+ r0Gaps.push("Add fast linter (Oxlint / Roslyn / Ruff / Clippy / golangci-lint)");
9072
+ if (isTs && !s.hasAntiSlop)
9073
+ r0Gaps.push("Add anti-slop linter (veristack/lint or dmmulroy/anti-slop)");
9074
+ if (isTs && !s.hasLandmines)
9075
+ r0Gaps.push("Add test-integrity linter (veristack/lint or @interfere/landmines)");
9076
+ if (s.hasPreCommitHook)
9077
+ r0Evidence.push("pre-commit hook");
9078
+ else
9079
+ r0Gaps.push("Wire pre-commit hook (Lefthook) < 2s");
9080
+ if (s.hasCodeowners)
9081
+ r0Evidence.push("CODEOWNERS");
9082
+ else
9083
+ r0Gaps.push("Add CODEOWNERS locking acceptance specs & CI workflows");
9084
+ const r0 = finalizeRung({
9085
+ rung: "R0",
9086
+ name: "Instant Static, Anti-Slop & Locks",
9087
+ speedBudget: "< 2 s",
9088
+ targetBudget: "100% files",
9089
+ idealCoverage: "Formatter + fast linter/anti-slop + pre-commit hook + CODEOWNERS, running in CI",
9090
+ observedCoverage: `${r0Evidence.join(", ") || "none"} | CI: ${ci.runsFormatterOrLint ? "yes" : "no"}`,
9091
+ observedCount: r0Evidence.length,
9092
+ evidence: r0Evidence,
9093
+ gaps: r0Gaps,
9094
+ executedInCi: ci.runsFormatterOrLint,
9095
+ checks: [
9096
+ { id: "r0-formatter", label: "Formatter configured", weight: 20, passed: s.hasFormatter, executed: ci.runsFormatterOrLint, detail: s.hasFormatter ? "present" : "missing" },
9097
+ { id: "r0-linter", label: "Fast linter + anti-slop", weight: 25, passed: s.hasLinter && r0AntiSlopOk, executed: ci.runsFormatterOrLint, detail: s.hasLinter && r0AntiSlopOk ? "present" : "missing linter or anti-slop" },
9098
+ { id: "r0-precommit", label: "Pre-commit hook", weight: 15, passed: s.hasPreCommitHook, executed: s.hasPreCommitHook, detail: s.hasPreCommitHook ? "present" : "missing" },
9099
+ { id: "r0-codeowners", label: "CODEOWNERS lock", weight: 10, passed: s.hasCodeowners, executed: s.hasCodeowners, detail: s.hasCodeowners ? "present" : "missing" },
9100
+ { id: "r0-ci", label: "Executed in CI", weight: 30, passed: ci.runsFormatterOrLint, executed: ci.runsFormatterOrLint, detail: ci.runsFormatterOrLint ? "running in CI" : "not invoked in CI" }
9101
+ ]
9102
+ });
9103
+ const r1Evidence = [];
9104
+ const r1Gaps = [];
9105
+ const r1ArchOk = s.hasArchFitness || s.hasGoInternal || s.hasDeslopPlease;
9106
+ if (s.hasStrictTypes)
9107
+ r1Evidence.push(s.hasTsgo ? "strict types + tsgo" : "strict types");
9108
+ else
9109
+ r1Gaps.push("Enable strict compiler mode (strict: true / Nullable enable / mypy)");
9110
+ if (s.hasKnipOrDeadCode)
9111
+ r1Evidence.push("dead-code check");
9112
+ else
9113
+ r1Gaps.push("Add dead-code check (knip / noUnusedLocals / Roslyn CS0162+ / clippy)");
9114
+ if (r1ArchOk)
9115
+ r1Evidence.push("structural/arch check");
9116
+ else
9117
+ r1Gaps.push("Add structural boundary gate (veristack, deslop-please, go-internal, or arch-fitness)");
9118
+ const r1 = finalizeRung({
9119
+ rung: "R1",
9120
+ name: "Types, Deep-Module Structure & Ratchets",
9121
+ speedBudget: "1–10 s",
9122
+ targetBudget: "100% files",
9123
+ idealCoverage: "Strict types + dead-code check + structural/arch gate, running in CI",
9124
+ observedCoverage: `${r1Evidence.join(", ") || "none"} | CI: ${ci.runsTypeOrStructureCheck ? "yes" : "no"}`,
9125
+ observedCount: r1Evidence.length,
9126
+ evidence: r1Evidence,
9127
+ gaps: r1Gaps,
9128
+ executedInCi: ci.runsTypeOrStructureCheck,
9129
+ checks: [
9130
+ { id: "r1-types", label: "Strict type checking", weight: 30, passed: s.hasStrictTypes, executed: ci.runsTypeOrStructureCheck, detail: s.hasStrictTypes ? "enabled" : "missing" },
9131
+ { id: "r1-deadcode", label: "Dead-code check", weight: 20, passed: s.hasKnipOrDeadCode, executed: ci.runsTypeOrStructureCheck, detail: s.hasKnipOrDeadCode ? "present" : "missing" },
9132
+ { id: "r1-arch", label: "Structural/arch gate", weight: 20, passed: r1ArchOk, executed: ci.runsTypeOrStructureCheck, detail: r1ArchOk ? "present" : "missing" },
9133
+ { id: "r1-ci", label: "Executed in CI", weight: 30, passed: ci.runsTypeOrStructureCheck, executed: ci.runsTypeOrStructureCheck, detail: ci.runsTypeOrStructureCheck ? "running in CI" : "not invoked in CI" }
9134
+ ]
9135
+ });
9136
+ const idealR2Files = Math.max(1, Math.min(15, Math.ceil(Math.max(1, prodFiles) * 0.25)));
9137
+ const r2ScaledOk = r2Files.length >= idealR2Files || r2Cases >= Math.max(10, idealR2Files * 2);
9138
+ const r2HasTables = r2Files.some((f) => f.hasTable);
9139
+ const r2HasPbt = s.hasPbt || r2Files.some((f) => f.hasPbt);
9140
+ const r2Evidence = [];
9141
+ const r2Gaps = [];
9142
+ if (r2Files.length > 0)
9143
+ r2Evidence.push(`${r2Files.length} pure/unit test file(s) (${r2Cases} cases)`);
9144
+ else
9145
+ r2Gaps.push(`Add pure unit tests (ideal >= ${idealR2Files} file(s) for ${prodFiles} prod files)`);
9146
+ if (r2Files.length > 0 && !r2ScaledOk) {
9147
+ r2Gaps.push(`Unit test depth is sparse (${r2Files.length} file(s), ${r2Cases} cases vs ideal >= ${idealR2Files} files for ${prodFiles} prod files)`);
9148
+ }
9149
+ if (r2HasTables)
9150
+ r2Evidence.push("Tests-as-Data tables");
9151
+ else if (r2Files.length >= 3 || prodFiles >= 10)
9152
+ r2Gaps.push("Express multi-case matrices as Tests-as-Data tables");
9153
+ if (r2HasPbt)
9154
+ r2Evidence.push("Property-Based Tests");
9155
+ else
9156
+ r2Gaps.push("Add Property-Based Testing (fast-check / Hypothesis / FsCheck / proptest) for core invariants");
9157
+ const r2 = finalizeRung({
9158
+ rung: "R2",
9159
+ name: "Pure Logic, Tables & Stateless Oracles",
9160
+ speedBudget: "10 ms–2 s",
9161
+ targetBudget: "15–40 specs",
9162
+ idealCoverage: `>= ${idealR2Files} unit file(s) + Tests-as-Data tables + Property-Based Testing, running in CI`,
9163
+ observedCoverage: `${r2Files.length} file(s) / ${r2Cases} cases, tables=${r2HasTables ? "yes" : "no"}, PBT=${r2HasPbt ? "yes" : "no"} | CI: ${ci.runsUnitTests ? "yes" : "no"}`,
9164
+ observedCount: r2Files.length,
9165
+ evidence: r2Evidence,
9166
+ gaps: r2Gaps,
9167
+ executedInCi: ci.runsUnitTests && r2Files.length > 0,
9168
+ checks: [
9169
+ { id: "r2-unit-presence", label: "Pure unit suite exists", weight: 15, passed: r2Files.length > 0, executed: ci.runsUnitTests, detail: `${r2Files.length} file(s)` },
9170
+ { id: "r2-unit-depth", label: "Scales with prod surface", weight: 15, passed: r2ScaledOk, executed: ci.runsUnitTests, detail: `${r2Files.length}/${idealR2Files} target files` },
9171
+ { id: "r2-tables", label: "Tests-as-Data tables", weight: 20, passed: r2Files.length > 0 && (r2HasTables || r2Files.length < 3 && prodFiles < 10), executed: ci.runsUnitTests, detail: r2HasTables ? "present" : "missing" },
9172
+ { id: "r2-pbt", label: "Property-Based Testing", weight: 20, passed: r2HasPbt, executed: ci.runsUnitTests, detail: r2HasPbt ? "present" : "missing" },
9173
+ { id: "r2-ci", label: "Executed in CI", weight: 30, passed: ci.runsUnitTests && r2Files.length > 0, executed: ci.runsUnitTests, detail: ci.runsUnitTests ? "running in CI" : "not invoked in CI" }
9174
+ ]
9175
+ });
9176
+ const r3HasMbt = s.hasMbt || r3Files.some((f) => f.hasMbt);
9177
+ const r3NeedUi = isFront || repo.archetype === "fullstack";
9178
+ const r3UiOk = !r3NeedUi || s.hasComponentUiTool && (!s.hasMsw || s.hasMswStrict);
9179
+ const r3ContractOk = !isService || s.hasContractTool;
9180
+ const r3LibBoundaryOk = !isLib || r3Files.length >= (prodFiles > 15 ? 2 : 1);
9181
+ const r3Evidence = [];
9182
+ const r3Gaps = [];
9183
+ if (r3Files.length > 0)
9184
+ r3Evidence.push(`${r3Files.length} in-process boundary suite(s)`);
9185
+ else
9186
+ r3Gaps.push("Add in-process boundary / host integration-lite suite(s)");
9187
+ if (r3HasMbt)
9188
+ r3Evidence.push("Stateful MBT");
9189
+ else
9190
+ r3Gaps.push("Add Stateful Model-Based Test for complex state machines / workflows");
9191
+ if (r3NeedUi) {
9192
+ if (s.hasComponentUiTool)
9193
+ r3Evidence.push("Component UI");
9194
+ else
9195
+ r3Gaps.push("Add Component UI tests (Testing Library / Playwright CT + strict MSW)");
9196
+ if (s.hasMsw && !s.hasMswStrict)
9197
+ r3Gaps.push("Set MSW onUnhandledRequest: 'error' (strict-msw)");
9198
+ }
9199
+ if (isService) {
9200
+ if (s.hasContractTool)
9201
+ r3Evidence.push("Contract tests");
9202
+ else
9203
+ r3Gaps.push("Add Producer/Consumer Contract tests (Pact / OpenAPI / AsyncAPI)");
9204
+ }
9205
+ if (isLib && r3Files.length > 0 && !r3LibBoundaryOk) {
9206
+ r3Gaps.push(`Add >= 2 in-process boundary suites for library surface (${r3Files.length} observed)`);
9207
+ }
9208
+ const r3ArchSpecificOk = r3UiOk && r3ContractOk && r3LibBoundaryOk;
9209
+ const r3CiExec = ci.runsBoundaryOrMbtTests && (r3Files.length > 0 || r3HasMbt);
9210
+ const r3 = finalizeRung({
9211
+ rung: "R3",
9212
+ name: "MBT, Component UI, Host, Contracts & Twins",
9213
+ speedBudget: "0.2–5 s",
9214
+ targetBudget: "5–15 suites",
9215
+ idealCoverage: isLib ? "In-process boundary suites (>= 2) + Stateful MBT, running in CI" : `${r3NeedUi ? "Component UI (+ strict MSW) + " : ""}${isService ? "Contracts + " : ""}boundary suites + Stateful MBT, running in CI`,
9216
+ observedCoverage: `${r3Files.length} suite(s), MBT=${r3HasMbt ? "yes" : "no"} | CI: ${r3CiExec ? "yes" : "no"}`,
9217
+ observedCount: r3Files.length,
9218
+ evidence: r3Evidence,
9219
+ gaps: r3Gaps,
9220
+ executedInCi: r3CiExec,
9221
+ checks: [
9222
+ { id: "r3-suites", label: "In-process boundary suites", weight: 25, passed: r3Files.length > 0, executed: r3CiExec, detail: `${r3Files.length} suite(s)` },
9223
+ { id: "r3-mbt", label: "Stateful MBT", weight: 25, passed: r3HasMbt, executed: r3CiExec, detail: r3HasMbt ? "present" : "missing" },
9224
+ { id: "r3-archetype", label: "Archetype boundary/UI/contracts", weight: 20, passed: r3ArchSpecificOk, executed: r3CiExec, detail: r3ArchSpecificOk ? "covered" : "incomplete" },
9225
+ { id: "r3-ci", label: "Executed in CI", weight: 30, passed: r3CiExec, executed: r3CiExec, detail: r3CiExec ? "running in CI" : "not invoked in CI" }
9226
+ ]
9227
+ });
9228
+ const r4Na = isLib || isFront;
9229
+ const r4HasReal = r4Files.length > 0 || s.hasTestcontainersOrRealDb;
9230
+ const r4Evidence = [];
9231
+ const r4Gaps = [];
9232
+ if (r4Na) {
9233
+ r4Evidence.push(`Not required for ${repo.archetype}`);
9234
+ } else {
9235
+ if (r4HasReal)
9236
+ r4Evidence.push(`${r4Files.length} real-engine integration file(s)`);
9237
+ else
9238
+ r4Gaps.push("Add isolated real-DB integration slices (Testcontainers / pglite / emulator)");
9239
+ if (s.hasMigrationTest)
9240
+ r4Evidence.push("migration check");
9241
+ else
9242
+ r4Gaps.push("Verify DB migrations against seeded old-schema rows");
9243
+ if (s.hasDst)
9244
+ r4Evidence.push("DST");
9245
+ if (s.hasDryRun)
9246
+ r4Evidence.push("dry-run check");
9247
+ }
9248
+ const r4CiExec = !r4Na && ci.runsIntegrationOrDbTests && r4HasReal;
9249
+ const r4 = finalizeRung({
9250
+ rung: "R4",
9251
+ name: "Real Engines, Migrations, Dry-Run & DST",
9252
+ speedBudget: "2–30 s",
9253
+ targetBudget: r4Na ? "0" : "3–8 slices",
9254
+ idealCoverage: r4Na ? "Not applicable" : ">= 3 real-engine integration slices + migration verification, running in CI",
9255
+ observedCoverage: r4Na ? "not applicable" : `${r4Files.length} file(s), migrations=${s.hasMigrationTest ? "yes" : "no"} | CI: ${r4CiExec ? "yes" : "no"}`,
9256
+ observedCount: r4Files.length,
9257
+ evidence: r4Evidence,
9258
+ gaps: r4Gaps,
9259
+ executedInCi: r4CiExec,
9260
+ notApplicable: r4Na,
9261
+ checks: r4Na ? [] : [
9262
+ { id: "r4-real-engine", label: "Real-engine integration slices", weight: 40, passed: r4HasReal, executed: r4CiExec, detail: `${r4Files.length} file(s)` },
9263
+ { id: "r4-migrations", label: "Migration verification", weight: 30, passed: s.hasMigrationTest, executed: r4CiExec, detail: s.hasMigrationTest ? "present" : "missing" },
9264
+ { id: "r4-ci", label: "Executed in CI", weight: 30, passed: r4CiExec, executed: r4CiExec, detail: r4CiExec ? "running in CI" : "not invoked in CI" }
9265
+ ]
9266
+ });
9267
+ const r5NeedVisual = isFront || repo.archetype === "fullstack";
9268
+ const r5Evidence = [];
9269
+ const r5Gaps = [];
9270
+ if (s.hasMutationTool)
9271
+ r5Evidence.push("mutation/precision bench");
9272
+ else
9273
+ r5Gaps.push("Add targeted mutation testing (Stryker / mutmut / cargo-mutants) or precision bench");
9274
+ if (s.hasFormalTool)
9275
+ r5Evidence.push("formal verification");
9276
+ else
9277
+ r5Gaps.push("Add R5 formal spec or model check (Bend 2 / Quint / TLA+ / Z3 / Stateright / Kani)");
9278
+ if (s.hasFuzzTool)
9279
+ r5Evidence.push("fuzzing");
9280
+ if (s.hasBombadil)
9281
+ r5Evidence.push("Bombadil UI/TUI fuzzer");
9282
+ if (s.hasVisualTool)
9283
+ r5Evidence.push("visual regression");
9284
+ else if (r5NeedVisual)
9285
+ r5Gaps.push("Add visual regression (/ui-diff, Chromatic, Percy, or Playwright screenshots)");
9286
+ const r5CiExec = ci.runsMutationOrFormal && (s.hasMutationTool || s.hasFormalTool || s.hasVisualTool);
9287
+ const r5Checks = [
9288
+ { id: "r5-mutation", label: "Mutation or precision bench", weight: 35, passed: s.hasMutationTool, executed: r5CiExec, detail: s.hasMutationTool ? "present" : "missing" },
9289
+ { id: "r5-formal", label: "Formal spec / model check", weight: r5NeedVisual ? 20 : 35, passed: s.hasFormalTool, executed: r5CiExec, detail: s.hasFormalTool ? "present" : "missing" },
9290
+ ...r5NeedVisual ? [{ id: "r5-visual", label: "Visual regression", weight: 15, passed: s.hasVisualTool, executed: r5CiExec, detail: s.hasVisualTool ? "present" : "missing" }] : [],
9291
+ { id: "r5-ci", label: "Executed in CI", weight: 30, passed: r5CiExec, executed: r5CiExec, detail: r5CiExec ? "running in CI" : "not invoked in CI" }
9292
+ ];
9293
+ const r5 = finalizeRung({
9294
+ rung: "R5",
9295
+ name: "Deep Exploration, Formal & Meta-Testing",
9296
+ speedBudget: "30 s–15 m",
9297
+ targetBudget: "Diff / Nightly",
9298
+ idealCoverage: r5NeedVisual ? "Mutation/precision bench + formal spec/model check + visual regression, running in CI" : "Mutation/precision bench + formal spec/model check, running in CI",
9299
+ observedCoverage: `${r5Evidence.join(", ") || "none"} | CI: ${r5CiExec ? "yes" : "no"}`,
9300
+ observedCount: r5Evidence.length,
9301
+ evidence: r5Evidence,
9302
+ gaps: r5Gaps,
9303
+ executedInCi: r5CiExec,
9304
+ checks: r5Checks
9305
+ });
9306
+ const r6Evidence = [];
9307
+ const r6Gaps = [];
9308
+ if (s.hasPerfOrLoadTool)
9309
+ r6Evidence.push("perf/Big-O/load benchmark");
9310
+ else {
9311
+ r6Gaps.push(isFront ? "Add frontend perf budget (Lighthouse / web-vitals) in CI" : "Add comparable perf/Big-O/load benchmark (k6 / BenchmarkDotNet / criterion / vstack big-o)");
9312
+ }
9313
+ if (s.hasDiffSelection)
9314
+ r6Evidence.push("diff-reachable PR test selection");
9315
+ const r6CiExec = ci.runsPerfOrBench && s.hasPerfOrLoadTool;
9316
+ const r6 = finalizeRung({
9317
+ rung: "R6",
9318
+ name: "Perf, Load Capacity & CI Telemetry",
9319
+ speedBudget: "2–30 m",
9320
+ targetBudget: isLib ? "1+ perf/Big-O gate" : "1–2 / svc",
9321
+ idealCoverage: isFront ? "Web-vitals / Lighthouse performance budget, running in CI" : "Comparable perf / Big-O / load benchmark with explicit budget, running in CI",
9322
+ observedCoverage: `${r6Evidence.join(", ") || "none"} | CI: ${r6CiExec ? "yes" : "no"}`,
9323
+ observedCount: r6Evidence.length,
9324
+ evidence: r6Evidence,
9325
+ gaps: r6Gaps,
9326
+ executedInCi: r6CiExec,
9327
+ checks: [
9328
+ { id: "r6-perf", label: "Perf / Big-O / load benchmark", weight: 70, passed: s.hasPerfOrLoadTool, executed: r6CiExec, detail: s.hasPerfOrLoadTool ? "present" : "missing" },
9329
+ { id: "r6-ci", label: "Executed in CI", weight: 30, passed: r6CiExec, executed: r6CiExec, detail: r6CiExec ? "running in CI" : "not invoked in CI" }
9330
+ ]
9331
+ });
9332
+ const r7Na = isLib && e2eCases === 0;
9333
+ const r7Over = e2eCases > e2eCap.max;
9334
+ const r7HasNetworkMock = e2eFiles.some((f) => f.hasNetworkMock);
9335
+ const r7Evidence = [];
9336
+ const r7Gaps = [];
9337
+ if (e2eFiles.length > 0)
9338
+ r7Evidence.push(`${e2eFiles.length} E2E file(s), ${e2eCases} case(s)`);
9339
+ if (r7Over) {
9340
+ r7Gaps.push(`E2E cases (${e2eCases}) exceed ${repo.archetype} cap (${e2eCap.label}); push matrices & stateful flows down to R2–R3`);
9341
+ } else if (!isLib && e2eFiles.length === 0) {
9342
+ r7Gaps.push(`Add ${e2eCap.label} covering real wiring + fresh-read persistence`);
9343
+ }
9344
+ if (!r7Na && r7HasNetworkMock) {
9345
+ r7Gaps.push("Remove mocked network routes from E2E tests — E2E must prove real end-to-end wiring");
9346
+ }
9347
+ const r7CiExec = !r7Na && ci.runsE2eTests && e2eFiles.length > 0;
9348
+ const r7WithinBudget = !r7Over && e2eCases >= e2eCap.min;
9349
+ const r7 = finalizeRung({
9350
+ rung: "R7",
9351
+ name: "Thin Golden-Path E2E & Hardware Proof",
9352
+ speedBudget: "2–15 m",
9353
+ targetBudget: e2eCap.label,
9354
+ idealCoverage: r7Na ? "Not applicable (0 E2E cap for library)" : `${e2eCap.label} with real wiring (no network mocks), running in CI`,
9355
+ observedCoverage: r7Na ? "not applicable" : `${e2eCases} case(s) across ${e2eFiles.length} file(s) (cap ${e2eCap.max}) | CI: ${r7CiExec ? "yes" : "no"}`,
9356
+ observedCount: e2eCases,
9357
+ evidence: r7Evidence,
9358
+ gaps: r7Gaps,
9359
+ executedInCi: r7CiExec,
9360
+ notApplicable: r7Na,
9361
+ overBudget: r7Over,
9362
+ overBudgetPenaltyScore: r7Over && e2eCases > 0 ? Math.round((e2eCap.max > 0 ? e2eCap.max : 1) / e2eCases * 100) : 0,
9363
+ checks: r7Na ? [] : [
9364
+ { id: "r7-budget", label: "Golden-path E2E within cap", weight: 50, passed: r7WithinBudget, executed: r7CiExec, detail: `${e2eCases} case(s) vs cap ${e2eCap.max}` },
9365
+ { id: "r7-real-wiring", label: "Real wiring (no mocked network)", weight: 20, passed: e2eFiles.length > 0 && !r7HasNetworkMock, executed: r7CiExec, detail: r7HasNetworkMock ? "network mocked" : "real wiring" },
9366
+ { id: "r7-ci", label: "Executed in CI", weight: 30, passed: r7CiExec, executed: r7CiExec, detail: r7CiExec ? "running in CI" : "not invoked in CI" }
9367
+ ]
9368
+ });
9369
+ const r8Evidence = [];
9370
+ const r8Gaps = [];
9371
+ if (isLib) {
9372
+ r8Evidence.push("Not required for pure library");
9373
+ } else if (s.hasProdTelemetryOrCanary) {
9374
+ r8Evidence.push("prod telemetry / progressive delivery");
9375
+ } else {
9376
+ r8Gaps.push("Wire wide-event telemetry (OpenTelemetry), 3–10 synthetics, and canary/rollback rehearsal");
9377
+ }
9378
+ const r8CiExec = !isLib && ci.runsProdVerification && s.hasProdTelemetryOrCanary;
9379
+ const r8 = finalizeRung({
9380
+ rung: "R8",
9381
+ name: "Live Production Verification",
9382
+ speedBudget: "Continuous",
9383
+ targetBudget: isLib ? "0" : "3–10 probes",
9384
+ idealCoverage: isLib ? "Not applicable" : "OpenTelemetry/wide events + synthetics + canary/rollback workflow",
9385
+ observedCoverage: isLib ? "not applicable" : `${r8Evidence.join(", ") || "none"} | CI/workflow: ${r8CiExec ? "yes" : "no"}`,
9386
+ observedCount: r8Evidence.length,
9387
+ evidence: r8Evidence,
9388
+ gaps: r8Gaps,
9389
+ executedInCi: r8CiExec,
9390
+ notApplicable: isLib,
9391
+ checks: isLib ? [] : [
9392
+ { id: "r8-telemetry", label: "Telemetry / canary instrumentation", weight: 70, passed: s.hasProdTelemetryOrCanary, executed: r8CiExec, detail: s.hasProdTelemetryOrCanary ? "present" : "missing" },
9393
+ { id: "r8-workflow", label: "Automated prod/canary check", weight: 30, passed: r8CiExec, executed: r8CiExec, detail: r8CiExec ? "wired in workflow" : "not wired in workflow" }
9394
+ ]
9395
+ });
9396
+ return [r0, r1, r2, r3, r4, r5, r6, r7, r8];
9397
+ }
9398
+
8724
9399
  // src/structure.ts
8725
- import path20 from "node:path";
9400
+ import path21 from "node:path";
8726
9401
 
8727
9402
  // src/oracle-audit.ts
8728
- import path16 from "node:path";
9403
+ import path17 from "node:path";
8729
9404
  var INSTRUCTION_NAMES = new Set(["agents.md", "claude.md", "gemini.md", "skill.md"]);
8730
9405
  var ORACLE_NO_EDIT_TOPIC = /\b(?:oracle|gherkin|feature files?|acceptance tests?|contracts\.lock)\b|(?:features|tests\/acceptance)\/|\.feature\b/i;
8731
9406
  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;
@@ -8780,7 +9455,7 @@ function parseCodeowners(text) {
8780
9455
  }
8781
9456
  function analyzeOracleAndInstructions(repo) {
8782
9457
  const findings = [];
8783
- const codeownersFiles = repo.files.filter((f) => path16.posix.basename(f.rel).toLowerCase() === "codeowners");
9458
+ const codeownersFiles = repo.files.filter((f) => path17.posix.basename(f.rel).toLowerCase() === "codeowners");
8784
9459
  const ownerRules = codeownersFiles.flatMap((f) => parseCodeowners(f.content));
8785
9460
  const oracleArtifacts = repo.allRelPaths.filter((rel) => /\.feature$/i.test(rel) || /(?:^|\/)tests\/acceptance\//i.test(rel) || /(?:^|\/)contracts\.lock\.json$/i.test(rel));
8786
9461
  if (oracleArtifacts.length > 0 && ownerRules.length > 0) {
@@ -8802,7 +9477,7 @@ function analyzeOracleAndInstructions(repo) {
8802
9477
  }
8803
9478
  }
8804
9479
  }
8805
- const instructionFiles = repo.files.filter((f) => INSTRUCTION_NAMES.has(path16.posix.basename(f.rel).toLowerCase()));
9480
+ const instructionFiles = repo.files.filter((f) => INSTRUCTION_NAMES.has(path17.posix.basename(f.rel).toLowerCase()));
8806
9481
  let forbidFile;
8807
9482
  let allowFile;
8808
9483
  let allowLine = 1;
@@ -9036,7 +9711,7 @@ function analyzeBlackHoleReplayGuards(file, ast) {
9036
9711
  }
9037
9712
 
9038
9713
  // src/ast/cross-file-graph.ts
9039
- import path17 from "node:path";
9714
+ import path18 from "node:path";
9040
9715
  var DANGEROUS_SINKS = new Set([
9041
9716
  "eval",
9042
9717
  "Function",
@@ -9071,8 +9746,8 @@ function push8(findings, file, line, rule, rung, severity, message, fix) {
9071
9746
  function resolveImport(fromRel, spec, allFiles) {
9072
9747
  if (!spec.startsWith("."))
9073
9748
  return null;
9074
- const dir = path17.posix.dirname(fromRel);
9075
- const base = path17.posix.normalize(path17.posix.join(dir, spec));
9749
+ const dir = path18.posix.dirname(fromRel);
9750
+ const base = path18.posix.normalize(path18.posix.join(dir, spec));
9076
9751
  const candidates = [
9077
9752
  base,
9078
9753
  `${base}.ts`,
@@ -9384,7 +10059,7 @@ function analyzeBlackHoleArchGates(repo) {
9384
10059
  }
9385
10060
 
9386
10061
  // src/ast/deviant-invariants.ts
9387
- import path18 from "node:path";
10062
+ import path19 from "node:path";
9388
10063
  var GENERATED_PATH3 = /(?:^|\/)(?:generated|generated-clients?|codegen|__snapshots__)\/|\.(?:gen|generated)\.[cm]?[jt]sx?$/i;
9389
10064
  var SKIP_NULL_CALLEE = new Set([
9390
10065
  "get",
@@ -9579,10 +10254,10 @@ function minePairedCleanupBeliefs(files, findings) {
9579
10254
  function mineRouteAuthBeliefs(files, findings) {
9580
10255
  const routeGroups = new Map;
9581
10256
  for (const file of files) {
9582
- const dir = path18.posix.dirname(file.rel);
10257
+ const dir = path19.posix.dirname(file.rel);
9583
10258
  if (!ROUTE_DIR_RE.test(dir))
9584
10259
  continue;
9585
- const base = path18.posix.basename(file.rel, path18.posix.extname(file.rel));
10260
+ const base = path19.posix.basename(file.rel, path19.posix.extname(file.rel));
9586
10261
  if (PUBLIC_ROUTE_FILE.test(base))
9587
10262
  continue;
9588
10263
  const list = routeGroups.get(dir) ?? [];
@@ -10644,7 +11319,7 @@ function analyzeWave7TitansBGuards(file) {
10644
11319
  }
10645
11320
 
10646
11321
  // src/zero-defect/ecosystem-guards.ts
10647
- import path19 from "node:path";
11322
+ import path20 from "node:path";
10648
11323
  var TS_ANY_ANNOTATION = /(?:[,({]\s*[A-Za-z_$][A-Za-z0-9_$]*\??\s*:\s*any\b|\)\s*:\s*any\b|<\s*any\s*>)/g;
10649
11324
  var UNBOUNDED_FETCH = /\bfetch\s*\(\s*[^,)\n]+\s*\)/g;
10650
11325
  var DYNAMIC_IMPORT_VAR = /\bimport\s*\(\s*([A-Za-z_$][A-Za-z0-9_$.]*)\s*\)/g;
@@ -10675,8 +11350,8 @@ function scanMigrationDuplicates(repo, findings) {
10675
11350
  for (const rel of repo.allRelPaths) {
10676
11351
  if (!/(?:^|\/)migrations?\//i.test(rel) || !/\.sql$/i.test(rel))
10677
11352
  continue;
10678
- const dir = path19.posix.dirname(rel);
10679
- const base = path19.posix.basename(rel);
11353
+ const dir = path20.posix.dirname(rel);
11354
+ const base = path20.posix.basename(rel);
10680
11355
  const prefixMatch = /^(\d{2,})[_-]/.exec(base);
10681
11356
  if (!prefixMatch?.[1])
10682
11357
  continue;
@@ -10697,7 +11372,7 @@ function scanMigrationDuplicates(repo, findings) {
10697
11372
  }
10698
11373
  function scanFileEcosystemGuards(file, hasTsRepo, findings) {
10699
11374
  const raw = file.content;
10700
- const baseLower = path19.posix.basename(file.rel).toLowerCase();
11375
+ const baseLower = path20.posix.basename(file.rel).toLowerCase();
10701
11376
  if (/^\.env\.(?:example|sample|template|dist)$/i.test(baseLower)) {
10702
11377
  for (const m of raw.matchAll(ENV_REAL_SECRET)) {
10703
11378
  const tok = m[0] ?? "";
@@ -11089,8 +11764,8 @@ function analyzeStructure(repo) {
11089
11764
  const dirMembers = new Map;
11090
11765
  const dirSourceFiles = new Map;
11091
11766
  for (const rel of repo.allRelPaths) {
11092
- const dir = path20.posix.dirname(rel);
11093
- const base = path20.posix.basename(rel);
11767
+ const dir = path21.posix.dirname(rel);
11768
+ const base = path21.posix.basename(rel);
11094
11769
  const members = dirMembers.get(dir) ?? new Set;
11095
11770
  members.add(base);
11096
11771
  dirMembers.set(dir, members);
@@ -11098,9 +11773,9 @@ function analyzeStructure(repo) {
11098
11773
  for (const file of repo.files) {
11099
11774
  const isGenerated = GENERATED_PATH5.test(file.rel);
11100
11775
  if (file.language && !file.isTest && !isGenerated) {
11101
- const dir = path20.posix.dirname(file.rel);
11776
+ const dir = path21.posix.dirname(file.rel);
11102
11777
  const list = dirSourceFiles.get(dir) ?? [];
11103
- list.push(path20.posix.basename(file.rel));
11778
+ list.push(path21.posix.basename(file.rel));
11104
11779
  dirSourceFiles.set(dir, list);
11105
11780
  }
11106
11781
  if (file.language && !file.isTest && !isGenerated && file.lines > WARN_FILE_LINES) {
@@ -11350,7 +12025,7 @@ function analyzeStructure(repo) {
11350
12025
  }
11351
12026
  }
11352
12027
  }
11353
- const baseLower = path20.posix.basename(file.rel).toLowerCase();
12028
+ const baseLower = path21.posix.basename(file.rel).toLowerCase();
11354
12029
  if (baseLower.endsWith(".csproj") || baseLower === "directory.build.props") {
11355
12030
  for (const match of file.content.matchAll(CSPROJ_WARN_FALSE)) {
11356
12031
  const line = lineOf5(file.content, match.index ?? 0);
@@ -11468,180 +12143,6 @@ function analyzeStructure(repo) {
11468
12143
  }
11469
12144
 
11470
12145
  // src/ladder.ts
11471
- var E2E_CAP_BY_ARCHETYPE = {
11472
- library: { max: 0, label: "0 (not applicable)" },
11473
- service: { max: 3, label: "1–3 cross-service tasks" },
11474
- frontend: { max: 10, label: "5–10 golden journeys" },
11475
- fullstack: { max: 15, label: "5–15 golden journeys" }
11476
- };
11477
- function buildRungStatuses(repo, inventory) {
11478
- const s = repo.signals;
11479
- const isLib = repo.archetype === "library";
11480
- const isFront = repo.archetype === "frontend";
11481
- const isService = repo.archetype === "service" || repo.archetype === "fullstack";
11482
- const isTs = repo.languages.includes("typescript") || repo.languages.includes("javascript");
11483
- const r2Files = inventory.filter((t) => t.rung === "R2");
11484
- const r3Files = inventory.filter((t) => t.rung === "R3");
11485
- const r4Files = inventory.filter((t) => t.rung === "R4");
11486
- const e2eFiles = inventory.filter((t) => t.rung === "R7");
11487
- const e2eCases = e2eFiles.reduce((sum, t) => sum + Math.max(1, t.testCaseCount), 0);
11488
- const e2eCap = E2E_CAP_BY_ARCHETYPE[repo.archetype];
11489
- const r0Evidence = [];
11490
- const r0Gaps = [];
11491
- if (s.hasFormatter)
11492
- r0Evidence.push("formatter");
11493
- else
11494
- r0Gaps.push("Add deterministic formatter");
11495
- if (s.hasLinter)
11496
- r0Evidence.push(s.hasOxlint ? "oxlint" : "linter");
11497
- else
11498
- r0Gaps.push("Add fast linter (Oxlint / Roslyn / Ruff / Clippy)");
11499
- if (isTs && !s.hasAntiSlop)
11500
- r0Gaps.push("Add dmmulroy/anti-slop Oxlint rules");
11501
- if (isTs && !s.hasLandmines)
11502
- r0Gaps.push("Add @interfere/landmines test-integrity Oxlint plugin");
11503
- if (s.hasPreCommitHook)
11504
- r0Evidence.push("pre-commit hook");
11505
- else
11506
- r0Gaps.push("Wire pre-commit hook (Lefthook) < 2s");
11507
- if (s.hasCodeowners)
11508
- r0Evidence.push("CODEOWNERS");
11509
- else
11510
- r0Gaps.push("Add CODEOWNERS locking acceptance specs & CI workflows");
11511
- const r1Evidence = [];
11512
- const r1Gaps = [];
11513
- if (s.hasStrictTypes)
11514
- r1Evidence.push(s.hasTsgo ? "strict types + tsgo" : "strict types");
11515
- else
11516
- r1Gaps.push("Enable strict compiler mode (strict: true / Nullable enable)");
11517
- if (s.hasKnipOrDeadCode)
11518
- r1Evidence.push("dead-code check");
11519
- else
11520
- r1Gaps.push("Add dead-code check (knip / Roslyn CS0162+)");
11521
- if (s.hasArchFitness || s.hasGoInternal || s.hasDeslopPlease)
11522
- r1Evidence.push("structural/arch check");
11523
- else
11524
- r1Gaps.push("Add structural boundary gate (deslop-please, oxlint-plugin-go-internal, or arch-fitness)");
11525
- const r2Evidence = [];
11526
- const r2Gaps = [];
11527
- if (r2Files.length > 0)
11528
- r2Evidence.push(`${r2Files.length} pure/unit test file(s)`);
11529
- if (r2Files.some((f) => f.hasTable))
11530
- r2Evidence.push("Tests-as-Data tables");
11531
- else if (r2Files.length >= 3)
11532
- r2Gaps.push("Express multi-case matrices as CSV/YAML Tests-as-Data tables");
11533
- if (s.hasPbt || r2Files.some((f) => f.hasPbt))
11534
- r2Evidence.push("Property-Based Tests");
11535
- else
11536
- r2Gaps.push("Add Property-Based Testing (fast-check / Hypothesis / FsCheck / proptest) for core invariants");
11537
- const r3Evidence = [];
11538
- const r3Gaps = [];
11539
- if (r3Files.length > 0)
11540
- r3Evidence.push(`${r3Files.length} in-process boundary suite(s)`);
11541
- if (s.hasMbt || r3Files.some((f) => f.hasMbt))
11542
- r3Evidence.push("Stateful MBT");
11543
- else
11544
- r3Gaps.push("Add Stateful Model-Based Test for complex state machines / workflows");
11545
- if (isFront || repo.archetype === "fullstack") {
11546
- if (s.hasComponentUiTool)
11547
- r3Evidence.push("Component UI");
11548
- else
11549
- r3Gaps.push("Add Component UI tests (Testing Library / Playwright CT + strict MSW)");
11550
- if (s.hasMsw && !s.hasMswStrict)
11551
- r3Gaps.push("Set MSW onUnhandledRequest: 'error' (strict-msw)");
11552
- }
11553
- if (isService) {
11554
- if (s.hasContractTool)
11555
- r3Evidence.push("Contract tests");
11556
- else
11557
- r3Gaps.push("Add Producer/Consumer Contract tests (Pact / OpenAPI / AsyncAPI)");
11558
- }
11559
- const r4Evidence = [];
11560
- const r4Gaps = [];
11561
- if (isLib) {
11562
- r4Evidence.push("Not required for pure library");
11563
- } else {
11564
- if (r4Files.length > 0 || s.hasTestcontainersOrRealDb)
11565
- r4Evidence.push(`${r4Files.length} real-engine integration file(s)`);
11566
- else if (isService)
11567
- r4Gaps.push("Add isolated real-DB integration slice (Testcontainers + 1s schema snapshot)");
11568
- if (s.hasMigrationTest)
11569
- r4Evidence.push("migration check");
11570
- else if (isService)
11571
- r4Gaps.push("Verify DB migrations against seeded old-schema rows");
11572
- if (s.hasDst)
11573
- r4Evidence.push("DST");
11574
- if (s.hasDryRun)
11575
- r4Evidence.push("dry-run check");
11576
- }
11577
- const r5Evidence = [];
11578
- const r5Gaps = [];
11579
- if (s.hasMutationTool)
11580
- r5Evidence.push("mutation testing");
11581
- else
11582
- r5Gaps.push("Add targeted mutation testing (Stryker / mutmut / cargo-mutants) on critical diffs");
11583
- if (s.hasFormalTool)
11584
- r5Evidence.push("formal verification");
11585
- else if (isService || s.hasMbt) {
11586
- r5Gaps.push("Add R5 formal spec or model check (Quint/TLA+, Z3 SMT, Stateright/Kani) for critical state machines/protocols");
11587
- }
11588
- if (s.hasFuzzTool)
11589
- r5Evidence.push("fuzzing");
11590
- if (s.hasBombadil)
11591
- r5Evidence.push("Bombadil UI/TUI fuzzer");
11592
- if (s.hasVisualTool)
11593
- r5Evidence.push("visual regression");
11594
- else if (isFront || repo.archetype === "fullstack")
11595
- r5Gaps.push("Add visual regression (/ui-diff, /gridlines, or Playwright screenshots)");
11596
- const r6Evidence = [];
11597
- const r6Gaps = [];
11598
- if (s.hasPerfOrLoadTool)
11599
- r6Evidence.push("perf/load tooling");
11600
- else if (isService)
11601
- r6Gaps.push("Add comparable perf bounds & k6 stress/spike/soak profile");
11602
- if (s.hasDiffSelection)
11603
- r6Evidence.push("diff-reachable PR test selection");
11604
- const r7Evidence = [];
11605
- const r7Gaps = [];
11606
- if (e2eFiles.length > 0)
11607
- r7Evidence.push(`${e2eFiles.length} E2E file(s), ${e2eCases} case(s)`);
11608
- if (e2eCases > e2eCap.max) {
11609
- r7Gaps.push(`E2E cases (${e2eCases}) exceed ${repo.archetype} cap (${e2eCap.label}); push matrices & stateful flows down to R2–R3`);
11610
- } else if (!isLib && e2eFiles.length === 0) {
11611
- r7Gaps.push(`Add ${e2eCap.label} covering real wiring + fresh-read persistence`);
11612
- }
11613
- const r8Evidence = [];
11614
- const r8Gaps = [];
11615
- if (isLib) {
11616
- r8Evidence.push("Not required for pure library");
11617
- } else if (s.hasProdTelemetryOrCanary) {
11618
- r8Evidence.push("prod telemetry / progressive delivery");
11619
- } else {
11620
- r8Gaps.push("Wire wide-event telemetry, 3–10 synthetics, and canary/rollback rehearsal");
11621
- }
11622
- const statusFor = (ev, gaps, na = false, over = false) => {
11623
- if (na)
11624
- return "not-applicable";
11625
- if (over)
11626
- return "over-budget";
11627
- if (ev.length === 0 && gaps.length > 0)
11628
- return "hole";
11629
- if (gaps.length > 0)
11630
- return "partial";
11631
- return "covered";
11632
- };
11633
- return [
11634
- { rung: "R0", name: "Instant Static, Anti-Slop & Locks", speedBudget: "< 2 s", targetBudget: "100% files", status: statusFor(r0Evidence, r0Gaps), observedCount: r0Evidence.length, evidence: r0Evidence, gaps: r0Gaps },
11635
- { rung: "R1", name: "Types, Deep-Module Structure & Ratchets", speedBudget: "1–10 s", targetBudget: "100% files", status: statusFor(r1Evidence, r1Gaps), observedCount: r1Evidence.length, evidence: r1Evidence, gaps: r1Gaps },
11636
- { rung: "R2", name: "Pure Logic, Tables & Stateless Oracles", speedBudget: "10 ms–2 s", targetBudget: "15–40 specs", status: statusFor(r2Evidence, r2Gaps), observedCount: r2Files.length, evidence: r2Evidence, gaps: r2Gaps },
11637
- { rung: "R3", name: "MBT, Component UI, Host, Contracts & Twins", speedBudget: "0.2–5 s", targetBudget: "5–15 suites", status: statusFor(r3Evidence, r3Gaps), observedCount: r3Files.length, evidence: r3Evidence, gaps: r3Gaps },
11638
- { rung: "R4", name: "Real Engines, Migrations, Dry-Run & DST", speedBudget: "2–30 s", targetBudget: isLib ? "0" : "3–8 slices", status: statusFor(r4Evidence, r4Gaps, isLib), observedCount: r4Files.length, evidence: r4Evidence, gaps: r4Gaps },
11639
- { rung: "R5", name: "Deep Exploration, Formal & Meta-Testing", speedBudget: "30 s–15 m", targetBudget: "Diff / Nightly", status: statusFor(r5Evidence, r5Gaps), observedCount: r5Evidence.length, evidence: r5Evidence, gaps: r5Gaps },
11640
- { rung: "R6", name: "Perf, Load Capacity & CI Telemetry", speedBudget: "2–30 m", targetBudget: "1–2 / svc", status: statusFor(r6Evidence, r6Gaps, isLib && r6Evidence.length === 0), observedCount: r6Evidence.length, evidence: r6Evidence, gaps: r6Gaps },
11641
- { rung: "R7", name: "Thin Golden-Path E2E & Hardware Proof", speedBudget: "2–15 m", targetBudget: e2eCap.label, status: statusFor(r7Evidence, r7Gaps, isLib && e2eCases === 0, e2eCases > e2eCap.max), observedCount: e2eCases, evidence: r7Evidence, gaps: r7Gaps },
11642
- { rung: "R8", name: "Live Production Verification", speedBudget: "Continuous", targetBudget: isLib ? "0" : "3–10 probes", status: statusFor(r8Evidence, r8Gaps, isLib), observedCount: r8Evidence.length, evidence: r8Evidence, gaps: r8Gaps }
11643
- ];
11644
- }
11645
12146
  function recommendMissingLinters(repo) {
11646
12147
  const s = repo.signals;
11647
12148
  const isTs = repo.languages.includes("typescript") || repo.languages.includes("javascript");
@@ -11692,6 +12193,12 @@ function scanRepo(repoPath, options = {}) {
11692
12193
  const e2eFiles = testResult.inventory.filter((t) => t.rung === "R7");
11693
12194
  const e2eTestCases = e2eFiles.reduce((sum, t) => sum + Math.max(1, t.testCaseCount), 0);
11694
12195
  const hasActiveConfig = Boolean(config.configPath) || applied.disabledRules.length > 0;
12196
+ const applicableRungs = rungs.filter((r) => r.coverageGrade !== "not-applicable");
12197
+ const wellCoveredCount = applicableRungs.filter((r) => r.coverageGrade === "well-covered").length;
12198
+ const poorlyCoveredCount = applicableRungs.filter((r) => r.coverageGrade === "poorly-covered").length;
12199
+ const holeCount = applicableRungs.filter((r) => r.coverageGrade === "not-covered" || r.coverageGrade === "over-budget").length;
12200
+ const unexecutedRungCount = applicableRungs.filter((r) => !r.executedInCi).length;
12201
+ const overallCoverageScore = applicableRungs.length > 0 ? Math.round(applicableRungs.reduce((sum, r) => sum + r.coverageScore, 0) / applicableRungs.length) : 100;
11695
12202
  return {
11696
12203
  schemaVersion: 1,
11697
12204
  repo: repo.root,
@@ -11718,7 +12225,12 @@ function scanRepo(repoPath, options = {}) {
11718
12225
  cheatCount: findings.filter((f) => f.category === "cheat").length,
11719
12226
  noCommentCount: findings.filter((f) => f.category === "no-comments").length,
11720
12227
  pushDownCount: testResult.pushDownOpportunities.length,
11721
- holeCount: rungs.filter((r) => r.status === "hole" || r.status === "over-budget").length
12228
+ holeCount,
12229
+ poorlyCoveredCount,
12230
+ wellCoveredCount,
12231
+ applicableRungCount: applicableRungs.length,
12232
+ unexecutedRungCount,
12233
+ overallCoverageScore
11722
12234
  },
11723
12235
  rungs,
11724
12236
  pushDownOpportunities: testResult.pushDownOpportunities,
@@ -11730,8 +12242,15 @@ function scanRepo(repoPath, options = {}) {
11730
12242
 
11731
12243
  // src/ratchet.ts
11732
12244
  import fs12 from "node:fs";
11733
- import path21 from "node:path";
11734
- function buildRatchetBaseline(findings) {
12245
+ import path22 from "node:path";
12246
+ var GRADE_RANK = {
12247
+ "not-covered": 0,
12248
+ "over-budget": 1,
12249
+ "poorly-covered": 2,
12250
+ "well-covered": 3,
12251
+ "not-applicable": 3
12252
+ };
12253
+ function buildRatchetBaseline(findings, rungs) {
11735
12254
  const counts = new Map;
11736
12255
  for (const f of findings) {
11737
12256
  if (f.severity === "info")
@@ -11742,9 +12261,20 @@ function buildRatchetBaseline(findings) {
11742
12261
  for (const key of [...counts.keys()].sort()) {
11743
12262
  rules[key] = counts.get(key) ?? 0;
11744
12263
  }
11745
- return { version: 1, rules };
12264
+ if (!rungs || rungs.length === 0) {
12265
+ return { version: 1, rules };
12266
+ }
12267
+ const rungMap = {};
12268
+ for (const r of rungs) {
12269
+ rungMap[r.rung] = {
12270
+ grade: r.coverageGrade,
12271
+ score: r.coverageScore,
12272
+ executedInCi: r.executedInCi
12273
+ };
12274
+ }
12275
+ return { version: 1, rules, rungs: rungMap };
11746
12276
  }
11747
- function evaluateRatchet(findings, baseline) {
12277
+ function evaluateRatchet(findings, baseline, rungs) {
11748
12278
  const current = buildRatchetBaseline(findings).rules;
11749
12279
  const allRules = new Set([...Object.keys(baseline.rules), ...Object.keys(current)]);
11750
12280
  const regressions = [];
@@ -11758,24 +12288,134 @@ function evaluateRatchet(findings, baseline) {
11758
12288
  tightenAvailable.push({ rule, baseline: baseVal, current: curVal, delta: curVal - baseVal });
11759
12289
  }
11760
12290
  }
12291
+ const rungRegressions = [];
12292
+ if (baseline.rungs && rungs) {
12293
+ for (const r of rungs) {
12294
+ const base = baseline.rungs[r.rung];
12295
+ if (!base)
12296
+ continue;
12297
+ if (GRADE_RANK[r.coverageGrade] < GRADE_RANK[base.grade]) {
12298
+ rungRegressions.push({
12299
+ rung: r.rung,
12300
+ reason: `grade regressed ${base.grade} -> ${r.coverageGrade} (${base.score}% -> ${r.coverageScore}%)`
12301
+ });
12302
+ } else if (base.executedInCi && !r.executedInCi && r.coverageGrade !== "not-applicable") {
12303
+ rungRegressions.push({
12304
+ rung: r.rung,
12305
+ reason: "stopped executing in CI workflows"
12306
+ });
12307
+ }
12308
+ }
12309
+ }
11761
12310
  return {
11762
- passed: regressions.length === 0 && tightenAvailable.length === 0,
12311
+ passed: regressions.length === 0 && tightenAvailable.length === 0 && rungRegressions.length === 0,
11763
12312
  regressions,
11764
12313
  tightenAvailable,
12314
+ rungRegressions,
11765
12315
  currentCounts: current
11766
12316
  };
11767
12317
  }
11768
12318
  function writeRatchetBaseline(filePath, baseline) {
11769
- const resolved = path21.resolve(filePath);
11770
- fs12.mkdirSync(path21.dirname(resolved), { recursive: true });
12319
+ const resolved = path22.resolve(filePath);
12320
+ fs12.mkdirSync(path22.dirname(resolved), { recursive: true });
11771
12321
  fs12.writeFileSync(resolved, `${JSON.stringify(baseline, null, 2)}
11772
12322
  `, "utf8");
11773
12323
  }
11774
12324
 
12325
+ // src/rungs/scan-cli.ts
12326
+ function parseFlagValue(args, flag) {
12327
+ const index = args.indexOf(flag);
12328
+ if (index < 0)
12329
+ return;
12330
+ return args[index + 1];
12331
+ }
12332
+ function handleScanCli(rest, target, asJson, asMd) {
12333
+ const strict = rest.includes("--strict");
12334
+ const allowMissingRungs = rest.includes("--allow-missing-rungs");
12335
+ const failOnPoorCoverage = rest.includes("--fail-on-poor-coverage");
12336
+ const configPath = parseFlagValue(rest, "--config");
12337
+ const disableRaw = parseFlagValue(rest, "--disable");
12338
+ const disableRules = disableRaw ? disableRaw.split(",").map((r) => r.trim()).filter(Boolean) : undefined;
12339
+ const ratchetPath = parseFlagValue(rest, "--ratchet");
12340
+ const updateRatchet = rest.includes("--update-ratchet");
12341
+ if (strict && (ratchetPath || updateRatchet)) {
12342
+ console.error("vstack scan --strict forbids --ratchet and --update-ratchet baselines.");
12343
+ return 1;
12344
+ }
12345
+ if (strict && (configPath || disableRules && disableRules.length > 0)) {
12346
+ console.error("vstack scan --strict forbids --config and --disable rule overrides.");
12347
+ return 1;
12348
+ }
12349
+ if (strict && allowMissingRungs) {
12350
+ console.error("vstack scan --strict forbids --allow-missing-rungs.");
12351
+ return 1;
12352
+ }
12353
+ const report = scanRepo(target, { configPath, disableRules });
12354
+ let ratchetEval;
12355
+ if (ratchetPath) {
12356
+ if (updateRatchet || !fs13.existsSync(ratchetPath)) {
12357
+ const nextBaseline = buildRatchetBaseline(report.findings, report.rungs);
12358
+ writeRatchetBaseline(ratchetPath, nextBaseline);
12359
+ ratchetEval = evaluateRatchet(report.findings, nextBaseline, report.rungs);
12360
+ } else {
12361
+ const baseline = JSON.parse(fs13.readFileSync(ratchetPath, "utf8"));
12362
+ ratchetEval = evaluateRatchet(report.findings, baseline, report.rungs);
12363
+ }
12364
+ }
12365
+ if (asJson)
12366
+ console.log(JSON.stringify(ratchetEval ? { ...report, ratchet: ratchetEval } : report, null, 2));
12367
+ else if (asMd)
12368
+ console.log(formatMarkdownReport(report));
12369
+ else {
12370
+ console.log(formatTerminalReport(report));
12371
+ if (ratchetEval) {
12372
+ console.log(`
12373
+ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
12374
+ for (const r of ratchetEval.regressions) {
12375
+ console.log(` - [REGRESSION] ${r.rule}: ${r.baseline} -> ${r.current} (+${r.delta})`);
12376
+ }
12377
+ for (const t of ratchetEval.tightenAvailable) {
12378
+ console.log(` - [TIGHTEN] ${t.rule}: ${t.baseline} -> ${t.current} (${t.delta}) — rerun with --update-ratchet`);
12379
+ }
12380
+ for (const rr of ratchetEval.rungRegressions) {
12381
+ console.log(` - [RUNG REGRESSION] ${rr.rung}: ${rr.reason}`);
12382
+ }
12383
+ }
12384
+ }
12385
+ const s = report.summary;
12386
+ if (strict) {
12387
+ if (report.config && (report.config.disabledRules.length > 0 || report.config.suppressedCount > 0)) {
12388
+ console.error("vstack scan --strict failed: .vstack.json disables or suppresses rules.");
12389
+ return 1;
12390
+ }
12391
+ if (s.totalFindings > 0 || s.errorCount > 0 || s.warnCount > 0 || s.cheatCount > 0 || s.noCommentCount > 0 || s.holeCount > 0 || s.poorlyCoveredCount > 0 || s.unexecutedRungCount > 0 || s.pushDownCount > 0) {
12392
+ return 1;
12393
+ }
12394
+ return 0;
12395
+ }
12396
+ if (ratchetEval && !ratchetEval.passed)
12397
+ return 1;
12398
+ if (!allowMissingRungs && !ratchetEval && (s.holeCount > 0 || s.unexecutedRungCount > 0)) {
12399
+ if (!asJson && !asMd) {
12400
+ console.error(`
12401
+ FAIL: ${s.holeCount} not-covered/over-budget rung(s) and ${s.unexecutedRungCount} rung(s) not executing in CI. Wire missing rungs into CI (or pass --allow-missing-rungs for snippet-only scans).`);
12402
+ }
12403
+ return 1;
12404
+ }
12405
+ if (failOnPoorCoverage && s.poorlyCoveredCount > 0)
12406
+ return 1;
12407
+ if (rest.includes("--fail-on-errors") && s.errorCount > 0)
12408
+ return 1;
12409
+ if (rest.includes("--fail-on-cheats") && (s.cheatCount > 0 || s.noCommentCount > 0)) {
12410
+ return 1;
12411
+ }
12412
+ return 0;
12413
+ }
12414
+
11775
12415
  // src/zero-defect/bench.ts
11776
- import fs13 from "node:fs";
12416
+ import fs14 from "node:fs";
11777
12417
  import os4 from "node:os";
11778
- import path22 from "node:path";
12418
+ import path23 from "node:path";
11779
12419
  function commentPrefix(lang) {
11780
12420
  if (lang === "python" || lang === "shell")
11781
12421
  return "# ";
@@ -11809,16 +12449,16 @@ const Doc = "${escaped}"
11809
12449
  `;
11810
12450
  }
11811
12451
  function runInTempDir(files) {
11812
- const dir = fs13.mkdtempSync(path22.join(os4.tmpdir(), "vstack-bench-"));
12452
+ const dir = fs14.mkdtempSync(path23.join(os4.tmpdir(), "vstack-bench-"));
11813
12453
  try {
11814
12454
  for (const [rel, content] of Object.entries(files)) {
11815
- const full = path22.join(dir, rel);
11816
- fs13.mkdirSync(path22.dirname(full), { recursive: true });
11817
- fs13.writeFileSync(full, content, "utf8");
12455
+ const full = path23.join(dir, rel);
12456
+ fs14.mkdirSync(path23.dirname(full), { recursive: true });
12457
+ fs14.writeFileSync(full, content, "utf8");
11818
12458
  }
11819
12459
  return scanRepo(dir);
11820
12460
  } finally {
11821
- fs13.rmSync(dir, { recursive: true, force: true });
12461
+ fs14.rmSync(dir, { recursive: true, force: true });
11822
12462
  }
11823
12463
  }
11824
12464
  function countRuleMap(findings) {
@@ -11832,11 +12472,11 @@ function countRuleMap(findings) {
11832
12472
  return m;
11833
12473
  }
11834
12474
  function runHistoricalReplayBench(replayDir) {
11835
- const manifestPath = path22.join(replayDir, "manifest.json");
11836
- const entries = JSON.parse(fs13.readFileSync(manifestPath, "utf8"));
12475
+ const manifestPath = path23.join(replayDir, "manifest.json");
12476
+ const entries = JSON.parse(fs14.readFileSync(manifestPath, "utf8"));
11837
12477
  const t0 = performance.now();
11838
- const beforeScan = scanRepo(path22.join(replayDir, "before"));
11839
- const afterScan = scanRepo(path22.join(replayDir, "after"));
12478
+ const beforeScan = scanRepo(path23.join(replayDir, "before"));
12479
+ const afterScan = scanRepo(path23.join(replayDir, "after"));
11840
12480
  const scanMs = Number((performance.now() - t0).toFixed(2));
11841
12481
  const beforeByFile = new Map;
11842
12482
  for (const f of beforeScan.findings) {
@@ -11874,8 +12514,8 @@ function runHistoricalReplayBench(replayDir) {
11874
12514
  if (aCnt > (bMap.get(rule) ?? 0))
11875
12515
  regressedRules.push(rule);
11876
12516
  }
11877
- const beforeRaw = fs13.readFileSync(path22.join(replayDir, "before", entry.beforeRel), "utf8");
11878
- const afterRaw = fs13.readFileSync(path22.join(replayDir, "after", entry.afterRel), "utf8");
12517
+ const beforeRaw = fs14.readFileSync(path23.join(replayDir, "before", entry.beforeRel), "utf8");
12518
+ const afterRaw = fs14.readFileSync(path23.join(replayDir, "after", entry.afterRel), "utf8");
11879
12519
  const revertEvents = buildSyntheticRevertEvents(entry.afterRel, afterRaw, beforeRaw);
11880
12520
  const revertFindings = [
11881
12521
  ...auditDiffInvariantLoss(revertEvents),
@@ -11942,17 +12582,17 @@ function runHistoricalReplayBench(replayDir) {
11942
12582
  };
11943
12583
  }
11944
12584
  function runPrecisionBench(repoRoot, corpusDir, replayDir) {
11945
- const examplesRoot = path22.join(repoRoot, "examples");
12585
+ const examplesRoot = path23.join(repoRoot, "examples");
11946
12586
  const langs = ["typescript", "csharp", "rust", "python", "go", "sql", "shell"];
11947
12587
  const languages = [];
11948
12588
  for (const lang of langs) {
11949
- const langDir = path22.join(examplesRoot, lang);
11950
- const manifestPath = path22.join(langDir, "manifest.json");
11951
- if (!fs13.existsSync(manifestPath))
12589
+ const langDir = path23.join(examplesRoot, lang);
12590
+ const manifestPath = path23.join(langDir, "manifest.json");
12591
+ if (!fs14.existsSync(manifestPath))
11952
12592
  continue;
11953
- const manifest = JSON.parse(fs13.readFileSync(manifestPath, "utf8"));
11954
- const caughtDir = path22.join(langDir, "caught");
11955
- const cleanDir = path22.join(langDir, "clean");
12593
+ const manifest = JSON.parse(fs14.readFileSync(manifestPath, "utf8"));
12594
+ const caughtDir = path23.join(langDir, "caught");
12595
+ const cleanDir = path23.join(langDir, "clean");
11956
12596
  const t0 = performance.now();
11957
12597
  const caughtScan = scanRepo(caughtDir);
11958
12598
  const cleanScan = scanRepo(cleanDir);
@@ -11981,7 +12621,7 @@ function runPrecisionBench(repoRoot, corpusDir, replayDir) {
11981
12621
  for (const relFile of Object.keys(manifest.caught)) {
11982
12622
  if (/test|spec/i.test(relFile))
11983
12623
  continue;
11984
- const content = fs13.readFileSync(path22.join(caughtDir, relFile), "utf8");
12624
+ const content = fs14.readFileSync(path23.join(caughtDir, relFile), "utf8");
11985
12625
  commentedFiles[relFile] = wrapInComments(content, lang);
11986
12626
  const wrappedStr = wrapInStringLiteral(content, lang);
11987
12627
  if (wrappedStr !== null)
@@ -12005,7 +12645,7 @@ function runPrecisionBench(repoRoot, corpusDir, replayDir) {
12005
12645
  });
12006
12646
  }
12007
12647
  let corpusFindingsPer10kLoc;
12008
- if (corpusDir && fs13.existsSync(corpusDir)) {
12648
+ if (corpusDir && fs14.existsSync(corpusDir)) {
12009
12649
  const corpusReport = scanRepo(corpusDir);
12010
12650
  const loc = Math.max(1, corpusReport.summary.prodLines + corpusReport.summary.testLines);
12011
12651
  corpusFindingsPer10kLoc = Number((corpusReport.findings.length / loc * 1e4).toFixed(2));
@@ -12015,7 +12655,7 @@ function runPrecisionBench(repoRoot, corpusDir, replayDir) {
12015
12655
  const totalCleanFps = languages.reduce((s, l) => s + l.cleanFalsePositives.length, 0);
12016
12656
  const totalAdversarialFps = languages.reduce((s, l) => s + l.commentWrappedFps.length + l.stringWrappedFps.length, 0);
12017
12657
  const totalScanMs = Number(languages.reduce((s, l) => s + l.scanMs, 0).toFixed(2));
12018
- const replay = replayDir && fs13.existsSync(path22.join(replayDir, "manifest.json")) ? runHistoricalReplayBench(replayDir) : undefined;
12658
+ const replay = replayDir && fs14.existsSync(path23.join(replayDir, "manifest.json")) ? runHistoricalReplayBench(replayDir) : undefined;
12019
12659
  return {
12020
12660
  passed: totalExpectedRules === totalMatchedRules && totalCleanFps === 0 && totalAdversarialFps === 0,
12021
12661
  totalExpectedRules,
@@ -12151,8 +12791,8 @@ function fitEmpiricalBigO(samples, thresholds = { maxTimeExponent: 1.45 }) {
12151
12791
  }
12152
12792
 
12153
12793
  // src/zero-defect/daikon-invariants.ts
12154
- import fs14 from "node:fs";
12155
- import path23 from "node:path";
12794
+ import fs15 from "node:fs";
12795
+ import path24 from "node:path";
12156
12796
  function runtimeType(val) {
12157
12797
  if (val === null)
12158
12798
  return "null";
@@ -12313,9 +12953,9 @@ function compareInvariantSnapshots(baseline, current, baselineFile = ".verificat
12313
12953
  };
12314
12954
  }
12315
12955
  function writeInvariantSnapshot(filePath, snapshot) {
12316
- const resolved = path23.resolve(filePath);
12317
- fs14.mkdirSync(path23.dirname(resolved), { recursive: true });
12318
- fs14.writeFileSync(resolved, `${JSON.stringify(snapshot, null, 2)}
12956
+ const resolved = path24.resolve(filePath);
12957
+ fs15.mkdirSync(path24.dirname(resolved), { recursive: true });
12958
+ fs15.writeFileSync(resolved, `${JSON.stringify(snapshot, null, 2)}
12319
12959
  `, "utf8");
12320
12960
  }
12321
12961
  function formatInvariantDiffReport(snapshot, diff) {
@@ -12343,7 +12983,7 @@ function formatInvariantDiffReport(snapshot, diff) {
12343
12983
 
12344
12984
  // src/anti-slop/review-brief.ts
12345
12985
  import { spawnSync as spawnSync7 } from "node:child_process";
12346
- import path24 from "node:path";
12986
+ import path25 from "node:path";
12347
12987
  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;
12348
12988
  var DOC_FILE = /\.(?:md|mdx|txt|rst)$/i;
12349
12989
  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;
@@ -12428,7 +13068,7 @@ function buildBlindSpots(files, docLinesAdded, additionBias) {
12428
13068
  return spots;
12429
13069
  }
12430
13070
  function buildReviewBrief(repoPath, options = {}) {
12431
- const repoRoot = path24.resolve(repoPath);
13071
+ const repoRoot = path25.resolve(repoPath);
12432
13072
  const baseRef = options.baseRef ?? "HEAD";
12433
13073
  validateBaseRef(baseRef);
12434
13074
  const maxLines = options.maxLines ?? 600;
@@ -12469,7 +13109,7 @@ function buildReviewBrief(repoPath, options = {}) {
12469
13109
  linesDeleted += deleted;
12470
13110
  if (!LOCK_OR_GENERATED.test(file)) {
12471
13111
  nonLockfileLinesAdded += added;
12472
- const dir = path24.posix.dirname(file);
13112
+ const dir = path25.posix.dirname(file);
12473
13113
  dirs.add(dir === "." ? "<root>" : dir);
12474
13114
  }
12475
13115
  if (DOC_FILE.test(file))
@@ -12668,7 +13308,7 @@ function usage() {
12668
13308
  "vstack — Deterministic Verification Stack, Push-Down Analyzer, Formal Checks & JEV-Style System 1 Circuits",
12669
13309
  "",
12670
13310
  "Commands:",
12671
- " vstack scan [dir] [--json | --md] [--config <file>] [--disable <rules>] [--ratchet <file>] [--update-ratchet] [--strict] [--fail-on-cheats] [--fail-on-errors]",
13311
+ " vstack scan [dir] [--json | --md] [--config <file>] [--disable <rules>] [--ratchet <file>] [--update-ratchet] [--strict] [--allow-missing-rungs] [--fail-on-poor-coverage] [--fail-on-cheats] [--fail-on-errors]",
12672
13312
  " vstack no-comments [dir] [--json] [--fail]",
12673
13313
  " vstack state-machines [dir] [--json] [--fail]",
12674
13314
  " vstack diff-cheats [dir] [--base <ref>] [--json] [--fail]",
@@ -12691,7 +13331,7 @@ function usage() {
12691
13331
  ].join(`
12692
13332
  `);
12693
13333
  }
12694
- function parseFlagValue(args, flag) {
13334
+ function parseFlagValue2(args, flag) {
12695
13335
  const index = args.indexOf(flag);
12696
13336
  if (index < 0)
12697
13337
  return;
@@ -12762,68 +13402,7 @@ async function run() {
12762
13402
  if (hookOrDoctorCode !== null)
12763
13403
  return hookOrDoctorCode;
12764
13404
  if (cmd === "scan") {
12765
- const strict = rest.includes("--strict");
12766
- const configPath = parseFlagValue(rest, "--config");
12767
- const disableRaw = parseFlagValue(rest, "--disable");
12768
- const disableRules = disableRaw ? disableRaw.split(",").map((r) => r.trim()).filter(Boolean) : undefined;
12769
- const ratchetPath = parseFlagValue(rest, "--ratchet");
12770
- const updateRatchet = rest.includes("--update-ratchet");
12771
- if (strict && (ratchetPath || updateRatchet)) {
12772
- console.error("vstack scan --strict forbids --ratchet and --update-ratchet baselines.");
12773
- return 1;
12774
- }
12775
- if (strict && (configPath || disableRules && disableRules.length > 0)) {
12776
- console.error("vstack scan --strict forbids --config and --disable rule overrides.");
12777
- return 1;
12778
- }
12779
- const report = scanRepo(target, { configPath, disableRules });
12780
- let ratchetEval;
12781
- if (ratchetPath) {
12782
- if (updateRatchet || !fs15.existsSync(ratchetPath)) {
12783
- const nextBaseline = buildRatchetBaseline(report.findings);
12784
- writeRatchetBaseline(ratchetPath, nextBaseline);
12785
- ratchetEval = evaluateRatchet(report.findings, nextBaseline);
12786
- } else {
12787
- const baseline = JSON.parse(fs15.readFileSync(ratchetPath, "utf8"));
12788
- ratchetEval = evaluateRatchet(report.findings, baseline);
12789
- }
12790
- }
12791
- if (asJson)
12792
- console.log(JSON.stringify(ratchetEval ? { ...report, ratchet: ratchetEval } : report, null, 2));
12793
- else if (asMd)
12794
- console.log(formatMarkdownReport(report));
12795
- else {
12796
- console.log(formatTerminalReport(report));
12797
- if (ratchetEval) {
12798
- console.log(`
12799
- RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
12800
- for (const r of ratchetEval.regressions) {
12801
- console.log(` - [REGRESSION] ${r.rule}: ${r.baseline} -> ${r.current} (+${r.delta})`);
12802
- }
12803
- for (const t of ratchetEval.tightenAvailable) {
12804
- console.log(` - [TIGHTEN] ${t.rule}: ${t.baseline} -> ${t.current} (${t.delta}) — rerun with --update-ratchet`);
12805
- }
12806
- }
12807
- }
12808
- if (strict) {
12809
- if (report.config && (report.config.disabledRules.length > 0 || report.config.suppressedCount > 0)) {
12810
- console.error("vstack scan --strict failed: .vstack.json disables or suppresses rules.");
12811
- return 1;
12812
- }
12813
- const s = report.summary;
12814
- if (s.totalFindings > 0 || s.errorCount > 0 || s.warnCount > 0 || s.cheatCount > 0 || s.noCommentCount > 0 || s.holeCount > 0 || s.pushDownCount > 0) {
12815
- return 1;
12816
- }
12817
- return 0;
12818
- }
12819
- if (ratchetEval && !ratchetEval.passed)
12820
- return 1;
12821
- if (rest.includes("--fail-on-errors") && report.summary.errorCount > 0)
12822
- return 1;
12823
- if (rest.includes("--fail-on-cheats") && (report.summary.cheatCount > 0 || report.summary.noCommentCount > 0)) {
12824
- return 1;
12825
- }
12826
- return 0;
13405
+ return handleScanCli(rest, target, asJson, asMd);
12827
13406
  }
12828
13407
  if (cmd === "formal-sync") {
12829
13408
  const repo = discoverRepo(target);
@@ -12844,8 +13423,8 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
12844
13423
  return rest.includes("--fail") && result.findings.length > 0 ? 1 : 0;
12845
13424
  }
12846
13425
  if (cmd === "bench") {
12847
- const corpus = parseFlagValue(rest, "--corpus");
12848
- const replay = parseFlagValue(rest, "--replay");
13426
+ const corpus = parseFlagValue2(rest, "--corpus");
13427
+ const replay = parseFlagValue2(rest, "--replay");
12849
13428
  const report = runPrecisionBench(target, corpus, replay);
12850
13429
  if (asJson)
12851
13430
  console.log(JSON.stringify(report, null, 2));
@@ -12871,16 +13450,16 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
12871
13450
  return rest.includes("--fail") && findings.length > 0 ? 1 : 0;
12872
13451
  }
12873
13452
  if (cmd === "diff-cheats") {
12874
- const baseRef = parseFlagValue(rest, "--base") ?? "HEAD";
13453
+ const baseRef = parseFlagValue2(rest, "--base") ?? "HEAD";
12875
13454
  const findings = scanGitDiffCheats(target, baseRef);
12876
13455
  console.log(formatFindingsList(`diff-cheats (${baseRef})`, findings, asJson));
12877
13456
  return rest.includes("--fail") && findings.length > 0 ? 1 : 0;
12878
13457
  }
12879
13458
  if (cmd === "review-brief") {
12880
- const baseRef = parseFlagValue(rest, "--base") ?? "HEAD";
12881
- const maxLinesRaw = parseFlagValue(rest, "--max-lines");
12882
- const maxDirsRaw = parseFlagValue(rest, "--max-dirs");
12883
- const maxDocRaw = parseFlagValue(rest, "--max-doc-lines");
13459
+ const baseRef = parseFlagValue2(rest, "--base") ?? "HEAD";
13460
+ const maxLinesRaw = parseFlagValue2(rest, "--max-lines");
13461
+ const maxDirsRaw = parseFlagValue2(rest, "--max-dirs");
13462
+ const maxDocRaw = parseFlagValue2(rest, "--max-doc-lines");
12884
13463
  const report = buildReviewBrief(target, {
12885
13464
  baseRef,
12886
13465
  maxLines: maxLinesRaw ? Number(maxLinesRaw) : undefined,
@@ -12896,22 +13475,22 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
12896
13475
  return rest.includes("--fail") && !report.passed ? 1 : 0;
12897
13476
  }
12898
13477
  if (cmd === "classify") {
12899
- const maxRaw = parseFlagValue(rest, "--max");
13478
+ const maxRaw = parseFlagValue2(rest, "--max");
12900
13479
  const maxCandidates = maxRaw ? Number(maxRaw) : 30;
12901
13480
  let packet = buildSystem1Packet(target, { maxCandidates });
12902
- const provider = parseProvider(parseFlagValue(rest, "--provider"));
12903
- const corroboratePath = parseFlagValue(rest, "--corroborate");
13481
+ const provider = parseProvider(parseFlagValue2(rest, "--provider"));
13482
+ const corroboratePath = parseFlagValue2(rest, "--corroborate");
12904
13483
  if (provider) {
12905
13484
  const answers = await runSystem1Provider(packet.requests, {
12906
13485
  provider,
12907
- endpoint: parseFlagValue(rest, "--endpoint"),
12908
- model: parseFlagValue(rest, "--model"),
12909
- image: parseFlagValue(rest, "--image"),
12910
- command: parseFlagValue(rest, "--command")
13486
+ endpoint: parseFlagValue2(rest, "--endpoint"),
13487
+ model: parseFlagValue2(rest, "--model"),
13488
+ image: parseFlagValue2(rest, "--image"),
13489
+ command: parseFlagValue2(rest, "--command")
12911
13490
  });
12912
13491
  packet = { ...corroborateSystem1Batch(packet, answers), provider };
12913
13492
  } else if (corroboratePath) {
12914
- const answers = JSON.parse(fs15.readFileSync(corroboratePath, "utf8"));
13493
+ const answers = JSON.parse(fs16.readFileSync(corroboratePath, "utf8"));
12915
13494
  packet = corroborateSystem1Batch(packet, answers);
12916
13495
  }
12917
13496
  if (rest.includes("--emit-requests")) {
@@ -12942,17 +13521,17 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
12942
13521
  const circuitId = parseCircuitId(rest[1]);
12943
13522
  const circuitArgs = rest.slice(2);
12944
13523
  const circuitTarget = firstPositional(circuitArgs);
12945
- const provider = parseProvider(parseFlagValue(circuitArgs, "--provider")) ?? "fixture";
13524
+ const provider = parseProvider(parseFlagValue2(circuitArgs, "--provider")) ?? "fixture";
12946
13525
  const engine = createSystem1Engine({
12947
13526
  provider,
12948
- endpoint: parseFlagValue(circuitArgs, "--endpoint"),
12949
- model: parseFlagValue(circuitArgs, "--model"),
12950
- image: parseFlagValue(circuitArgs, "--image"),
12951
- command: parseFlagValue(circuitArgs, "--command")
13527
+ endpoint: parseFlagValue2(circuitArgs, "--endpoint"),
13528
+ model: parseFlagValue2(circuitArgs, "--model"),
13529
+ image: parseFlagValue2(circuitArgs, "--image"),
13530
+ command: parseFlagValue2(circuitArgs, "--command")
12952
13531
  });
12953
- const maxRaw = parseFlagValue(circuitArgs, "--max");
13532
+ const maxRaw = parseFlagValue2(circuitArgs, "--max");
12954
13533
  const report = await runRepoCircuit(circuitId, circuitTarget, engine, {
12955
- baseRef: parseFlagValue(circuitArgs, "--base"),
13534
+ baseRef: parseFlagValue2(circuitArgs, "--base"),
12956
13535
  maxCandidates: maxRaw ? Number(maxRaw) : undefined
12957
13536
  });
12958
13537
  if (asJson)
@@ -12967,8 +13546,8 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
12967
13546
  return 2;
12968
13547
  }
12969
13548
  if (cmd === "red-before-fix") {
12970
- const baseRef = parseFlagValue(rest, "--base") ?? "HEAD";
12971
- const testCmd = parseFlagValue(rest, "--test-cmd");
13549
+ const baseRef = parseFlagValue2(rest, "--base") ?? "HEAD";
13550
+ const testCmd = parseFlagValue2(rest, "--test-cmd");
12972
13551
  if (!testCmd) {
12973
13552
  throw new Error("vstack red-before-fix requires --test-cmd <command>.");
12974
13553
  }
@@ -13002,7 +13581,7 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
13002
13581
  const metricsPath = rest.find((a) => !a.startsWith("-"));
13003
13582
  if (!metricsPath)
13004
13583
  throw new Error("vstack spc requires a JSON metrics file ({ metric, upperSpecLimit, values }).");
13005
- const parsed = JSON.parse(fs15.readFileSync(metricsPath, "utf8"));
13584
+ const parsed = JSON.parse(fs16.readFileSync(metricsPath, "utf8"));
13006
13585
  const result = evaluateSpcSeries(parsed.metric, parsed.values, parsed.upperSpecLimit);
13007
13586
  if (asJson)
13008
13587
  console.log(JSON.stringify(result, null, 2));
@@ -13018,9 +13597,9 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
13018
13597
  if (!samplesPath) {
13019
13598
  throw new Error("vstack big-o requires a JSON samples file ({ samples: [{ n, timeMs, memoryBytes? }], maxTimeExponent? }).");
13020
13599
  }
13021
- const parsed = JSON.parse(fs15.readFileSync(samplesPath, "utf8"));
13022
- const maxTimeRaw = parseFlagValue(rest, "--max-time-exp");
13023
- const maxSpaceRaw = parseFlagValue(rest, "--max-space-exp");
13600
+ const parsed = JSON.parse(fs16.readFileSync(samplesPath, "utf8"));
13601
+ const maxTimeRaw = parseFlagValue2(rest, "--max-time-exp");
13602
+ const maxSpaceRaw = parseFlagValue2(rest, "--max-space-exp");
13024
13603
  const result = fitEmpiricalBigO(parsed.samples, {
13025
13604
  maxTimeExponent: maxTimeRaw ? Number(maxTimeRaw) : parsed.maxTimeExponent ?? 1.45,
13026
13605
  maxSpaceExponent: maxSpaceRaw ? Number(maxSpaceRaw) : parsed.maxSpaceExponent
@@ -13040,18 +13619,18 @@ RATCHET (${ratchetPath}): ${ratchetEval.passed ? "PASS" : "FAIL"}`);
13040
13619
  if (!tracesPath || tracesPath === ".") {
13041
13620
  throw new Error("vstack invariants requires a JSON traces file ({ samples: [{ fn, args?, result?, throws? }] }).");
13042
13621
  }
13043
- const parsed = JSON.parse(fs15.readFileSync(tracesPath, "utf8"));
13622
+ const parsed = JSON.parse(fs16.readFileSync(tracesPath, "utf8"));
13044
13623
  const samples = Array.isArray(parsed) ? parsed : parsed.samples ?? [];
13045
13624
  const current = inferDynamicInvariants(samples);
13046
- const baselinePath = parseFlagValue(rest, "--baseline");
13625
+ const baselinePath = parseFlagValue2(rest, "--baseline");
13047
13626
  const update = rest.includes("--update");
13048
13627
  let diff;
13049
13628
  if (baselinePath) {
13050
- if (update || !fs15.existsSync(baselinePath)) {
13629
+ if (update || !fs16.existsSync(baselinePath)) {
13051
13630
  writeInvariantSnapshot(baselinePath, current);
13052
13631
  diff = compareInvariantSnapshots(current, current, baselinePath);
13053
13632
  } else {
13054
- const baseline = JSON.parse(fs15.readFileSync(baselinePath, "utf8"));
13633
+ const baseline = JSON.parse(fs16.readFileSync(baselinePath, "utf8"));
13055
13634
  diff = compareInvariantSnapshots(baseline, current, baselinePath);
13056
13635
  }
13057
13636
  }