testguard-cli 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,71 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.1.2] - 2026-09-17
11
+
12
+ From a field report on a real codebase (63 test files, 458 tests, 39 faults).
13
+
14
+ ### Fixed
15
+
16
+ - **A runner that cannot be resolved was reported as `FLAKY-DEFENDER`.** In
17
+ the scratch worktree, a symlinked `node_modules` (the sibling/auto-worktree
18
+ layout) was invisible, vitest failed to load, and the load error was
19
+ classified as flaky tests — blaming the wrong party. Symlinked
20
+ `node_modules` are now linked to their resolved target; the runner is
21
+ checked before any verdict and an unresolvable one is a precondition
22
+ failure (exit 2) with the fix in the message; defenders that fail to
23
+ *load* during a baseline are `UNVERIFIABLE` (`defenders-failed-to-load`),
24
+ never flaky.
25
+ - **Blast radius ignored path aliases.** `tsconfig`/`jsconfig` `paths` (with
26
+ `baseUrl` and relative `extends`) and `package.json#imports` are resolved,
27
+ so a module imported 83 times via `@/…` no longer ranks as if nothing
28
+ imported it. Bare package specifiers remain ignored, as documented.
29
+ - Summary said "N unproven claims" when N counted faults; it now reports
30
+ unproven faults *and* the distinct claims they belong to.
31
+ - `testguard claims` never showed which claims carry a `@claim` annotation;
32
+ it now reports the count and marks each annotated row.
33
+ - Piping output to a closed reader (`testguard claims | head`) no longer
34
+ crashes with an `EPIPE` stack trace.
35
+
36
+ ### Added
37
+
38
+ - `--claim <ID,ID>` probes only the named claims and writes
39
+ `.testguard/evidence-partial.json`, keeping the canonical evidence intact —
40
+ turns a fix-loop iteration from minutes into seconds.
41
+ - `--runner-cmd "<cmd>"` with `{files}` and `{out}` placeholders for
42
+ monorepos, custom configs and other package managers.
43
+ - `--node-modules <dir>` (or `TESTGUARD_NODE_MODULES`) to link a specific
44
+ `node_modules` into the scratch worktree.
45
+
46
+ ### Changed
47
+
48
+ - The `--in-place` precondition message says what it means: only fault
49
+ target files must be clean; test files may be dirty.
50
+ - `testguard baseline` prints the two `.gitignore` lines for the regenerated
51
+ files instead of leaving it to the README.
52
+ - With no baseline, the ranked block is not printed a second time under the
53
+ per-fault stream.
54
+ - `--quiet` is documented precisely.
55
+ - Staged Homebrew formula carries the sha256 of the published 0.1.1 tarball.
56
+
57
+ ## [0.1.1] - 2026-09-17
58
+
59
+ ### Fixed
60
+
61
+ - **0.1.0 did not run when installed.** `ajv`, which validates every document
62
+ against the spec, was declared as a devDependency, so `testguard` crashed on
63
+ startup from npm, `npx`, `pip` and Homebrew. It is now an exact-pinned
64
+ runtime dependency — the project's one dependency.
65
+ - CI and the release job now pack the tarball, install it into a scratch
66
+ project with production dependencies only, and run the CLI from there
67
+ (`npm run test:install`). The suite alone runs from the checkout and could
68
+ not see this class of defect.
69
+
70
+ ### Changed
71
+
72
+ - Homebrew formula carries the sha256 of the published tarball; description
73
+ shortened to satisfy `brew audit --strict`.
74
+
10
75
  ## [0.1.0] - 2026-09-17
11
76
 
