checkchange 0.5.7 → 0.5.9

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.
@@ -59,6 +59,7 @@ Correct use of `checkchange check`: prevents hallucination, enforces WARN blocks
59
59
  - CRAP: = CC + uncovered lines; 0% coverage → high CRAP.
60
60
  - Cache: `--cache` opt-in (default off). Also `CHECKCHANGE_CACHE=1` env.
61
61
  - Format: `--format github|junit|sarif` (sidecar, separate from --json). Valid only on `check`. SARIF sidecar emits canonical `$schema` key (`https://json.schemastore.org/sarif-2.1.0.json`) since 0.5.1 — strict SARIF validators accept it.
62
+ - Sidecar NOT_EVALUATED (since 0.5.8): functions the gate cannot evaluate (no coverage) are reported honestly — github annotation title `CRAP not evaluated`, message `CRAP n/a (coverage unavailable, cc N)` (no more `CRAP null > 30`); SARIF emits a `level:'note'` result per such function (WARN results unchanged; notes excluded from the gate); JUnit `<skipped message="...">` carries the reason. Gate verdict, exit codes, and `--json` evidence unchanged.
62
63
  - Value flags: inline (`--base=HEAD`) and next-token (`--base HEAD`) both honored; bare or empty-inline (`--base`, `--base=`) errors `<flag> requires a value`; `--crap-threshold abc` errors instead of producing NaN.
63
64
  - Bun projects: `bun test --coverage --coverage-reporter=lcov` then `checkchange check --coverage-file coverage/lcov.info --json`. lcov provider reads `DA:` line-hit records, ignores `FN:` (bun emits none).
64
65
  - Gate self-disable trap: a diff containing unsupported-extension files (e.g. package-lock.json, reformatted package.json) can make checkchange evaluate 0 functions → gate NOT_EVALUATED with gateReason no-supported-file-extensions. Keep such files out of the diff.
@@ -121,5 +122,6 @@ if ! checkchange check --base $BASE_REF; then exit 1; fi
121
122
  | absent artifact | Run tests with coverage. |
122
123
  | failed artifact | Fix tests/coverage (malformed JSON, truncation, etc.). |
123
124
  | NOT_EVALUATED in tests/** | Ignore. |
125
+ | Gate PASS + completeness INCOMPLETE | Not a clean verdict. State evaluated/NOT_EVALUATED counts next to the gate word; escalate to owner for disposition (add tests / accept untested / exempt via expectedNotEvaluated). Never hard-block. |
124
126
 
125
127
  (End of file)
package/README.md CHANGED
@@ -438,6 +438,14 @@ Exit codes:
438
438
  | `gate === 'WARN'` | 1 |
439
439
  | `PASS` / `NOT_EVALUATED` | 0 |
440
440
 
441
+ Without `--json`, the summary line always carries the verdict and its
442
+ denominator: `Analysis complete. Base: <base>, Changed functions: <n>,
443
+ Gate: <gate>, Completeness: <COMPLETE|INCOMPLETE>`, plus `Evaluated:
444
+ <evaluated>/<total>` whenever rule results exist (`evaluated` counts the
445
+ PASS/WARN results). A `PASS` can therefore never be presented without the
446
+ count of functions the gate could not evaluate; an empty diff prints no
447
+ `Evaluated:` segment.
448
+
441
449
  ---
442
450
 
443
451
  # Diagnostics output
@@ -1,3 +1,10 @@
1
+ import type { ResolvedProvider } from './providers/index.js';
2
+ /**
3
+ * Hint for a coverage-less run. Runner names come from the provider registry's
4
+ * `testRunners` for languages with source files in the repo; no tool/language
5
+ * literal is duplicated here. ponytail: one registry, used by detection + hint.
6
+ */
7
+ export declare function noRunnerHint(cwd: string, registry: Map<string, ResolvedProvider>): string;
1
8
  /**
2
9
  * Detect runner, spawn ONE coverage run (120s timeout), return expected artifact path or null.
3
10
  * On timeout/failure: returns null (caller falls back to absent path — never forced FAILED).
@@ -1,82 +1,39 @@
1
1
  import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
3
  import { spawnSync } from 'node:child_process';
4
- import { loadProviderConfig, deriveRegistry, resolveRunner, builtinConfig } from './providers/index.js';
4
+ import { loadProviderConfig, deriveRegistry, resolveRunner, resolveRunnerFromPackageDeps, builtinConfig, languagesWithSourceFiles } from './providers/index.js';
5
5
  const COV_TIMEOUT = 120_000;
6
6
  /**
7
- * Detect which test runner is available and return its coverage command + expected artifact path.
8
- * Precedence: vitest > jest > pytest.
9
- * ponytail: config glob + package.json dep check is enough; no runner introspection needed.
7
+ * Hint for a coverage-less run. Runner names come from the provider registry's
8
+ * `testRunners` for languages with source files in the repo; no tool/language
9
+ * literal is duplicated here. ponytail: one registry, used by detection + hint.
10
10
  */
