checkchange 0.5.8 → 0.5.10

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.
@@ -67,6 +67,7 @@ Correct use of `checkchange check`: prevents hallucination, enforces WARN blocks
67
67
  - Exit codes: FAILED→1, SUCCESS+WARN→1, UNSUPPORTED+NOT_APPLICABLE→0.
68
68
  - Malformed artifact: analysisStatus=FAILED, gate=FAILED, completeness=INCOMPLETE.
69
69
  - Trace sidecar: `{command:"trace", correlationId, spans:[{stage,durationMs,status}]}`.
70
+ - Doctor skill announcement: `checkchange doctor` (also `doctor --json`) reports the packaged `using-checkchange/SKILL.md` as `present` or `absent` with its path and reinstall remediation when absent. Announce-only: the CLI never installs or syncs skill files; copy it manually as described in the README "For AI agents (skill file)" section.
70
71
 
71
72
  # Implementation
72
73
  ```bash
@@ -122,5 +123,6 @@ if ! checkchange check --base $BASE_REF; then exit 1; fi
122
123
  | absent artifact | Run tests with coverage. |
123
124
  | failed artifact | Fix tests/coverage (malformed JSON, truncation, etc.). |
124
125
  | NOT_EVALUATED in tests/** | Ignore. |
126
+ | 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. |
125
127
 
126
128
  (End of file)
package/README.md CHANGED
@@ -117,6 +117,8 @@ npm install -g checkchange
117
117
  checkchange --help
118
118
  ```
119
119
 