12
77
  First release. A claim verifier, not a test generator.
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  [![PyPI](https://img.shields.io/pypi/v/testguard-cli.svg)](https://pypi.org/project/testguard-cli/)
6
6
  [![node](https://img.shields.io/node/v/testguard-cli.svg)](https://nodejs.org)
7
7
  [![license](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
8
- [![zero deps](https://img.shields.io/badge/runtime%20deps-0-brightgreen.svg)](./package.json)
8
+ [![deps](https://img.shields.io/badge/runtime%20deps-1%20pinned-brightgreen.svg)](./package.json)
9
9
 
10
10
  > Proves that a test suite actually defends the claims a project makes — by
11
11
  > injecting the faults those claims say cannot happen, and reporting every
@@ -35,6 +35,15 @@ on known-broken code. The largest gap was a compliance-critical path with
35
35
  100% coverage, where the one assertion that mattered used
36
36
  `expect.objectContaining({...})` and omitted the field carrying the data.
37
37
 
38
+ A second, independent run on a different AI-authored codebase (63 test
39
+ files, 458 tests, 24 hand-written security claims, 39 faults): **21 of 39
40
+ faults survived a fully green suite — 9 of them critical.** Super-admin
41
+ gating, membership checks, cookie flags and the whole authorization callback
42
+ could be disabled without a single test noticing. One test file had
43
+ re-implemented the authorization logic *inside the test* and asserted
44
+ against the copy: fifteen green tests, zero detection. After wrapper-level
45
+ tests were written against the survivors, 39/39 were killed.
46
+
38
47
  ## Install
39
48
 
40
49
  | How | Command |
@@ -43,7 +52,7 @@ on known-broken code. The largest gap was a compliance-critical path with
43
52
  | npm | `npm i -D testguard-cli` then `npx testguard probe` |
44
53
  | pip | `pip install testguard-cli` then `testguard probe` (needs Node ≥ 20) |
45
54
  | Homebrew | `brew tap raccioly/tap && brew install testguard` |
46
- | GitHub Action | `uses: raccioly/testguard@v0.1.0` — see [`action.yml`](./action.yml) |
55
+ | GitHub Action | `uses: raccioly/testguard@v0.1.2` — see [`action.yml`](./action.yml) |
47
56
  | pre-commit | `repo: https://github.com/raccioly/testguard`, hooks `testguard-claims`, `testguard-probe` |
48
57
 
49
58
  ## How it works
@@ -60,7 +69,7 @@ npx testguard-cli brief # tell the agent where the suite is blind, before
60
69
  deterministic source change that would make the statement false. Every
61
70
  claim and every fault records who produced it. `testguard claims`
62
71
  validates the file and reports drift against `@claim <ID>` annotations in
63
- source.
72
+ source. Test files are deliberately not scanned — a claim asserted by a test is the authorship trap the tool exists for — and annotation ids must contain a hyphen so prose is never mistaken for one.
64
73
  2. **Probe** confirms the defenders are green N times unmodified, applies
65
74
  each fault in a scratch git worktree (your tree is never touched), runs
66
75
  the defenders N times, re-runs survivors against the whole suite with
@@ -77,8 +86,18 @@ npx testguard-cli brief # tell the agent where the suite is blind, before
77
86
  | `FLAKY-DEFENDER` | the defenders are not reliably green, or disagreed across runs |
78
87
 
79
88
  Never a single score. Findings are ranked by severity, claim provenance
80
- and blast radius, and written to `.testguard/evidence.json` validated
81
- against the spec before it is written.
89
+ and blast radius (relative imports, `tsconfig` path aliases and
90
+ `package.json#imports` are resolved; bare package names are not), and
91
+ written to `.testguard/evidence.json` — validated against the spec before
92
+ it is written.
93
+
94
+ Practical loop: first pass `--no-escalate` (escalation re-runs the whole
95
+ suite N times per survivor); iterate on one claim with
96
+ `--claim <ID> --in-place` — only the files faults are applied to must be
97
+ committed, test files may be dirty; final pass with defaults. A custom
98
+ runner (`pnpm --filter`, a specific config) goes in
99
+ `--runner-cmd "<cmd> {files} … {out}"`; if the scratch worktree cannot
100
+ see your `node_modules`, pass `--node-modules <dir>`.
82
101
  3. **Baseline** freezes every non-passing fingerprint. Later probes suppress
83
102
  what was already known and exit non-zero only on what is new. Claims whose
84
103
  source and defenders are unchanged reuse their prior verdict, so a probe
@@ -123,7 +142,7 @@ through every verdict.
123
142
 
124
143
  **v0.1.** Four commands, vitest runner, hand-authored faults. The contract
125
144
  spine — six JSON Schemas shared with the other Guard tools — is under
126
- [`spec/`](spec/). Zero runtime dependencies; Node ≥ 20.
145
+ [`spec/`](spec/). One exact-pinned runtime dependency (`ajv`, for schema validation); Node ≥ 20.
127
146
 
128
147
  Not yet: test generation (the two-gate acceptance loop), other runners,
129
148
  mechanical fault producers, and calibration of fault classes against real
package/cli/testguard.mjs CHANGED
@@ -1,6 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { main } from '../src/cli.mjs';
3
3
 
4
+ // `testguard … | head` closes stdout early; that is not an error worth a stack trace.
5
+ for (const stream of [process.stdout, process.stderr]) {
6
+ stream.on('error', (err) => {
7
+ if (err.code === 'EPIPE') process.exit(0);
8
+ throw err;
9
+ });
10
+ }
11
+
4
12
  main(process.argv.slice(2)).then((code) => {
5
13
  process.exitCode = code;
6
14
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "testguard-cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Proves a test suite defends the claims a project makes: injects the faults those claims forbid and reports every one the tests fail to detect.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -28,7 +28,8 @@
28
28
  "test:spec": "vitest run spec/conformance",
29
29
  "self:probe": "node cli/testguard.mjs probe . --budget 180000",
30
30
  "release:sync": "node .github/scripts/sync-release-version.mjs",
31
- "prepublishOnly": "node cli/testguard.mjs --version && node .github/scripts/sync-release-version.mjs --check"
31
+ "prepublishOnly": "node cli/testguard.mjs --version && node .github/scripts/sync-release-version.mjs --check",
32
+ "test:install": "node .github/scripts/install-smoke.mjs"
32
33
  },
33
34
  "keywords": [
34
35
  "testing",
@@ -45,7 +46,6 @@
45
46
  "quality-gate"
46
47
  ],
47
48
  "devDependencies": {
48
- "ajv": "^8.20.0",
49
49
  "vitest": "^5.0.1"
50
50
  },
51
51
  "bin": {
@@ -62,5 +62,8 @@
62
62
  },
63
63
  "publishConfig": {
64
64
  "access": "public"
65
+ },
66
+ "dependencies": {
67
+ "ajv": "8.20.0"
65
68
  }
66
69
  }
@@ -12,7 +12,7 @@ The verdict set is closed. Only one value is a pass.
12
12
  | `killed` | Fault applied; every one of N probe runs failed with a genuine assertion failure, on a defender set that was green N/N unmodified. | no |
13
13
  | `survived` | Fault applied; every one of N probe runs passed. The claim is **unproven**. | **yes** |
14
14
  | `nocover` | No defending test exists: the declared globs resolve to nothing, or no test imports the subject. Worse than `survived` — nothing was even tried. | **yes** |
15
- | `unverifiable` | The fault could not be applied: anchor missing or ambiguous. Carries a `reason`. This is a loud, gating verdict — a claim that cannot be probed is not "skipped", it is undefended until someone re-authors the fault. | **yes** |
15
+ | `unverifiable` | The claim could not be probed: the fault's anchor is missing or ambiguous, or its defenders failed to load (`defenders-failed-to-load`). Carries a `reason`. A loud, gating verdict — a claim that cannot be probed is not "skipped", it is undefended until someone fixes the fault or the defenders. Never confused with `flaky-defender`, which requires tests that *ran*. | **yes** |
16
16
  | `timeout` | Probe run exceeded its budget. Not counted as a kill; the pessimistic reading is the safe one because flakiness biases the metric optimistically. | **yes** |
17
17
  | `fault-invalid` | The replacement does not load or compile. A bad fault, not a detection. | **yes** |
18
18
  | `flaky-defender` | Defenders were not green N/N on unmodified source (`defenders-not-green`), or the N probe runs disagreed with each other (`inconsistent-probe`). Either way no verdict about the fault can be trusted; fix the defenders first. | **yes** |
@@ -81,7 +81,7 @@ evidence; they simply do not turn CI red.
81
81
  |---|---|
82
82
  | `0` | No new gating findings at or above the severity floor. |
83
83
  | `1` | At least one new gating finding. |
84
- | `2` | Precondition failed: defenders not green, working tree dirty for a target file, runner not found, claims file invalid. Nothing was probed. |
84
+ | `2` | Precondition failed: test runner not resolvable (e.g. no `node_modules` linked into the scratch worktree), working tree dirty for a fault target file, claims file invalid, no commits. Nothing was probed. |
85
85
  | `3` | Usage or configuration error. |
86
86
 
87
87
  A tool must never exit `0` because it had nothing to check. If the claims
@@ -31,7 +31,7 @@
31
31
  "enum": ["critical", "high", "medium", "low"]
32
32
  },
33
33
  "verdict": {
34
- "description": "Closed set. Only `killed` is a pass. Every other verdict gates by default (see GATE-SEMANTICS.md).",
34
+ "description": "Closed set. Only `killed` is a pass. Every other verdict gates by default (see GATE-SEMANTICS.md). `unverifiable` covers a fault that could not be applied (anchor missing/ambiguous) and a claim whose defenders failed to load (`defenders-failed-to-load`).",
35
35
  "enum": [
36
36
  "killed",
37
37
  "survived",
package/src/cli.mjs CHANGED
@@ -28,10 +28,13 @@ probe
28
28
  --baseline <path> baseline to gate against (default: <dir>/.testguard/baseline.json if present)
29
29
  --severity <level> gate only at or above (default: low)
30
30
  --ref <commit> probe this commit in the scratch worktree (default: HEAD)
31
+ --claim <ID,ID> probe only these claims; writes .testguard/evidence-partial.json
32
+ --runner-cmd "<cmd>" custom runner; must contain {files} and {out}, e.g. "pnpm vitest run {files} --reporter=json --outputFile={out}"
33
+ --node-modules <dir> node_modules to link into the scratch worktree (or TESTGUARD_NODE_MODULES)
31
34
  --in-place mutate the working tree instead of a scratch worktree
32
35
  --no-escalate do not re-run survivors against the whole suite
33
36
  --no-reuse re-probe claims whose inputs have not changed
34
- --quiet summary only
37
+ --quiet suppress the per-fault stream and ranked block; print only the summary and evidence path
35
38
 
36
39
  claims --json
37
40
  baseline --evidence <path> --out <path>
@@ -58,6 +61,9 @@ export async function main(argv, io = { out: (s) => process.stdout.write(s + '\n
58
61
  severity: { type: 'string', default: 'low' },
59
62
  max: { type: 'string', default: '20' },
60
63
  ref: { type: 'string', default: 'HEAD' },
64
+ claim: { type: 'string' },
65
+ 'runner-cmd': { type: 'string' },
66
+ 'node-modules': { type: 'string' },
61
67
  'in-place': { type: 'boolean', default: false },
62
68
  'no-escalate': { type: 'boolean', default: false },
63
69
  'no-reuse': { type: 'boolean', default: false },
@@ -16,6 +16,8 @@ export async function baselineCommand({ projectDir, values }, io) {
16
16
  writeSpecDoc('baseline', outPath, baseline);
17
17
  const n = Object.values(baseline.fingerprints).reduce((a, b) => a + b, 0);
18
18
  io.out(`baseline: ${n} unproven finding${n === 1 ? '' : 's'} frozen at ${baseline.head.slice(0, 12)} → ${outPath}`);
19
- io.out('Commit this file. From now on only new findings gate.');
19
+ io.out('Commit this file; from now on only new findings gate. Ignore the regenerated ones — add to .gitignore:');
20
+ io.out(' .testguard/evidence.json');
21
+ io.out(' .testguard/brief.json');
20
22
  return 0;
21
23
  }
@@ -12,12 +12,13 @@ export async function claimsCommand({ projectDir, values }, io) {
12
12
  if (values.json) {
13
13
  io.out(JSON.stringify({ path, claims, annotations, drift }, null, 2));
14
14
  } else {
15
- io.out(`${claims.claims.length} claims in ${path}`);
15
+ const annotated = new Set(drift.annotated);
16
+ io.out(`${claims.claims.length} claims in ${path} — ${annotated.size} carry a @claim annotation in source (test files are not scanned)`);
16
17
  io.out('');
17
18
  for (const c of claims.claims) {
18
19
  const defenders = resolveDefenders(projectDir, c.defendedBy);
19
20
  const cover = defenders.length ? `${defenders.length} defender${defenders.length === 1 ? '' : 's'}` : 'NO DEFENDER';
20
- io.out(`${c.id.padEnd(14)} ${c.severity.padEnd(8)} ${c.source.kind.padEnd(10)} ${String(c.faults.length).padStart(2)} fault${c.faults.length === 1 ? ' ' : 's'} ${cover.padEnd(12)} ${c.statement}`);
21
+ io.out(`${annotated.has(c.id) ? '@ ' : ' '}${c.id.padEnd(14)} ${c.severity.padEnd(8)} ${c.source.kind.padEnd(10)} ${String(c.faults.length).padStart(2)} fault${c.faults.length === 1 ? ' ' : 's'} ${cover.padEnd(12)} ${c.statement}`);
21
22
  }
22
23
  if (drift.undeclared.length || drift.stale.length) io.out('');
23
24
  for (const a of drift.undeclared) io.out(`UNDECLARED @claim ${a.id} at ${a.file}:${a.line} has no entry in the claims file — a claim with no fault model`);
@@ -21,7 +21,9 @@ export async function probeCommand({ projectDir, values, version }, io) {
21
21
  io.err('claims file declares no claims; nothing to verify');
22
22
  return 2;
23
23
  }
24
- const outPath = values.out ? resolve(values.out) : evidencePath(projectDir);
24
+ const only = values.claim ? values.claim.split(',').map((s) => s.trim()).filter(Boolean) : undefined;
25
+ // A --claim run is partial evidence; keep it away from the canonical file unless --out says otherwise.
26
+ const outPath = values.out ? resolve(values.out) : only ? join(projectDir, '.testguard', 'evidence-partial.json') : evidencePath(projectDir);
25
27
  const previous = !values['no-reuse'] && existsSync(outPath) ? readSpecDoc('evidence', outPath) : undefined;
26
28
  const basePath = values.baseline ? resolve(values.baseline) : baselinePath(projectDir);
27
29
  const baseline = existsSync(basePath) ? readSpecDoc('baseline', basePath) : undefined;
@@ -34,6 +36,9 @@ export async function probeCommand({ projectDir, values, version }, io) {
34
36
  budgetMs,
35
37
  mode: values['in-place'] ? 'in-place' : 'worktree',
36
38
  ref: values.ref,
39
+ runnerCommand: values['runner-cmd'],
40
+ nodeModules: values['node-modules'] ? resolve(values['node-modules']) : process.env.TESTGUARD_NODE_MODULES,
41
+ only,
37
42
  escalate: !values['no-escalate'],
38
43
  toolVersion: version,
39
44
  onProgress: values.quiet ? undefined : (r) => io.out(renderRecord(r) + (r.reusedFrom ? ' (reused)' : '')),
@@ -41,13 +46,13 @@ export async function probeCommand({ projectDir, values, version }, io) {
41
46
  writeSpecDoc('evidence', outPath, evidence);
42
47
 
43
48
  const g = gate(evidence.records, baseline, { severityFloor: values.severity });
44
- if (!values.quiet) {
49
+ if (!values.quiet && baseline) {
45
50
  io.out('');
46
51
  const tag = (r) => (g.new.includes(r) ? '[NEW] ' : g.baselined.includes(r) ? '[baseline] ' : '[below floor] ');
47
52
  for (const r of sortForReport(evidence.records).filter((x) => x.verdict !== 'killed')) io.out(' ' + tag(r) + renderRecord(r));
48
53
  }
49
54
  io.out('');
50
55
  io.out(renderSummary(evidence.records) + (baseline ? ` ${g.new.length} new since baseline, ${g.baselined.length} baselined.` : ' No baseline.'));
51
- io.out(`evidence: ${outPath}`);
56
+ io.out(`evidence: ${outPath}${only ? ` (partial: --claim ${only.join(',')}; not the canonical evidence file)` : ''}`);
52
57
  return g.new.length > 0 ? 1 : 0;
53
58
  }
@@ -12,7 +12,7 @@ import { fingerprint } from '../../spec/lib/fingerprint.mjs';
12
12
 
13
13
  const isKill = (r) => r.outcome === 'fail' && r.assertionFailures > 0;
14
14
 
15
- function runnerVersion(projectDir) {
15
+ function readRunnerVersion(projectDir) {
16
16
  try {
17
17
  return JSON.parse(readFileSync(createRequire(join(projectDir, 'noop.js')).resolve('vitest/package.json'), 'utf8')).version;
18
18
  } catch {
@@ -31,6 +31,9 @@ export async function probe({
31
31
  mode = 'worktree',
32
32
  ref = 'HEAD',
33
33
  budgetMs = 120_000,
34
+ runnerCommand,
35
+ nodeModules,
36
+ only,
34
37
  escalate = true,
35
38
  scratchBase,
36
39
  toolVersion = '0.0.0',
@@ -45,21 +48,39 @@ export async function probe({
45
48
 
46
49
  const targets = [...new Set(claims.claims.flatMap((c) => c.faults.map((f) => relative(root, join(projectDir, f.file)))))];
47
50
  if (mode === 'in-place' && isDirty(root, targets)) {
48
- throw new PreconditionError(`uncommitted changes in target files (${targets.join(', ')}); commit or stash first, or drop --in-place`);
51
+ throw new PreconditionError(`uncommitted changes in fault target files (${targets.join(', ')}); commit or stash them, or drop --in-place. Only the files faults are applied to must be clean — test files may be dirty, which is what makes --in-place usable while writing tests.`);
52
+ }
53
+ const selected = only ? new Set(only) : null;
54
+ if (selected) {
55
+ const known = new Set(claims.claims.map((c) => c.id));
56
+ const unknown = [...selected].filter((id) => !known.has(id));
57
+ if (unknown.length) throw new PreconditionError(`--claim: unknown claim id(s) ${unknown.join(', ')}`);
49
58
  }
50
59
 
51
60
  const startedAt = new Date().toISOString();
52
- const iso = mode === 'worktree' ? createScratch({ repoRoot: root, projectDir, ref, scratchBase }) : inPlace({ repoRoot: root, projectDir });
61
+ const iso = mode === 'worktree' ? createScratch({ repoRoot: root, projectDir, ref, scratchBase, nodeModules }) : inPlace({ repoRoot: root, projectDir });
53
62
  const records = [];
63
+ let runnerVersion;
54
64
  try {
65
+ const commandTemplate = runnerCommand ? vitest.parseCommandTemplate(runnerCommand) : undefined;
66
+ if (!commandTemplate) {
67
+ // An unresolvable runner is a precondition failure, not a flaky defender.
68
+ const check = await vitest.checkRunner({ projectDir: iso.projectDir });
69
+ if (!check.ok) {
70
+ throw new PreconditionError(`test runner is not resolvable in the ${mode === 'worktree' ? 'scratch worktree' : 'project'} (${check.message}). ` +
71
+ (mode === 'worktree' ? 'No usable node_modules was linked: pass --node-modules <path>, or run with --in-place.' : 'Install dependencies first.'));
72
+ }
73
+ runnerVersion = check.version;
74
+ }
55
75
  const allTests = vitest.listTestFiles(iso.projectDir);
56
76
  const baselineCache = new Map();
57
77
  const prior = previous && previous.run.confirmRuns === confirmRuns
58
78
  ? new Map(previous.records.map((r) => [`${r.claim.id}/${r.subject.id}`, r]))
59
79
  : new Map();
60
- const runDefenders = (files) => vitest.runVitest({ projectDir: iso.projectDir, files, budgetMs });
80
+ const runDefenders = (files) => vitest.runVitest({ projectDir: iso.projectDir, files, budgetMs, commandTemplate });
61
81
 
62
82
  for (const claim of claims.claims) {
83
+ if (selected && !selected.has(claim.id)) continue;
63
84
  const defenders = vitest.resolveDefenders(iso.projectDir, claim.defendedBy);
64
85
  for (const fault of claim.faults) {
65
86
  const record = await probeOne({ claim, fault, defenders, allTests, iso, confirmRuns, escalate, baselineCache, runDefenders, prior: prior.get(`${claim.id}/${fault.id}`), priorRunId: previous?.run.id });
@@ -79,7 +100,7 @@ export async function probe({
79
100
  startedAt,
80
101
  finishedAt: new Date().toISOString(),
81
102
  repo: { head, dirty: isDirty(root) },
82
- runner: { name: vitest.name, ...(runnerVersion(projectDir) ? { version: runnerVersion(projectDir) } : {}) },
103
+ runner: { name: vitest.name, ...((runnerVersion ?? readRunnerVersion(projectDir)) ? { version: runnerVersion ?? readRunnerVersion(projectDir) } : {}) },
83
104
  confirmRuns,
84
105
  mode,
85
106
  },
@@ -111,14 +132,24 @@ async function probeOne({ claim, fault, defenders, allTests, iso, confirmRuns, e
111
132
  const key = defenders.join('\n');
112
133
  if (!baselineCache.has(key)) {
113
134
  const runs = [];
135
+ let loadMessage;
114
136
  for (let i = 0; i < confirmRuns; i++) {
115
- const { run } = await runDefenders(defenders);
116
- runs.push(run);
117
- if (run.outcome !== 'pass') break;
137
+ const res = await runDefenders(defenders);
138
+ runs.push(res.run);
139
+ if (res.run.outcome !== 'pass') {
140
+ loadMessage = res.loadMessage;
141
+ break;
142
+ }
118
143
  }
119
- baselineCache.set(key, runs);
144
+ baselineCache.set(key, { runs, loadMessage });
145
+ }
146
+ const baseline = baselineCache.get(key);
147
+ detail.baselineRuns = baseline.runs;
148
+ if (baseline.runs.some((r) => r.outcome === 'error')) {
149
+ // The defenders did not load. That is not flakiness and not a verdict
150
+ // about the fault; the claim cannot be probed until they do.
151
+ anchor = { status: 'defenders-failed-to-load', hits: anchor.hits, expected: anchor.expected, message: baseline.loadMessage };
120
152
  }
121
- detail.baselineRuns = baselineCache.get(key);
122
153
 
123
154
  if (detail.baselineRuns.every((r) => r.outcome === 'pass') && detail.baselineRuns.length === confirmRuns) {
124
155
  const mutation = applyFault(iso.projectDir, fault);
@@ -1,7 +1,78 @@
1
- import { readFileSync } from 'node:fs';
1
+ import { readFileSync, existsSync } from 'node:fs';
2
2
  import { dirname, join, resolve, extname } from 'node:path';
3
3
  import { walk } from '../util/glob.mjs';
4
4
 
5
+ const aliasCache = new Map();
6
+
7
+ /** Minimal JSONC: strip comments and trailing commas, as tsconfig allows. */
8
+ function parseJsonc(text) {
9
+ return JSON.parse(text.replace(/\/\*[\s\S]*?\*\//g, '').replace(/^\s*\/\/.*$/gm, '').replace(/,(\s*[}\]])/g, '$1'));
10
+ }
11
+
12
+ /**
13
+ * Alias rules for a project: tsconfig/jsconfig `compilerOptions.paths` (with
14
+ * `baseUrl`, following a relative `extends` a few levels) and package.json
15
+ * `imports`. Bare specifiers that match no rule are ignored, as documented.
16
+ */
17
+ export function loadAliases(projectDir) {
18
+ if (aliasCache.has(projectDir)) return aliasCache.get(projectDir);
19
+ const rules = [];
20
+ const toRule = (pattern, targets, base) => {
21
+ const [prefix, suffix = ''] = pattern.split('*');
22
+ rules.push({ prefix, suffix, wildcard: pattern.includes('*'), targets: targets.map((t) => resolve(base, t)) });
23
+ };
24
+
25
+ let cfgPath = ['tsconfig.json', 'jsconfig.json'].map((f) => join(projectDir, f)).find(existsSync);
26
+ let baseUrl;
27
+ let paths;
28
+ for (let hop = 0; cfgPath && hop < 5; hop++) {
29
+ let cfg;
30
+ try {
31
+ cfg = parseJsonc(readFileSync(cfgPath, 'utf8'));
32
+ } catch {
33
+ break;
34
+ }
35
+ const co = cfg.compilerOptions ?? {};
36
+ if (baseUrl === undefined && co.baseUrl !== undefined) baseUrl = resolve(dirname(cfgPath), co.baseUrl);
37
+ if (paths === undefined && co.paths !== undefined) paths = { dir: dirname(cfgPath), map: co.paths };
38
+ const ext = typeof cfg.extends === 'string' && cfg.extends.startsWith('.') ? cfg.extends : null;
39
+ cfgPath = ext ? resolve(dirname(cfgPath), ext.endsWith('.json') ? ext : ext + '.json') : null;
40
+ }
41
+ if (paths) {
42
+ const base = baseUrl ?? paths.dir;
43
+ for (const [pattern, targets] of Object.entries(paths.map)) if (Array.isArray(targets)) toRule(pattern, targets, base);
44
+ }
45
+
46
+ const pkgPath = join(projectDir, 'package.json');
47
+ if (existsSync(pkgPath)) {
48
+ try {
49
+ const imports = JSON.parse(readFileSync(pkgPath, 'utf8')).imports ?? {};
50
+ for (const [pattern, target] of Object.entries(imports)) {
51
+ const t = typeof target === 'string' ? target : target?.default ?? target?.import ?? target?.node;
52
+ if (typeof t === 'string' && t.startsWith('.')) toRule(pattern, [t], projectDir);
53
+ }
54
+ } catch {}
55
+ }
56
+ aliasCache.set(projectDir, rules);
57
+ return rules;
58
+ }
59
+
60
+ /** Absolute candidate bases an aliased specifier could mean, or [] if it matches no rule. */
61
+ function aliasCandidates(specifier, rules) {
62
+ const out = [];
63
+ for (const r of rules) {
64
+ if (r.wildcard) {
65
+ if (specifier.startsWith(r.prefix) && specifier.endsWith(r.suffix) && specifier.length >= r.prefix.length + r.suffix.length) {
66
+ const star = specifier.slice(r.prefix.length, specifier.length - r.suffix.length);
67
+ for (const t of r.targets) out.push(t.replace('*', star));
68
+ }
69
+ } else if (specifier === r.prefix) {
70
+ out.push(...r.targets);
71
+ }
72
+ }
73
+ return out;
74
+ }
75
+
5
76
  const SOURCE_EXT = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.jsx', '.tsx']);
6
77
  const IMPORT_RE = /(?:from\s*|import\s*\(?\s*|require\s*\(\s*)['"]([^'"]+)['"]/g;
7
78
  const TEST_RE = /\.(test|spec)\.[cm]?[jt]sx?$/;
@@ -11,18 +82,26 @@ const SEVERITY_WEIGHT = { critical: 8, high: 4, medium: 2, low: 1 };
11
82
  // independent evidence than one from a human-governed spec.
12
83
  const SOURCE_WEIGHT = { spec: 1, adr: 1, manual: 0.9, annotation: 0.75, comment: 0.75 };
13
84
 
14
- function resolvesTo(fromFile, specifier, targetAbs) {
15
- if (!specifier.startsWith('.')) return false;
16
- const base = resolve(dirname(fromFile), specifier);
85
+ function expandBase(base) {
17
86
  const candidates = [base, ...[...SOURCE_EXT].map((e) => base + e), ...[...SOURCE_EXT].map((e) => join(base, 'index' + e))];
18
87
  const stripped = base.replace(/\.(js|mjs|cjs)$/, '');
19
88
  candidates.push(stripped + '.ts', stripped + '.mts', stripped + '.tsx');
20
- return candidates.includes(targetAbs);
89
+ return candidates;
90
+ }
91
+
92
+ function resolvesTo(fromFile, specifier, targetAbs, aliases) {
93
+ const bases = specifier.startsWith('.') ? [resolve(dirname(fromFile), specifier)] : aliasCandidates(specifier, aliases);
94
+ return bases.some((b) => expandBase(b).includes(targetAbs));
21
95
  }
22
96
 
23
- /** Number of non-test source files that import `targetRel` (direct imports only, documented as such). */
97
+ /**
98
+ * Number of non-test source files that import `targetRel`: relative specifiers,
99
+ * tsconfig/jsconfig `paths` aliases and package.json `imports` are resolved;
100
+ * bare package specifiers are not. Direct imports only.
101
+ */
24
102
  export function blastRadius(projectDir, targetRel) {
25
103
  const targetAbs = resolve(projectDir, targetRel);
104
+ const aliases = loadAliases(projectDir);
26
105
  let count = 0;
27
106
  for (const rel of walk(projectDir)) {
28
107
  if (!SOURCE_EXT.has(extname(rel)) || TEST_RE.test(rel) || rel === targetRel) continue;
@@ -34,7 +113,7 @@ export function blastRadius(projectDir, targetRel) {
34
113
  continue;
35
114
  }
36
115
  for (const m of src.matchAll(IMPORT_RE)) {
37
- if (resolvesTo(abs, m[1], targetAbs)) {
116
+ if (resolvesTo(abs, m[1], targetAbs, aliases)) {
38
117
  count++;
39
118
  break;
40
119
  }
@@ -10,6 +10,63 @@ const TEST_GLOBS = ['**/*.test.js', '**/*.test.mjs', '**/*.test.cjs', '**/*.test
10
10
 
11
11
  export const name = 'vitest';
12
12
 
13
+ /**
14
+ * Split a runner command template into argv. Supports double and single
15
+ * quotes; `{files}` expands to the test files (one argv entry each) and
16
+ * `{out}` to the JSON report path. Everything else is passed through.
17
+ */
18
+ export function parseCommandTemplate(template) {
19
+ const words = [];
20
+ let cur = '';
21
+ let quote = null;
22
+ let has = false;
23
+ for (const ch of template) {
24
+ if (quote) {
25
+ if (ch === quote) quote = null;
26
+ else cur += ch;
27
+ } else if (ch === '"' || ch === "'") {
28
+ quote = ch;
29
+ has = true;
30
+ } else if (/\s/.test(ch)) {
31
+ if (has || cur) words.push(cur);
32
+ cur = '';
33
+ has = false;
34
+ } else {
35
+ cur += ch;
36
+ }
37
+ }
38
+ if (has || cur) words.push(cur);
39
+ if (quote) throw new RangeError('unterminated quote in --runner-cmd');
40
+ if (!words.includes('{files}') || !words.some((w) => w.includes('{out}'))) throw new RangeError('--runner-cmd must contain {files} (as its own word) and {out}');
41
+ return words;
42
+ }
43
+
44
+ /** `{files}` must be a word of its own (one argv entry per file); `{out}` may be embedded, e.g. `--outputFile={out}`. */
45
+ export const expandCommand = (words, files, outFile) => words.flatMap((w) => (w === '{files}' ? files : [w.replaceAll('{out}', outFile)]));
46
+
47
+ /**
48
+ * Can the runner be resolved at all from this directory? Run before any
49
+ * verdict is attempted: an unresolvable runner is a precondition failure,
50
+ * never a statement about the tests.
51
+ */
52
+ export function checkRunner({ projectDir, budgetMs = 60_000, env = process.env }) {
53
+ const npx = process.platform === 'win32' ? 'npx.cmd' : 'npx';
54
+ return new Promise((resolve) => {
55
+ const child = spawn(npx, ['--no-install', 'vitest', '--version'], { cwd: projectDir, stdio: ['ignore', 'pipe', 'pipe'], env: { ...env, CI: '1' } });
56
+ let out = '';
57
+ let err = '';
58
+ child.on('error', (e) => resolve({ ok: false, message: e.message }));
59
+ child.stdout.on('data', (d) => (out += d));
60
+ child.stderr.on('data', (d) => (err += d));
61
+ const timer = setTimeout(() => child.kill('SIGKILL'), budgetMs);
62
+ child.on('close', (code) => {
63
+ clearTimeout(timer);
64
+ const version = out.trim().replace(/^vitest\//, '');
65
+ resolve(code === 0 && version ? { ok: true, version } : { ok: false, message: (err || out).trim().split('\n').filter(Boolean).slice(-1)[0] ?? `exit ${code}` });
66
+ });
67
+ });
68
+ }
69
+
13
70
  /** Defender globs → existing files. Empty result is the `nocover` signal. */
14
71
  export const resolveDefenders = (projectDir, globs) => matchGlobs(projectDir, globs ?? []);
15
72
 
@@ -47,16 +104,18 @@ export function parseReport(report, durationMs) {
47
104
  * The budget matters because a synchronous infinite loop is immune to
48
105
  * vitest's own test timeout; only killing the process ends it.
49
106
  */
50
- export function runVitest({ projectDir, files, budgetMs = 120_000, command }) {
107
+ export function runVitest({ projectDir, files, budgetMs = 120_000, command, commandTemplate }) {
51
108
  const outFile = join(tmpdir(), `testguard-vitest-${randomBytes(6).toString('hex')}.json`);
52
109
  const npx = process.platform === 'win32' ? 'npx.cmd' : 'npx';
53
- const [cmd, ...args] = command ?? [npx, 'vitest', 'run', ...files, '--reporter=json', `--outputFile=${outFile}`];
110
+ const [cmd, ...args] = command
111
+ ?? (commandTemplate ? expandCommand(commandTemplate, files, outFile) : [npx, 'vitest', 'run', ...files, '--reporter=json', `--outputFile=${outFile}`]);
54
112
  const started = Date.now();
55
113
 
56
114
  return new Promise((resolve) => {
57
115
  const child = spawn(cmd, args, { cwd: projectDir, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, CI: '1', FORCE_COLOR: '0' } });
58
116
  let stderr = '';
59
117
  child.stderr.on('data', (d) => (stderr += d));
118
+ child.on('error', (e) => (stderr += e.message));
60
119
  let killed = false;
61
120
  const timer = setTimeout(() => {
62
121
  killed = true;
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdtempSync, readdirSync, symlinkSync, mkdirSync, rmSync } from 'node:fs';
1
+ import { existsSync, mkdtempSync, readdirSync, symlinkSync, mkdirSync, statSync, realpathSync } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join, relative, dirname } from 'node:path';
4
4
  import { addWorktree, removeWorktree, headSha } from '../git.mjs';
@@ -7,10 +7,21 @@ export class PreconditionError extends Error {}
7
7
 
8
8
  /**
9
9
  * Find every node_modules directory in the main tree (to a shallow depth) so
10
- * the scratch worktree can borrow them instead of reinstalling.
10
+ * the scratch worktree can borrow them instead of reinstalling. A symlinked
11
+ * node_modules — the layout a sibling or auto-created worktree produces — is
12
+ * a directory for this purpose, and is linked to its resolved target.
11
13
  */
12
- function findNodeModules(root, depth = 3) {
14
+ export function findNodeModules(root, depth = 3) {
13
15
  const found = [];
16
+ const isDir = (dir, e) => {
17
+ if (e.isDirectory()) return true;
18
+ if (!e.isSymbolicLink()) return false;
19
+ try {
20
+ return statSync(join(dir, e.name)).isDirectory();
21
+ } catch {
22
+ return false;
23
+ }
24
+ };
14
25
  const visit = (dir, rel, d) => {
15
26
  let entries;
16
27
  try {
@@ -19,10 +30,10 @@ function findNodeModules(root, depth = 3) {
19
30
  return;
20
31
  }
21
32
  for (const e of entries) {
22
- if (!e.isDirectory()) continue;
33
+ if (!isDir(dir, e)) continue;
23
34
  const relPath = rel ? `${rel}/${e.name}` : e.name;
24
35
  if (e.name === 'node_modules') {
25
- found.push(relPath);
36
+ found.push({ rel: relPath, target: realpathSync(join(dir, e.name)) });
26
37
  } else if (d < depth && e.name !== '.git' && !e.name.startsWith('.')) {
27
38
  visit(join(dir, e.name), relPath, d + 1);
28
39
  }
@@ -36,18 +47,24 @@ function findNodeModules(root, depth = 3) {
36
47
  * A scratch git worktree at HEAD, with the main tree's node_modules linked in.
37
48
  * Faults are applied here; the user's tree is never touched.
38
49
  */
39
- export function createScratch({ repoRoot, projectDir, ref = 'HEAD', scratchBase = tmpdir() }) {
50
+ export function createScratch({ repoRoot, projectDir, ref = 'HEAD', scratchBase = tmpdir(), nodeModules }) {
40
51
  const sha = headSha(repoRoot, ref);
41
52
  if (!sha) {
42
53
  throw new PreconditionError(ref === 'HEAD' ? 'repository has no commits; commit first, or run with --in-place' : `ref ${ref} does not resolve to a commit`);
43
54
  }
44
55
  const dest = mkdtempSync(join(scratchBase, 'testguard-'));
45
56
  addWorktree(repoRoot, dest, sha);
46
- for (const rel of findNodeModules(repoRoot)) {
47
- const target = join(dest, rel);
48
- if (existsSync(target)) continue;
49
- mkdirSync(dirname(target), { recursive: true });
50
- symlinkSync(join(repoRoot, rel), target, 'dir');
57
+ const links = findNodeModules(repoRoot);
58
+ if (nodeModules) {
59
+ // Explicit override: link it where the probed project expects it.
60
+ const rel = join(relative(repoRoot, projectDir), 'node_modules');
61
+ links.unshift({ rel, target: realpathSync(nodeModules) });
62
+ }
63
+ for (const { rel, target } of links) {
64
+ const at = join(dest, rel);
65
+ if (existsSync(at)) continue;
66
+ mkdirSync(dirname(at), { recursive: true });
67
+ symlinkSync(target, at, 'dir');
51
68
  }
52
69
  return {
53
70
  mode: 'worktree',
package/src/render.mjs CHANGED
@@ -18,8 +18,9 @@ export function summarize(records) {
18
18
  export function renderSummary(records) {
19
19
  const byVerdict = summarize(records);
20
20
  const parts = ORDER.filter((v) => byVerdict[v]).map((v) => `${byVerdict[v]} ${formatVerdict(v)}`);
21
- const gating = records.filter((r) => r.verdict !== 'killed').length;
22
- return `${records.length} faults probed: ${parts.join(', ')}. ${gating} unproven claim${gating === 1 ? '' : 's'}.`;
21
+ const unproven = records.filter((r) => r.verdict !== 'killed');
22
+ const claims = new Set(unproven.map((r) => r.claim.id)).size;
23
+ return `${records.length} faults probed: ${parts.join(', ')}. ${unproven.length} unproven fault${unproven.length === 1 ? '' : 's'} across ${claims} claim${claims === 1 ? '' : 's'}.`;
23
24
  }
24
25
 
25
26
  /** Survivors first, then by rank score; killed last. */