11
- function detectRunner(cwd) {
12
- // Vitest: config files exist or vitest in devDependencies
13
- if (hasVitest(cwd)) {
14
- return { command: 'npx', args: ['vitest', 'run', '--coverage'], artifact: path.join(cwd, 'coverage', 'coverage-final.json') };
15
- }
16
- // Jest: config files exist or jest in devDependencies
17
- if (hasJest(cwd)) {
18
- return { command: 'npx', args: ['jest', '--coverage'], artifact: path.join(cwd, 'coverage', 'coverage-final.json') };
19
- }
20
- // pytest: pyproject.toml/pytest.ini + .py files
21
- if (hasPytest(cwd)) {
22
- return { command: 'python3', args: ['-m', 'pytest', '--cov', '--cov-report=xml'], artifact: path.join(cwd, 'coverage.xml') };
23
- }
24
- return null;
25
- }
26
- function hasVitest(cwd) {
27
- const configGlob = fs.readdirSync(cwd).some(f => f.startsWith('vitest.config'));
28
- if (configGlob)
29
- return true;
30
- try {
31
- const pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
32
- return !!(pkg.devDependencies?.vitest || pkg.dependencies?.vitest);
33
- }
34
- catch {
35
- return false;
36
- }
37
- }
38
- function hasJest(cwd) {
39
- const configGlob = fs.readdirSync(cwd).some(f => f.startsWith('jest.config'));
40
- if (configGlob)
41
- return true;
42
- try {
43
- const pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
44
- return !!(pkg.devDependencies?.jest || pkg.dependencies?.jest);
45
- }
46
- catch {
47
- return false;
48
- }
49
- }
50
- function hasPytest(cwd) {
51
- const configFiles = ['pyproject.toml', 'pytest.ini', 'setup.cfg'];
52
- const hasConfig = configFiles.some(f => fs.existsSync(path.join(cwd, f)));
53
- if (!hasConfig)
54
- return false;
55
- return fs.readdirSync(cwd, { recursive: true }).some(f => typeof f === 'string' && f.endsWith('.py'));
11
+ export function noRunnerHint(cwd, registry) {
12
+ const languages = languagesWithSourceFiles(cwd, registry);
13
+ const names = [...new Set([...registry.values()]
14
+ .filter((provider) => languages.includes(provider.language))
15
+ .flatMap((provider) => provider.testRunners?.map((runner) => runner.name) ?? []))];
16
+ // Existing hint shape (src/auto-coverage.ts:75): "No test runner detected. … to use --auto-coverage."
17
+ return names.length > 0
18
+ ? `No test runner detected. Install ${names.join(', ')} to use --auto-coverage.`
19
+ : 'No test runner detected. Run tests with coverage, or re-run with --auto-coverage.';
56
20
  }
57
21
  /**
58
22
  * Detect runner, spawn ONE coverage run (120s timeout), return expected artifact path or null.
59
23
  * On timeout/failure: returns null (caller falls back to absent path — never forced FAILED).
60
24
  */
61
25
  export function autoCoverage(cwd) {
62
- let runner = detectRunner(cwd);
63
26
  const cfg = loadProviderConfig(cwd, undefined);
64
27
  const registry = deriveRegistry(cfg.config, cfg.source);
65
- const resolved = resolveRunner(cwd, registry);
66
- if (resolved.size > 0) {
67
- const first = resolved.values().next().value;
68
- const [cmd, ...args] = first.command;
69
- runner = { command: cmd, args, artifact: path.join(cwd, first.artifact) };
70
- }
71
- if (!runner) {
72
- // Only the string was wrong (GAP 7). `detectRunner` is NOT dead: it is the
73
- // live fallback reached whenever the config-driven registry yields no runner
74
- // (:59). The hint now names dotnet, which IS a real configured runner
75
- // (DOTNET_RUNNER, src/providers/config.ts:90) — it was missing, and C# repos
76
- // were told to install a JS/Python toolchain they do not use. It also does not
77
- // promise Roslyn complexity analysis: --auto-coverage drives COVERAGE only.
78
- return { generatedPath: null, hint: 'No test runner detected. Install vitest, jest, or pytest, or add a .NET project (.csproj/.sln) so `dotnet test --collect:XPlat Code Coverage` is used, or install Bun (`bun` on PATH or a `bunfig.toml`), to use --auto-coverage.' };
79
- }
28
+ let resolved = resolveRunner(cwd, registry);
29
+ if (resolved.size === 0)
30
+ resolved = resolveRunnerFromPackageDeps(cwd, registry);
31
+ if (resolved.size === 0) {
32
+ return { generatedPath: null, hint: noRunnerHint(cwd, registry) };
33
+ }
34
+ const first = resolved.values().next().value;
35
+ const [cmd, ...args] = first.command;
36
+ const runner = { command: cmd, args, artifact: path.join(cwd, first.artifact) };
80
37
  const fullCommand = [runner.command, ...runner.args];
81
38
  const isBuiltinRunner = builtinConfig().providers.some(({ testRunners }) => testRunners?.some(({ command }) => command.length === fullCommand.length && command.every((arg, index) => arg === fullCommand[index])));
82
39
  if (!isBuiltinRunner) {
package/dist/cli.js CHANGED
@@ -237,6 +237,18 @@ export async function detectBase(base, verbose) {
237
237
  }
238
238
  return base;
239
239
  }
240
+ /**
241
+ * P7: additive text-path summary counts. Empty ruleResults emit no 0/0.
242
+ */
243
+ function summaryCounts(output) {
244
+ const ruleResults = output.ruleResults ?? [];
245
+ let suffix = `, Completeness: ${output.completeness}`;
246
+ if (ruleResults.length > 0) {
247
+ const evaluated = ruleResults.filter((r) => r.result === 'PASS' || r.result === 'WARN').length;
248
+ suffix += `, Evaluated: ${evaluated}/${ruleResults.length}`;
249
+ }
250
+ return suffix;
251
+ }
240
252
  /**
241
253
  * Emit check output: verbose diagnostics, formatter, JSON/summary, and
242
254
  * FAILED status handling + exit code. Preserves byte-identical output
@@ -267,7 +279,7 @@ export function formatOutput(output, opts, resolvedBase, cacheEnabled) {
267
279
  }
268
280
  else {
269
281
  // For WP1, we primarily want JSON, but let's output a simple summary if not JSON
270
- console.log(`Analysis complete. Base: ${resolvedBase}, Changed functions: ${output.changedFunctions.length}, Gate: ${output.gate}`);
282
+ console.log(`Analysis complete. Base: ${resolvedBase}, Changed functions: ${output.changedFunctions.length}, Gate: ${output.gate}${summaryCounts(output)}`);
271
283
  // H2: a FALLBACK complexity stage is otherwise invisible in the text path —
272
284
  // the run reports PASS/NOT_EVALUATED over approximate measurements. Warn on
273
285
  // stderr (stdout stays the machine-readable summary); nothing is printed when
@@ -174,10 +174,10 @@ export function vehicleRejection() {
174
174
  return lastVehicleRejection;
175
175
  }
176
176
  // The fallback parser is checkchange's OWN code (./csharpFallbackParser.ts), so
177
- // its tool is checkchange and its version is the package version — same 0.5.7
177
+ // its tool is checkchange and its version is the package version — same 0.5.9
178
178
  // the other self-provenance consts hard-code (src/crapCalc.ts:3, src/rules.ts:4).
179
179
  const FALLBACK_TOOL = 'checkchange';
180
- const FALLBACK_TOOL_VERSION = '0.5.7';
180
+ const FALLBACK_TOOL_VERSION = '0.5.9';
181
181
  // The vehicle's INSTALLED version is never probed: the rich path is
182
182
  // documented-unreachable (see SPAWN FORM above), so `dotnet-crap --version` is
183
183
  // never spawned to learn it, and no version is fabricated here. `unknown` is the
@@ -1,5 +1,5 @@
1
1
  export declare const crapCalcProvenance: {
2
2
  readonly tool: "checkchange";
3
- readonly version: "0.5.7";
3
+ readonly version: "0.5.9";
4
4
  };
5
5
  export declare function calculateCrap(cc: number, coveragePercent: number | null): number | null;
package/dist/crapCalc.js CHANGED
@@ -1,6 +1,5 @@
1
- // Provenance for the crapCalc lineage stage. Self tool version tracks package.json
2
- // (matches existing hard-coded '0.5.7' style for the core package).
3
- export const crapCalcProvenance = { tool: 'checkchange', version: '0.5.7' };
1
+ // Provenance for the crapCalc lineage stage. Self tool version tracks package.json.
2
+ export const crapCalcProvenance = { tool: 'checkchange', version: '0.5.9' };
4
3
  export function calculateCrap(cc, coveragePercent) {
5
4
  if (coveragePercent == null) {
6
5
  return null;
@@ -32,7 +32,7 @@ export interface DiagnosticLineageEntry {
32
32
  }
33
33
  export declare const evidenceProvenance: {
34
34
  readonly tool: "checkchange";
35
- readonly version: "0.5.7";
35
+ readonly version: "0.5.9";
36
36
  };
37
37
  export interface EvidenceOutput {
38
38
  schemaVersion: string;
@@ -55,6 +55,10 @@ export interface EvidenceOutput {
55
55
  completeness: string;
56
56
  coverageErrorReason?: string;
57
57
  gateReason?: string;
58
+ /** Additive 0.5 hint: absent coverage + changed functions. Omitted otherwise. */
59
+ coverageHint?: string;
60
+ /** Additive ratio: rule results evaluated (PASS+WARN) / total changed functions. Absent when none. */
61
+ evaluatedRatio?: number;
58
62
  diagnostics?: {
59
63
  lineage: DiagnosticLineageEntry[];
60
64
  quality: DiagnosticQuality;
@@ -145,6 +149,8 @@ export interface ChangedFunction {
145
149
  source: Source;
146
150
  language?: string;
147
151
  framework?: string;
152
+ /** True when this function's NOT_EVALUATED result is expected per exemption config. */
153
+ expectedNotEvaluated?: boolean;
148
154
  }
149
155
  export declare function detectExtension(intervals: Map<string, {
150
156
  start: number;
@@ -165,21 +171,7 @@ export declare function mapToMethodEvidence(attributedComplexity: AttributedComp
165
171
  export declare function correlate(methodEvidence: MethodEvidenceWithSource[], intervals: Map<string, {
166
172
  start: number;
167
173
  end: number;
168
- }[]>): {
169
- file: string;
170
- method: string;
171
- lineStart: number;
172
- lineEnd: number;
173
- cc: number;
174
- crap: number | null;
175
- coverage: number | null;
176
- coverageKind: string;
177
- analyzerStatus: "skipped" | "failed" | "passed";
178
- source: {
179
- tool: string;
180
- version: string;
181
- };
182
- }[];
174
+ }[]>): ChangedFunction[];
183
175
  /**
184
176
  * Legacy buildOutput for WP3 tests (schema 0.1, sync). Kept for backward compatibility.
185
177
  */
package/dist/evidence.js CHANGED
@@ -19,9 +19,10 @@ import * as fs from 'fs';
19
19
  import * as path from 'path';
20
20
  import { loadProviderConfig, deriveRegistry, builtinConfig, createGenericCommandProvider } from './providers/index.js';
21
21
  import { filterDiffedFiles } from './generated-filter.js';
22
+ import { noRunnerHint } from './auto-coverage.js';
22
23
  const requireFromEvidence = createRequire(import.meta.url);
23
- // Self provenance; version mirrors package.json (existing codebase style hard-codes '0.5.7').
24
- export const evidenceProvenance = { tool: 'checkchange', version: '0.5.7' };
24
+ // Self provenance; version mirrors package.json.
25
+ export const evidenceProvenance = { tool: 'checkchange', version: '0.5.9' };
25
26
  function sha256Hex(content) {
26
27
  return createHash('sha256').update(content).digest('hex');
27
28
  }
@@ -715,6 +716,83 @@ async function attachCoverageWithTracking(complexityInfo, coverageResult, trace,
715
716
  };
716
717
  }
717
718
  }
719
+ /**
720
+ * P6: mark functions whose NOT_EVALUATED result is expected per exemption config.
721
+ * ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity;
722
+ * `crap === null` is the sole NOT_EVALUATED predicate (rules.ts:30-33).
723
+ */
724
+ function markExpectedNotEvaluated(changedFunctions, patterns) {
725
+ // Same one-backslash normalizer as generated-filter.ts:55-57 and evidence.ts:248.
726
+ const normalized = (p) => p.split('\\').join('/');
727
+ for (const cf of changedFunctions) {
728
+ if (cf.crap !== null)
729
+ continue;
730
+ const file = normalized(cf.file);
731
+ if (patterns.some((p) => file.includes(normalized(p)))) {
732
+ cf.expectedNotEvaluated = true;
733
+ }
734
+ }
735
+ }
736
+ /**
737
+ * P4: evaluated (PASS+WARN) / total rule results; undefined for no results.
738
+ * ponytail: additive signal only — never feeds gate/completeness/exit code.
739
+ */
740
+ function evaluatedRatio(ruleResults) {
741
+ if (ruleResults.length === 0)
742
+ return undefined;
743
+ const evaluated = ruleResults.filter((r) => r.result === 'PASS' || r.result === 'WARN').length;
744
+ return evaluated / ruleResults.length;
745
+ }
746
+ /**
747
+ * Applies generated-file filtering (and its empty-diff early return) before
748
+ * complexity collection.
749
+ * ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity.
750
+ */
751
+ async function filterChangedIntervals(intervals, base, threshold, detectedExtension, cwd, coverageFile, trace, autoGenerated, gitCapability, lineage) {
752
+ if (_providerRegistry === null) {
753
+ initProviderConfig();
754
+ }
755
+ const { filtered, excluded } = filterDiffedFiles(intervals, {
756
+ generatedIgnorePatterns: _providerConfig?.generatedIgnorePatterns,
757
+ });
758
+ if (intervals.size > 0 && filtered.size === 0) {
759
+ // Fix unit 8 (M1): a test-only exclusion is reported honestly as
760
+ // 'test-files-excluded', never as the generated-bucket 'all-files-generated'.
761
+ const gateReason = excluded.length > 0 && excluded.every((entry) => entry.reason === 'test file')
762
+ ? 'test-files-excluded'
763
+ : 'all-files-generated';
764
+ return { filtered, excluded, earlyReturn: await emptyIntervalsReturn(base, threshold, detectedExtension, cwd, coverageFile, trace, autoGenerated, gitCapability, lineage, gateReason, excluded) };
765
+ }
766
+ return { filtered, excluded, earlyReturn: null };
767
+ }
768
+ /**
769
+ * Maps attributed complexity to changed functions, evaluates rules, computes the gate.
770
+ * ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity;
771
+ * lineage pushes and trace spans stay in their original order.
772
+ */
773
+ function evaluateChangedFunctions(attributedComplexity, intervals, threshold, coverageCapability, trace, lineage) {
774
+ const t0CrapCalc = Date.now();
775
+ const methodEvidence = mapToMethodEvidence(attributedComplexity);
776
+ lineage.push({ stage: 'crapCalc', ...crapCalcProvenance, inputs: { functions: methodEvidence.length } });
777
+ if (trace)
778
+ trace.recordStage('crapCalc', Date.now() - t0CrapCalc, 'ok');
779
+ // Step 6: Correlate with git intervals
780
+ const changedFunctions = correlate(methodEvidence, intervals);
781
+ // P6: mark NOT_EVALUATED functions whose file matches an exemption pattern.
782
+ markExpectedNotEvaluated(changedFunctions, _providerConfig?.expectedNotEvaluated ?? []);
783
+ // Step 7: Evaluate rule results (using the existing evaluateHighCrap from rules.js)
784
+ const t0Rules = Date.now();
785
+ const ruleResults = evaluateHighCrap(changedFunctions, threshold);
786
+ lineage.push({ stage: 'rules', ...rulesProvenance, inputs: { threshold, functions: changedFunctions.length } });
787
+ if (trace)
788
+ trace.recordStage('rules', Date.now() - t0Rules, 'ok');
789
+ // Step 8: Compute overall gate and completeness
790
+ let { gate: gateValue, completeness: completenessValue } = computeGateAndCompleteness(ruleResults);
791
+ // §5 vacuous-PASS ban: coverage absent + needs coverage → NOT_EVALUATED gate.
792
+ const coverageAbsentFlip = coverageCapability === 'absent' && changedFunctions.length > 0;
793
+ gateValue = applyAbsentCoverageGate(gateValue, coverageCapability, changedFunctions.length);
794
+ return { methodEvidence, changedFunctions, ruleResults, gateValue, completenessValue, coverageAbsentFlip };
795
+ }
718
796
  /**
719
797
  * Builds the final JSON output using composed evidence.
720
798
  * @param base The base reference used for comparison
@@ -742,24 +820,9 @@ export async function buildEvidenceOutput(base, intervals, cwd, threshold = 30,
742
820
  });
743
821
  // Step 1: Collect complexity
744
822
  const detectedExtension = detectExtension(intervals);
745
- // Seam A (plan task 3): exclude generated/minified/bundled files BEFORE any
746
- // complexity collection; exclusions surface via diagnostics.excludedGeneratedFiles.
747
- // Config first (plan task 4): the loaded config's generatedIgnorePatterns force
748
- // re-includes, so the same config that selects providers must drive the filter.
749
- if (_providerRegistry === null) {
750
- initProviderConfig();
751
- }
752
- const { filtered, excluded } = filterDiffedFiles(intervals, {
753
- generatedIgnorePatterns: _providerConfig?.generatedIgnorePatterns,
754
- });
755
- if (intervals.size > 0 && filtered.size === 0) {
756
- // Fix unit 8 (M1): a test-only exclusion is reported honestly as
757
- // 'test-files-excluded', never as the generated-bucket 'all-files-generated'.
758
- const gateReason = excluded.length > 0 && excluded.every((entry) => entry.reason === 'test file')
759
- ? 'test-files-excluded'
760
- : 'all-files-generated';
761
- return emptyIntervalsReturn(base, threshold, detectedExtension, cwd, coverageFile, trace, autoGenerated, gitCapability, lineage, gateReason, excluded);
762
- }
823
+ const { filtered, excluded, earlyReturn: filteredEarlyReturn } = await filterChangedIntervals(intervals, base, threshold, detectedExtension, cwd, coverageFile, trace, autoGenerated, gitCapability, lineage);
824
+ if (filteredEarlyReturn)
825
+ return filteredEarlyReturn;
763
826
  const changedFiles = new Set(filtered.keys());
764
827
  const t0Complexity = Date.now();
765
828
  let complexityInfo;
@@ -787,11 +850,15 @@ export async function buildEvidenceOutput(base, intervals, cwd, threshold = 30,
787
850
  // lineage `inputs` key-set AND order are unchanged — native TypeScript sets no
788
851
  // degradation, so `degradationCodes` is `[]` there.
789
852
  const degradationCodes = measurementDegradations(complexityInfo);
853
+ // Report the extension of a measured (or first changed) file, never the
854
+ // detectExtension() fallback .ts when the real source is another language.
855
+ const lineageFile = complexityInfo[0]?.file ?? [...changedFiles][0];
856
+ const lineageExtension = lineageFile ? path.extname(lineageFile) || detectedExtension : detectedExtension;
790
857
  lineage.push({
791
858
  stage: 'complexity',
792
859
  ...measurementProvenance(complexityInfo[0]),
793
860
  inputs: {
794
- extension: detectedExtension,
861
+ extension: lineageExtension,
795
862
  functions: complexityInfo.length,
796
863
  // Canonical vocabulary (ADR-0001): native analyzer => NATIVE, an
797
864
  // approximation of one => FALLBACK, provider threw => UNAVAILABLE.
@@ -887,25 +954,10 @@ export async function buildEvidenceOutput(base, intervals, cwd, threshold = 30,
887
954
  // FN/FNDA carriage (diagnostic only): match function hits to attributed
888
955
  // methods by file + lineStart; undefined when source had no FN data.
889
956
  const functionCoverageDiag = buildFunctionCoverageDiagnostics(attributedComplexity, coverageResult, cwd);
890
- // Step 4+5: Map attributed complexity → MethodEvidence (merged Steps 4+5 via mapToMethodEvidence)
891
- const t0CrapCalc = Date.now();
892
- const methodEvidence = mapToMethodEvidence(attributedComplexity);
893
- lineage.push({ stage: 'crapCalc', ...crapCalcProvenance, inputs: { functions: methodEvidence.length } });
894
- if (trace)
895
- trace.recordStage('crapCalc', Date.now() - t0CrapCalc, 'ok');
896
- // Step 6: Correlate with git intervals
897
- const changedFunctions = correlate(methodEvidence, intervals);
898
- // Step 7: Evaluate rule results (using the existing evaluateHighCrap from rules.js)
899
- const t0Rules = Date.now();
900
- const ruleResults = evaluateHighCrap(changedFunctions, threshold);
901
- lineage.push({ stage: 'rules', ...rulesProvenance, inputs: { threshold, functions: changedFunctions.length } });
902
- if (trace)
903
- trace.recordStage('rules', Date.now() - t0Rules, 'ok');
904
- // Step 8: Compute overall gate and completeness
905
- let { gate: gateValue, completeness: completenessValue } = computeGateAndCompleteness(ruleResults);
906
- // §5 vacuous-PASS ban: coverage absent + needs coverage → NOT_EVALUATED gate.
907
- const coverageAbsentFlip = coverageCapability === 'absent' && changedFunctions.length > 0;
908
- gateValue = applyAbsentCoverageGate(gateValue, coverageCapability, changedFunctions.length);
957
+ // Steps 4-8: mapping, correlation, rule evaluation and gate computation.
958
+ // ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity.
959
+ const { changedFunctions, ruleResults, gateValue, completenessValue, coverageAbsentFlip } = evaluateChangedFunctions(attributedComplexity, intervals, threshold, coverageCapability, trace, lineage);
960
+ const ratio = evaluatedRatio(ruleResults);
909
961
  // Step 9: Determine analysisStatus
910
962
  // If we have no relevant TS functions after successful analysis -> SUCCESS
911
963
  // We'll check if we have any complexityInfo (from the provider) and if we have any changedFunctions?
@@ -957,7 +1009,13 @@ export async function buildEvidenceOutput(base, intervals, cwd, threshold = 30,
957
1009
  analysisStatus: analysisStatus,
958
1010
  gate: gateValue,
959
1011
  completeness: completenessValue,
960
- ...(coverageAbsentFlip ? { gateReason: 'coverage-absent' } : {})
1012
+ ...(ratio !== undefined ? { evaluatedRatio: ratio } : {}),
1013
+ ...(coverageAbsentFlip
1014
+ ? {
1015
+ gateReason: 'coverage-absent',
1016
+ coverageHint: noRunnerHint(cwd, _providerRegistry ?? deriveRegistry(_providerConfig ?? builtinConfig(), 'builtin')),
1017
+ }
1018
+ : {})
961
1019
  }, lineage, buildQuality({
962
1020
  complexityCapability,
963
1021
  complexityQuality: measurementQuality(complexityInfo),
@@ -21,7 +21,9 @@ export function formatGitHub(out, opts) {
21
21
  const annotations = out.ruleResults
22
22
  .map((r, i) => ({ r, fn: out.changedFunctions[i] }))
23
23
  .filter(({ r }) => r.result === 'WARN' || r.result === 'NOT_EVALUATED')
24
- .map(({ r, fn }) => `::warning file=${r.file},line=${fn.lineStart},endLine=${fn.lineEnd},title=high CRAP:: ${r.method} CRAP ${r.crap} > ${r.threshold} (cc ${r.cc}, cov ${r.coverage})`)
24
+ .map(({ r, fn }) => r.result === 'WARN'
25
+ ? `::warning file=${r.file},line=${fn.lineStart},endLine=${fn.lineEnd},title=high CRAP:: ${r.method} CRAP ${r.crap} > ${r.threshold} (cc ${r.cc}, cov ${r.coverage})`
26
+ : `::warning file=${r.file},line=${fn.lineStart},endLine=${fn.lineEnd},title=CRAP not evaluated:: ${r.method} CRAP n/a (coverage unavailable, cc ${r.cc})`)
25
27
  .join('\n');
26
28
  return [annotations, prTable(out)].filter(Boolean).join('\n\n---\n\n');
27
29
  }
@@ -19,6 +19,7 @@ export interface ChangedFunctionShape {
19
19
  cc: number;
20
20
  crap: number | null;
21
21
  coverage: number | null;
22
+ expectedNotEvaluated?: boolean;
22
23
  }
23
24
  export interface RuleResultShape {
24
25
  ruleId: string;
@@ -37,6 +38,7 @@ export interface EvidenceOutputShape {
37
38
  analysisStatus: string;
38
39
  gate: 'PASS' | 'WARN' | 'NOT_EVALUATED' | 'FAILED';
39
40
  completeness: string;
41
+ evaluatedRatio?: number;
40
42
  schemaVersion: string;
41
43
  changedFunctions: ChangedFunctionShape[];
42
44
  ruleResults: RuleResultShape[];
@@ -11,6 +11,7 @@ function escapeXml(s) {
11
11
  export function formatJUnit(out, opts) {
12
12
  void opts;
13
13
  const warnCount = out.ruleResults.filter((r) => r.result === 'WARN').length;
14
+ const notEvaluatedCount = out.ruleResults.filter((r) => r.result === 'NOT_EVALUATED').length;
14
15
  const cases = out.ruleResults
15
16
  .map((r, i) => {
16
17
  const fn = out.changedFunctions[i];
@@ -20,13 +21,13 @@ export function formatJUnit(out, opts) {
20
21
  return ` <testcase ${attrs}>\n <failure message="${escapeXml(message)}">${escapeXml(r.method)} ${escapeXml(message)}</failure>\n </testcase>`;
21
22
  }
22
23
  if (r.result === 'NOT_EVALUATED') {
23
- return ` <testcase ${attrs}>\n <skipped/>\n </testcase>`;
24
+ return ` <testcase ${attrs}>\n <skipped message="${escapeXml(`CRAP not evaluated (coverage unavailable, cc ${r.cc})`)}"/>\n </testcase>`;
24
25
  }
25
26
  return ` <testcase ${attrs}/>`;
26
27
  })
27
28
  .join('\n');
28
29
  return (`<?xml version="1.0" encoding="UTF-8"?>\n` +
29
- `<testsuite name="checkchange" tests="${out.changedFunctions.length}" failures="${warnCount}">\n` +
30
+ `<testsuite name="checkchange" tests="${out.changedFunctions.length}" failures="${warnCount}" skipped="${notEvaluatedCount}">\n` +
30
31
  `${cases}\n` +
31
32
  `</testsuite>\n`);
32
33
  }
@@ -17,10 +17,27 @@ export function formatSARIF(out, opts) {
17
17
  ],
18
18
  message: { text: `${r.method} CRAP ${r.crap} > ${r.threshold} (cc ${r.cc}, cov ${r.coverage})` },
19
19
  }));
20
+ const notEvaluatedResults = out.ruleResults
21
+ .map((r, i) => ({ r, fn: out.changedFunctions[i] }))
22
+ .filter(({ r }) => r.result === 'NOT_EVALUATED')
23
+ .map(({ r, fn }) => ({
24
+ ruleId: 'changed-function-high-crap',
25
+ level: 'note',
26
+ locations: [
27
+ {
28
+ physicalLocation: {
29
+ artifactLocation: { uri: r.file },
30
+ region: { startLine: fn.lineStart, endLine: fn.lineEnd },
31
+ },
32
+ },
33
+ ],
34
+ message: { text: `${r.method} CRAP not evaluated (coverage unavailable, cc ${r.cc})` },
35
+ }));
20
36
  // FN/FNDA: informational note results when diagnostics carry function coverage.
21
37
  const coverageEntries = out.diagnostics?.functionCoverage ?? [];
22
38
  const results = [
23
39
  ...warnResults,
40
+ ...notEvaluatedResults,
24
41
  ...coverageEntries.map((entry) => ({
25
42
  ruleId: 'function-hit-coverage',
26
43
  level: 'note',
@@ -23,6 +23,8 @@ export interface ProviderConfig {
23
23
  providers: ProviderEntry[];
24
24
  /** Re-include patterns for the generated-file filter (default []). */
25
25
  generatedIgnorePatterns?: string[];
26
+ /** Path patterns for files whose NOT_EVALUATED result is EXPECTED (default []). */
27
+ expectedNotEvaluated?: string[];
26
28
  }
27
29
  export interface ResolvedProvider {
28
30
  language: string;
@@ -65,6 +65,7 @@ export function builtinConfig() {
65
65
  return {
66
66
  version: 1,
67
67
  generatedIgnorePatterns: [],
68
+ expectedNotEvaluated: [],
68
69
  providers: [
69
70
  {
70
71
  language: 'javascript',
@@ -172,6 +173,16 @@ function validateConfig(raw) {
172
173
  }
173
174
  generatedIgnorePatterns = raw.generatedIgnorePatterns;
174
175
  }
176
+ let expectedNotEvaluated;
177
+ if (raw.expectedNotEvaluated !== undefined) {
178
+ if (!Array.isArray(raw.expectedNotEvaluated) || raw.expectedNotEvaluated.some((p) => typeof p !== 'string')) {
179
+ throw new Error('config: expectedNotEvaluated must be an array of strings');
180
+ }
181
+ if (raw.expectedNotEvaluated.some((p) => p.trim().length === 0)) {
182
+ throw new Error('config: expectedNotEvaluated patterns must not be empty or whitespace-only');
183
+ }
184
+ expectedNotEvaluated = raw.expectedNotEvaluated;
185
+ }
175
186
  for (const [i, entry] of raw.providers.entries()) {
176
187
  if (!isRecord(entry))
177
188
  throw new Error(`config: providers[${i}] not an object`);
@@ -189,7 +200,7 @@ function validateConfig(raw) {
189
200
  }
190
201
  }
191
202
  // Defaults merged so consumers never see undefined (spec §4).
192
- return { ...raw, version, generatedIgnorePatterns: generatedIgnorePatterns ?? [] };
203
+ return { ...raw, version, generatedIgnorePatterns: generatedIgnorePatterns ?? [], expectedNotEvaluated: expectedNotEvaluated ?? [] };
193
204
  }
194
205
  const REPO_ROOT_NAMES = [
195
206
  'checkchange.providers.json',
@@ -1,7 +1,7 @@
1
1
  export type { ProviderConfig, ProviderEntry, ResolvedProvider, TestRunner } from './config.js';
2
2
  export { loadProviderConfig, deriveRegistry, builtinConfig } from './config.js';
3
3
  export { createGenericCommandProvider } from './genericCommand.js';
4
- export { resolveRunner } from './runner-detection.js';
4
+ export { resolveRunner, resolveRunnerFromPackageDeps, languagesWithSourceFiles } from './runner-detection.js';
5
5
  export type { ResolvedRunner } from './runner-detection.js';
6
6
  export type { PrepareOptions, DetectedStack, InstallActionKind, InstallAction, InstallPlan, PromptApprovalResult, PrepareReport, InstallActionResult, ExecuteResult, VerifyAnalyzer, VerifyReport, } from './prepare.js';
7
7
  export { detectStack, createInstallPlan, promptApproval, buildPreamble, executeInstallPlan, flushConfigUpdates, verifyInstall, } from './prepare.js';
@@ -1,4 +1,4 @@
1
1
  export { loadProviderConfig, deriveRegistry, builtinConfig } from './config.js';
2
2
  export { createGenericCommandProvider } from './genericCommand.js';
3
- export { resolveRunner } from './runner-detection.js';
3
+ export { resolveRunner, resolveRunnerFromPackageDeps, languagesWithSourceFiles } from './runner-detection.js';
4
4
  export { detectStack, createInstallPlan, promptApproval, buildPreamble, executeInstallPlan, flushConfigUpdates, verifyInstall, } from './prepare.js';
@@ -7,6 +7,14 @@ export interface ResolvedRunner {
7
7
  /** Human-readable evidence, e.g. 'pytest.ini + .venv/bin/pytest'. */
8
8
  provenance: string;
9
9
  }
10
+ /** Provider languages whose extensions have source files under cwd (hint evidence). */
11
+ export declare function languagesWithSourceFiles(cwd: string, registry: Map<string, ResolvedProvider>): string[];
12
+ /**
13
+ * Generic package.json-dependency fallback for the old `detectRunner` behavior,
14
+ * now driven entirely by `provider.testRunners[].name` — no language list.
15
+ * First configured runner whose name is a dependency wins, per language.
16
+ */
17
+ export declare function resolveRunnerFromPackageDeps(cwd: string, registry: Map<string, ResolvedProvider>): Map<string, ResolvedRunner>;
10
18
  /**
11
19
  * Resolve available test runners per language.
12
20
  * Returns one entry per language whose source files are present AND whose
@@ -42,6 +42,57 @@ function hasSourceFiles(cwd, extensions) {
42
42
  }
43
43
  return walk(cwd);
44
44
  }
45
+ /** Provider languages whose extensions have source files under cwd (hint evidence). */
46
+ export function languagesWithSourceFiles(cwd, registry) {
47
+ const languages = new Set();
48
+ const seen = new Set();
49
+ for (const provider of registry.values()) {
50
+ if (seen.has(provider))
51
+ continue; // dedupe extensions → one pass per provider
52
+ seen.add(provider);
53
+ if (hasSourceFiles(cwd, provider.extensions))
54
+ languages.add(provider.language);
55
+ }
56
+ return [...languages];
57
+ }
58
+ /**
59
+ * First configured runner whose name is a package.json dependency wins.
60
+ * ponytail: extracted from resolveRunnerFromPackageDeps to reduce cyclomatic complexity.
61
+ */
62
+ function runnerForProviderLanguage(cwd, provider) {
63
+ if (!provider.testRunners)
64
+ return null;
65
+ for (const runner of provider.testRunners) {
66
+ if (hasPackageDep(cwd, runner.name)) {
67
+ return {
68
+ command: runner.command,
69
+ artifact: runner.artifact,
70
+ provenance: 'package.json:' + runner.name,
71
+ };
72
+ }
73
+ }
74
+ return null;
75
+ }
76
+ /**
77
+ * Generic package.json-dependency fallback for the old `detectRunner` behavior,
78
+ * now driven entirely by `provider.testRunners[].name` — no language list.
79
+ * First configured runner whose name is a dependency wins, per language.
80
+ */
81
+ export function resolveRunnerFromPackageDeps(cwd, registry) {
82
+ const result = new Map();
83
+ const seen = new Set();
84
+ for (const provider of registry.values()) {
85
+ if (seen.has(provider))
86
+ continue;
87
+ seen.add(provider);
88
+ if (!hasSourceFiles(cwd, provider.extensions))
89
+ continue;
90
+ const runner = runnerForProviderLanguage(cwd, provider);
91
+ if (runner)
92
+ result.set(provider.language, runner);
93
+ }
94
+ return result;
95
+ }
45
96
  /** Match a configured configFile glob against root-level files in cwd. Returns matched filename. */
46
97
  function matchConfigFile(cwd, pattern) {
47
98
  let files;
package/dist/rules.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ChangedFunction } from './evidence.js';
2
2
  export declare const rulesProvenance: {
3
3
  readonly tool: "checkchange";
4
- readonly version: "0.5.7";
4
+ readonly version: "0.5.9";
5
5
  };
6
6
  export interface RuleResult {
7
7
  ruleId: string;
package/dist/rules.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Provenance for the rules lineage stage. Self tool version tracks package.json.
2
- export const rulesProvenance = { tool: 'checkchange', version: '0.5.7' };
2
+ export const rulesProvenance = { tool: 'checkchange', version: '0.5.9' };
3
3
  /**
4
4
  * Evaluate changed functions against the high-CRAP rule.
5
5
  * @param changed Array of changed functions
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "checkchange",
3
- "version": "0.5.7",
3
+ "version": "0.5.9",
4
4
  "license": "MIT",
5
5
  "packageManager": "pnpm@11.17.0",
6
6
  "type": "module",