120
+ The bundled agent skill: see [For AI agents (skill file)](#for-ai-agents-skill-file) below.
121
+
120
122
  Or use it without installing globally:
121
123
 
122
124
  ```bash
@@ -129,6 +131,8 @@ npx checkchange check --base main --json
129
131
  pnpm add -g checkchange
130
132
  ```
131
133
 
134
+ The bundled agent skill: see [For AI agents (skill file)](#for-ai-agents-skill-file) below.
135
+
132
136
  Or:
133
137
 
134
138
  ```bash
@@ -168,6 +172,23 @@ If you need a pinned version for reproducibility, use `checkchange@<version>`
168
172
  with the version you want (list available versions with
169
173
  `npm view checkchange versions`).
170
174
 
175
+ ### For AI agents (skill file)
176
+
177
+ The npm tarball ships `.agents/skills/using-checkchange/SKILL.md` inside the
178
+ installed package. npm does not install it into any agent's skills directory,
179
+ and the CLI never writes to your agent config. `checkchange doctor` reports the
180
+ exact path under the `agentSkill` probe (text output or `doctor --json`).
181
+
182
+ Copying the file into your agent's skills directory is your call:
183
+
184
+ ```bash
185
+ cp node_modules/checkchange/.agents/skills/using-checkchange/SKILL.md ~/.config/opencode/skills/using-checkchange/SKILL.md
186
+ ```
187
+
188
+ Use `npm root -g` instead of `node_modules/checkchange` for a global install,
189
+ or copy into `.agents/skills/using-checkchange/SKILL.md` in your repo. Create
190
+ the destination directory first if it does not exist.
191
+
171
192
  ---
172
193
 
173
194
  # Requirements
@@ -438,6 +459,14 @@ Exit codes:
438
459
  | `gate === 'WARN'` | 1 |
439
460
  | `PASS` / `NOT_EVALUATED` | 0 |
440
461
 
462
+ Without `--json`, the summary line always carries the verdict and its
463
+ denominator: `Analysis complete. Base: <base>, Changed functions: <n>,
464
+ Gate: <gate>, Completeness: <COMPLETE|INCOMPLETE>`, plus `Evaluated:
465
+ <evaluated>/<total>` whenever rule results exist (`evaluated` counts the
466
+ PASS/WARN results). A `PASS` can therefore never be presented without the
467
+ count of functions the gate could not evaluate; an empty diff prints no
468
+ `Evaluated:` segment.
469
+
441
470
  ---
442
471
 
443
472
  # 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.d.ts CHANGED
@@ -46,6 +46,14 @@ export declare function detectBase(base: string | null, verbose: boolean): Promi
46
46
  * from pre-dispatcher CLI.
47
47
  */
48
48
  export declare function formatOutput(output: EvidenceOutputShape, opts: CheckArgs, resolvedBase: string, cacheEnabled: boolean): void;
49
+ interface DoctorProbe {
50
+ name: string;
51
+ status: string;
52
+ detail?: string;
53
+ remediation?: string;
54
+ }
55
+ export declare function agentSkillCandidate(moduleDir: string): string;
56
+ export declare function agentSkillProbe(moduleDir: string): DoctorProbe;
49
57
  /**
50
58
  * Main CLI function: subcommand dispatcher. First argument selects the
51
59
  * subcommand; a non-subcommand first argument (e.g. legacy `--base HEAD check`)
package/dist/cli.js CHANGED
@@ -9,6 +9,8 @@ import { FORMATS, format } from './formatters/index.js';
9
9
  import { compareFromFiles } from './delta.js';
10
10
  import { resolveRunner, detectStack, createInstallPlan, promptApproval, executeInstallPlan, flushConfigUpdates, verifyInstall } from './providers/index.js';
11
11
  import * as path from 'node:path';
12
+ import * as fs from 'node:fs';
13
+ import { fileURLToPath } from 'node:url';
12
14
  import { formatHelpText, formatHelpJson, formatVersion } from './help.js';
13
15
  import { probeDotnetSdk } from './complexity-providers/csharpDescriptorProvider.js';
14
16
  // Subcommand dispatcher (check|doctor|explain|trace|delta). Legacy check path
@@ -237,6 +239,18 @@ export async function detectBase(base, verbose) {
237
239
  }
238
240
  return base;
239
241
  }
242
+ /**
243
+ * P7: additive text-path summary counts. Empty ruleResults emit no 0/0.
244
+ */
245
+ function summaryCounts(output) {
246
+ const ruleResults = output.ruleResults ?? [];
247
+ let suffix = `, Completeness: ${output.completeness}`;
248
+ if (ruleResults.length > 0) {
249
+ const evaluated = ruleResults.filter((r) => r.result === 'PASS' || r.result === 'WARN').length;
250
+ suffix += `, Evaluated: ${evaluated}/${ruleResults.length}`;
251
+ }
252
+ return suffix;
253
+ }
240
254
  /**
241
255
  * Emit check output: verbose diagnostics, formatter, JSON/summary, and
242
256
  * FAILED status handling + exit code. Preserves byte-identical output
@@ -267,7 +281,7 @@ export function formatOutput(output, opts, resolvedBase, cacheEnabled) {
267
281
  }
268
282
  else {
269
283
  // 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}`);
284
+ console.log(`Analysis complete. Base: ${resolvedBase}, Changed functions: ${output.changedFunctions.length}, Gate: ${output.gate}${summaryCounts(output)}`);
271
285
  // H2: a FALLBACK complexity stage is otherwise invisible in the text path —
272
286
  // the run reports PASS/NOT_EVALUATED over approximate measurements. Warn on
273
287
  // stderr (stdout stays the machine-readable summary); nothing is printed when
@@ -354,6 +368,18 @@ function probe(name, status, detail, remediation) {
354
368
  function errorMessage(error) {
355
369
  return error instanceof Error ? error.message : String(error);
356
370
  }
371
+ // Announce-only: the packaged skill is reported, never copied or installed.
372
+ // moduleDir is src/ (repo dev) or dist/ (published package); both parents are
373
+ // the package root. Same idiom as src/evidence.ts:78 and src/help.ts:314.
374
+ export function agentSkillCandidate(moduleDir) {
375
+ return path.resolve(moduleDir, '..', '.agents', 'skills', 'using-checkchange', 'SKILL.md');
376
+ }
377
+ export function agentSkillProbe(moduleDir) {
378
+ const candidate = agentSkillCandidate(moduleDir);
379
+ return fs.existsSync(candidate)
380
+ ? probe('agentSkill', 'present', candidate)
381
+ : probe('agentSkill', 'absent', 'skill not found next to the installed CLI', 'reinstall checkchange; the npm package bundles .agents/skills/using-checkchange/SKILL.md');
382
+ }
357
383
  // GAP 5: the .NET/Coverlet half of the coverageArtifact remediation. The command
358
384
  // is the builtin DOTNET_RUNNER command (src/providers/config.ts:94) and the
359
385
  // artifact note is honest about the GUID directory readCoverage actually scans
@@ -455,6 +481,8 @@ async function runDoctor(argv) {
455
481
  probes.push(sdk.available
456
482
  ? probe('csharpSdk', 'ok', sdk.version ?? undefined)
457
483
  : probe('csharpSdk', 'unfixable', sdk.diagnostic?.detail, sdk.diagnostic?.fix));
484
+ // 7. packaged agent skill (informational: no install, no exit-code impact)
485
+ probes.push(agentSkillProbe(path.dirname(fileURLToPath(import.meta.url))));
458
486
  if (json) {
459
487
  console.log(JSON.stringify({ command: 'doctor', probes }, null, 2));
460
488
  }
@@ -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.8
177
+ // its tool is checkchange and its version is the package version — same 0.5.10
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.8';
180
+ const FALLBACK_TOOL_VERSION = '0.5.10';
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.8";
3
+ readonly version: "0.5.10";
4
4
  };
5
5
  export declare function calculateCrap(cc: number, coveragePercent: number | null): number | null;
package/dist/crapCalc.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Provenance for the crapCalc lineage stage. Self tool version tracks package.json.
2
- export const crapCalcProvenance = { tool: 'checkchange', version: '0.5.8' };
2
+ export const crapCalcProvenance = { tool: 'checkchange', version: '0.5.10' };
3
3
  export function calculateCrap(cc, coveragePercent) {
4
4
  if (coveragePercent == null) {
5
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.8";
35
+ readonly version: "0.5.10";
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
24
  // Self provenance; version mirrors package.json.
24
- export const evidenceProvenance = { tool: 'checkchange', version: '0.5.8' };
25
+ export const evidenceProvenance = { tool: 'checkchange', version: '0.5.10' };
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),
@@ -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];
@@ -26,7 +27,7 @@ export function formatJUnit(out, opts) {
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
  }
package/dist/help.js CHANGED
@@ -61,7 +61,8 @@ Probes (always run):
61
61
  defaultBase origin/main or main auto-detected
62
62
  providerAvailability changed file extensions have registered providers
63
63
  coverageArtifact Istanbul JSON, Cobertura XML, or LCOV artifact present and parseable
64
- csharpSdk dotnet --version exits 0 (C# complexity is SDK-based)`,
64
+ csharpSdk dotnet --version exits 0 (C# complexity is SDK-based)
65
+ agentSkill bundled SKILL.md alongside the installed CLI`,
65
66
  flags: [
66
67
  { name: '--json', type: 'boolean', default: false, description: 'Output JSON' },
67
68
  { name: '--provider-config', type: 'string', default: null, description: 'Path to checkchange.providers.json' },
@@ -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.8";
4
+ readonly version: "0.5.10";
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.8' };
2
+ export const rulesProvenance = { tool: 'checkchange', version: '0.5.10' };
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.8",
3
+ "version": "0.5.10",
4
4
  "license": "MIT",
5
5
  "packageManager": "pnpm@11.17.0",
6
6
  "type": "module",