checkchange 0.4.2 → 0.4.4

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/dist/coverage.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import * as path from 'node:path';
2
2
  import * as fs from 'node:fs';
3
- import { access, constants, readFile } from 'node:fs/promises';
3
+ import { access, constants, readFile, readdir } from 'node:fs/promises';
4
4
  import { spawnSync } from 'node:child_process';
5
5
  import { createHash } from 'node:crypto';
6
6
  import { parseCoverageReport } from '@barney-media/crap-typescript-core';
7
7
  import { parseLcovContent } from './coverage-providers/lcovProvider.js';
8
+ import { parseCoberturaContent } from './coverage-providers/coberturaProvider.js';
8
9
  import { openWithinRoot } from './fs-safety.js';
9
10
  import { providerRegistry } from './evidence.js';
10
11
  // Provenance for the coverage lineage stage: artifact parser from the core package.
@@ -281,28 +282,243 @@ function normalizeCoveragePaths(coverageMap, cwd) {
281
282
  }
282
283
  return normalized;
283
284
  }
285
+ /**
286
+ * Union two coverage maps by file path — the seam a Cobertura artifact and an
287
+ * LCOV artifact feed (parseCoberturaContent + parseLcovContent).
288
+ *
289
+ * A path in only one map is carried through unchanged. A path in both has its
290
+ * statements concatenated and then deduped by start line, keeping the MAX hits:
291
+ * both formats report one statement per source line, so the same line reported
292
+ * twice is one statement, and the higher count is the honest one. Branch and
293
+ * function units are concatenated without dedupe — Cobertura never populates
294
+ * them, and this keeps the seam a plain union rather than a guess about which
295
+ * side is authoritative.
296
+ *
297
+ * KEY MATCHING IS CASE-INSENSITIVE. The parsers disagree on casing for the same
298
+ * file: `parseCoverageReport` (Istanbul) lowercases the whole absolute path,
299
+ * while `parseCoberturaContent` / `parseLcovContent` keep native case. Merging
300
+ * those two with a plain `Map.get(key)` silently matched nothing — one file
301
+ * landed in the merged map TWICE and the MAX-on-conflict rule never ran, which
302
+ * defeats the entire point of merging. Lookup is therefore folded to lower case;
303
+ * the FIRST-SEEN spelling is what the merged map emits, so a map whose keys all
304
+ * agree (Cobertura+LCOV, or any single format) round-trips byte-identical.
305
+ *
306
+ * ponytail: fold for LOOKUP only. Emitting the folded key would rewrite every
307
+ * key of a same-case merge, breaking callers that assert exact key spelling.
308
+ * First-seen wins, which keeps this a pure lookup change and leaves key casing
309
+ * as a property of whichever artifact the caller passed first.
310
+ *
311
+ * Neither input Map nor its FileCoverage values are mutated.
312
+ */
313
+ export function mergeCoverageMaps(a, b) {
314
+ const merged = new Map();
315
+ /** folded key -> the spelling already stored in `merged` */
316
+ const canonical = new Map();
317
+ const add = (key, value) => {
318
+ const folded = key.toLowerCase();
319
+ const seen = canonical.get(folded);
320
+ if (seen === undefined) {
321
+ canonical.set(folded, key);
322
+ merged.set(key, value);
323
+ return;
324
+ }
325
+ merged.set(seen, mergeFileCoverage(merged.get(seen), value));
326
+ };
327
+ for (const [key, value] of a)
328
+ add(key, value);
329
+ for (const [key, value] of b)
330
+ add(key, value);
331
+ return merged;
332
+ }
333
+ function mergeFileCoverage(a, b) {
334
+ // Map preserves first-seen line order; the unit stored for a line is the max-hits one.
335
+ const byLine = new Map();
336
+ for (const unit of [...a.statements, ...b.statements]) {
337
+ const seen = byLine.get(unit.span.startLine);
338
+ if (seen === undefined || unit.hits > seen.hits) {
339
+ byLine.set(unit.span.startLine, unit);
340
+ }
341
+ }
342
+ return {
343
+ statements: [...byLine.values()],
344
+ branches: [...a.branches, ...b.branches],
345
+ functions: [...a.functions, ...b.functions]
346
+ };
347
+ }
348
+ const COBERTURA_BASENAME = 'coverage.cobertura.xml';
349
+ // Directories the depth-3 walk must never descend into. `node_modules` is unbounded
350
+ // in size and a plausible home for a vendored `TestResults/` (proved in
351
+ // test/coverage-cobertura-routing.test.ts); `.git` is noise. Pruning at the depth-1
352
+ // child keeps the "bounded by construction" claim below honest — without it the
353
+ // widening to depth 3 would be a walk of every package tree under cwd.
354
+ // ponytail: duplicated from src/providers/runner-detection.ts SKIP_DIRS rather than
355
+ // imported — that set also skips dist/build/coverage, which a coverage scan must
356
+ // NOT skip (it is looking for artifacts there), and the module is provider-private.
357
+ const SKIP_SCAN_DIRS = new Set(['node_modules', '.git']);
358
+ /** True for any `*.cobertura.xml` path, case-insensitively (Windows-authored artifacts). */
359
+ function isCoberturaBasename(filePath) {
360
+ return path.basename(filePath).toLowerCase().endsWith('.cobertura.xml');
361
+ }
362
+ /**
363
+ * Depth-bounded readdir scan for a `coverage.cobertura.xml` inside any per-run
364
+ * subdirectory of a `TestResults` directory under cwd.
365
+ *
366
+ * Bounded by construction: the `TestResults` directory name is matched at depth 1,
367
+ * 2 and 3 only (cwd itself, each direct child, and each grandchild), so the walk is
368
+ * O(entries in those dirs) with no glob dependency and no unbounded recursion.
369
+ * Depth 3 is required because `dotnet test` run from a REPO ROOT writes the artifact
370
+ * under the TEST PROJECT's directory, not the root — `test/GuardClauses.UnitTests/
371
+ * TestResults/<guid>/` (measured, SHA f96b823e). See `SKIP_SCAN_DIRS` for the prune
372
+ * that keeps `node_modules` out of the grandchild pass.
373
+ *
374
+ * Newest-mtime wins: vstest mints a fresh GUID directory per run and never prunes
375
+ * the old ones, so the most recently written artifact is the one that matches the
376
+ * working tree. Ties break on the lexicographically smaller absolute path so the
377
+ * result is deterministic across filesystems.
378
+ *
379
+ /**
380
+ * EXPORTED for the cached path: src/cache.ts calls this as its last resort so a
381
+ * cached C# run sees the same Coverlet `TestResults/<GUID>/` artifact an uncached
382
+ * run does. The cache used to document that divergence as a KNOWN LIMITATION
383
+ * because this function was module-private.
384
+ *
385
+ * @returns absolute path of the newest match, or null when there is none
386
+ */
387
+ export function scanCoberturaUnderTestResults(cwd) {
388
+ const testResultsDirs = [];
389
+ const addIfTestResults = (dir) => {
390
+ try {
391
+ if (fs.readdirSync(dir, { withFileTypes: true }).some((e) => e.isDirectory() && e.name === 'TestResults')) {
392
+ testResultsDirs.push(path.join(dir, 'TestResults'));
393
+ }
394
+ }
395
+ catch {
396
+ // unreadable directory — nothing to scan
397
+ }
398
+ };
399
+ addIfTestResults(cwd);
400
+ try {
401
+ for (const entry of fs.readdirSync(cwd, { withFileTypes: true })) {
402
+ if (!entry.isDirectory())
403
+ continue;
404
+ const child = path.join(cwd, entry.name);
405
+ addIfTestResults(child);
406
+ // Depth 3: `dotnet test` run from a repo root writes the artifact under the
407
+ // TEST PROJECT's own directory, not the root —
408
+ // `test/GuardClauses.UnitTests/TestResults/<guid>/` (measured, SHA f96b823e)
409
+ // and `test/Stateless.Tests/TestResults/<guid>/` (SHA 588f1a1a). Depth 2
410
+ // alone missed both, so doctor reported `missing` on repos that HAVE the
411
+ // artifact. 3 is the measured worst case across the pinned corpus
412
+ // (`NCrontab.Tests/TestResults/<guid>/` is depth 2), so the bound is exactly
413
+ // 3 — not "until found", which would be an unbounded walk.
414
+ if (SKIP_SCAN_DIRS.has(entry.name))
415
+ continue;
416
+ try {
417
+ for (const grand of fs.readdirSync(child, { withFileTypes: true })) {
418
+ if (grand.isDirectory())
419
+ addIfTestResults(path.join(child, grand.name));
420
+ }
421
+ }
422
+ catch {
423
+ // unreadable child directory — its grandchildren are simply not scanned
424
+ }
425
+ }
426
+ }
427
+ catch {
428
+ // unreadable cwd — no scan
429
+ }
430
+ let newest = null;
431
+ for (const resultsDir of testResultsDirs) {
432
+ let runDirs;
433
+ try {
434
+ runDirs = fs.readdirSync(resultsDir, { withFileTypes: true });
435
+ }
436
+ catch {
437
+ continue;
438
+ }
439
+ for (const runDir of runDirs) {
440
+ if (!runDir.isDirectory())
441
+ continue;
442
+ const file = path.join(resultsDir, runDir.name, COBERTURA_BASENAME);
443
+ try {
444
+ const { mtimeMs } = fs.statSync(file);
445
+ if (newest === null ||
446
+ mtimeMs > newest.mtimeMs ||
447
+ (mtimeMs === newest.mtimeMs && file < newest.file)) {
448
+ newest = { file, mtimeMs };
449
+ }
450
+ }
451
+ catch {
452
+ // not a cobertura artifact — skip
453
+ }
454
+ }
455
+ }
456
+ return newest?.file ?? null;
457
+ }
458
+ /**
459
+ * Read the coverage artifacts discoverable under `cwd`.
460
+ *
461
+ * PRECEDENCE (top wins):
462
+ * 1. explicit `--coverage-file` — read alone, returned as-is, never merged
463
+ * 2. literal `coverageFiles` candidates — EVERY readable one is parsed and
464
+ * the resulting maps are REDUCED with `mergeCoverageMaps` in scan order
465
+ * 3. `TestResults` scan (newest mtime) — last resort, only when no literal
466
+ * candidate produced a map
467
+ *
468
+ * Multi-artifact merge (WS2.1): a repo routinely emits more than one coverage
469
+ * format at once (Coverlet Cobertura + an Istanbul `coverage.json`, or pytest-cov
470
+ * + LCOV). First-success-return silently dropped every artifact after the first,
471
+ * so a format that is the ONLY source of coverage for a given file reported it as
472
+ * uncovered. Accumulate-then-reduce unions them instead, keeping MAX hits per
473
+ * source line (`mergeFileCoverage`), which is the honest value when two tools
474
+ * instrument the same line.
475
+ *
476
+ * @lineage `contentSha256` is the hash of the FIRST artifact that produced a map
477
+ * (scan order), NOT of the merged result. `CoverageResult` carries a single hash
478
+ * and `src/evidence.ts:439` consumes it as the coverage lineage input, so the
479
+ * merged-map lineage stays per-artifact and is NOT a digest of the union. Any
480
+ * future consumer needing full-merge lineage must widen `CoverageResult` (a
481
+ * separate, schema-touching change) rather than silently reinterpreting this one.
482
+ *
483
+ * Malformed taxonomy is unchanged: if >=1 candidate was READABLE but none parsed,
484
+ * this returns `{ available:true, error:true, reason:'malformed' }` exactly as
485
+ * before — a partial success is a success, not a malformed read.
486
+ */
284
487
  export async function readCoverage(cwd, coverageFile, trace, autoGenerated) {
285
488
  // 1. Explicit coverageFile provided - use it directly (existing behavior)
286
489
  if (coverageFile !== undefined && coverageFile !== null && coverageFile !== '') {
287
490
  const coveragePath = path.isAbsolute(coverageFile) ? coverageFile : path.resolve(cwd, coverageFile);
288
491
  return await readCoverageFile(coveragePath, cwd, true, autoGenerated);
289
492
  }
290
- // 2. Auto-detect coverage files in precedence order with fallthrough on conversion failure
291
- // Precedence: config-driven — all providers' coverageFiles deduped in builtin order
493
+ // 2. Auto-detect coverage files. Precedence: config-driven — all providers'
494
+ // coverageFiles deduped in builtin order. EVERY readable candidate is parsed;
495
+ // the maps are accumulated and reduced at the end (see @lineage above).
292
496
  let artifactFound = false;
497
+ let mergedMap = null;
498
+ let mergedSha256;
293
499
  const registry = providerRegistry();
294
500
  const coverageCandidates = registry
295
501
  ? [...new Set([...registry.values()].flatMap((r) => r.coverageFiles))]
296
502
  : [...PYTHON_COVERAGE_FILES];
297
503
  for (const file of coverageCandidates) {
298
- const filePath = path.join(cwd, file);
504
+ // WS4: the exact literal is still tried FIRST (precedence unchanged), and only a
505
+ // miss falls through to a case-insensitive lookup in the candidate's own directory.
506
+ // null = miss, skipped exactly as silently as before.
507
+ const filePath = await resolveReadableCandidate(cwd, file);
508
+ if (filePath === null)
509
+ continue;
299
510
  try {
300
- await access(filePath, constants.R_OK);
301
511
  artifactFound = true;
302
512
  const result = await readCoverageFile(filePath, cwd, false);
303
- // If conversion/read succeeded (error: false), return it
513
+ // Conversion/read succeeded — ACCUMULATE, never return early
304
514
  if (!result.error) {
305
- return result;
515
+ if (result.coverageMap) {
516
+ mergedMap = mergedMap === null ? result.coverageMap : mergeCoverageMaps(mergedMap, result.coverageMap);
517
+ // First artifact that produced a map owns the reported lineage hash
518
+ if (mergedSha256 === undefined)
519
+ mergedSha256 = result.contentSha256;
520
+ }
521
+ continue;
306
522
  }
307
523
  // Conversion/read failed - warn and continue to next candidate
308
524
  const message = `Coverage conversion failed for ${filePath}: ${result.reason}`;
@@ -315,12 +531,50 @@ export async function readCoverage(cwd, coverageFile, trace, autoGenerated) {
315
531
  // Continue to next file in precedence
316
532
  }
317
533
  catch {
318
- // File doesn't exist or not readable, continue to next
534
+ // Read/conversion threw (it normally returns a result object instead) — continue
535
+ // to the next candidate, same as before.
536
+ }
537
+ }
538
+ // ponytail: a literal candidate produced a map — the merged result wins and the
539
+ // TestResults scan is NOT consulted, so the `artifactFound` short-circuit that
540
+ // test/coverage-cobertura-routing.test.ts:244 pins still holds. Placed before
541
+ // the scan (not after) because the scan's own result must never displace a map
542
+ // the literals already produced.
543
+ if (mergedMap !== null) {
544
+ const out = { available: true, coverageMap: mergedMap, error: false };
545
+ if (mergedSha256 !== undefined)
546
+ out.contentSha256 = mergedSha256;
547
+ return out;
548
+ }
549
+ // 2b. Scan fallback for Coverlet: `dotnet test --collect:"XPlat Code Coverage"`
550
+ // writes TestResults/<GUID>/coverage.cobertura.xml, where the GUID is generated
551
+ // per run by vstest — no literal path can name it, so the config-driven
552
+ // coverageFiles list above can never match. Runs only when NO literal candidate
553
+ // produced a MAP (the merged-map return above already left this branch for a
554
+ // literal hit), so the existing precedence and the malformed-taxonomy behaviour
555
+ // of "found but unconvertible" are untouched. The scan finds exactly ONE
556
+ // artifact (newest mtime), so there is nothing here to merge.
557
+ if (!artifactFound) {
558
+ const scanned = scanCoberturaUnderTestResults(cwd);
559
+ if (scanned !== null) {
560
+ artifactFound = true;
561
+ const result = await readCoverageFile(scanned, cwd, false);
562
+ if (!result.error)
563
+ return result;
564
+ const message = `Coverage conversion failed for ${scanned}: ${result.reason}`;
565
+ if (trace) {
566
+ trace.recordWarning('coverage', message);
567
+ }
568
+ else {
569
+ console.warn(message);
570
+ }
319
571
  }
320
572
  }
321
573
  // 3. All candidates exhausted
322
574
  if (artifactFound) {
323
- // At least one artifact existed but all failed conversion
575
+ // At least one artifact existed but all failed conversion. Under
576
+ // accumulate-then-reduce this is now "every readable candidate was read and
577
+ // NONE produced a map" — same taxonomy, same shape as the first-success era.
324
578
  return { available: true, coverageMap: null, error: true, reason: 'malformed' };
325
579
  }
326
580
  else {
@@ -328,16 +582,73 @@ export async function readCoverage(cwd, coverageFile, trace, autoGenerated) {
328
582
  return { available: false, coverageMap: null, error: false };
329
583
  }
330
584
  }
585
+ /**
586
+ * Resolve one literal coverage candidate to a readable path, or null on a miss.
587
+ *
588
+ * The EXACT literal is tried first and returns unchanged, so precedence is untouched: a
589
+ * candidate that exists keeps winning over any case-variant sibling beside it. Only on a
590
+ * miss do we list the candidate's OWN directory — a single `readdir`, no recursion, depth
591
+ * fixed at one — and take the first name matching case-insensitively.
592
+ *
593
+ * Why here and not in the config literals: `access()` is case-sensitive on Linux ext4, so
594
+ * an artifact emitted as `COVERAGE.XML` was invisible to discovery there while the same
595
+ * repo reported coverage on macOS's case-insensitive APFS. Fixing discovery (not the
596
+ * literal list) makes every provider's `coverageFiles` benefit, and it cannot turn a glob
597
+ * entry into something that works: exactly one basename is ever consulted.
598
+ */
599
+ async function resolveReadableCandidate(cwd, file) {
600
+ const exact = path.join(cwd, file);
601
+ try {
602
+ await access(exact, constants.R_OK);
603
+ return exact;
604
+ }
605
+ catch {
606
+ // Miss — fall through to the case-insensitive sibling lookup.
607
+ }
608
+ const dir = path.dirname(exact);
609
+ const wanted = path.basename(exact).toLowerCase();
610
+ let names;
611
+ try {
612
+ names = await readdir(dir);
613
+ }
614
+ catch {
615
+ // Missing/unreadable directory — a miss, skipped silently exactly as before. A cwd
616
+ // that is a FILE also lands here (ENOTDIR), which is the degradation the WS3.4 arms
617
+ // pin for the scan.
618
+ return null;
619
+ }
620
+ const hit = names.find((name) => name.toLowerCase() === wanted);
621
+ if (hit === undefined)
622
+ return null;
623
+ const sibling = path.join(dir, hit);
624
+ try {
625
+ await access(sibling, constants.R_OK);
626
+ return sibling;
627
+ }
628
+ catch {
629
+ return null;
630
+ }
631
+ }
331
632
  /**
332
633
  * Detect the coverage format and dispatch to the matching parser.
333
634
  *
334
635
  * Routes:
636
+ * - Cobertura: by basename ending `.cobertura.xml`, BEFORE the Python-JSON probe.
637
+ * Coverlet and pytest-cov emit the same Cobertura schema, so the filename is the
638
+ * only robust discriminator; content sniffing cannot separate them.
335
639
  * - LCOV: by extension (`.info`/`.lcov`) or content sniffing (TN:/SF:/DA: lines).
336
640
  * - Python coverage JSON (files key + meta/summary/totals): transformed to Istanbul
337
641
  * first, unless alreadyConverted (i.e. convertPythonCoverageToJson already ran).
338
642
  * - Otherwise: parsed directly as Istanbul JSON.
339
643
  */
340
644
  export async function detectCoverageFormat(content, actualPath, cwd, isLcovByExt, alreadyConverted) {
645
+ // Cobertura first, keyed on basename: a `.cobertura.xml` artifact is Cobertura
646
+ // whether it came from Coverlet or pytest-cov, and it is never Istanbul JSON,
647
+ // so answering before the LCOV and Python-JSON probes below is what keeps it
648
+ // off the `coverage json` conversion path.
649
+ if (isCoberturaBasename(actualPath)) {
650
+ return parseCoberturaContent(content, cwd);
651
+ }
341
652
  // Check if LCOV by content
342
653
  let isLcov = isLcovByExt;
343
654
  if (!isLcovByExt) {
@@ -401,7 +712,12 @@ async function readCoverageFile(coveragePath, cwd, isExplicit, autoGenerated) {
401
712
  const basename = path.basename(coveragePath);
402
713
  const isLcovByExt = ext === '.info' || ext === '.lcov';
403
714
  const isPythonCoverageBinary = basename === '.coverage';
404
- const isPythonCoverageXml = ext === '.xml' && basename.startsWith('coverage');
715
+ // Exact basename, not `startsWith('coverage')`: the prefix form also claimed
716
+ // `coverage.cobertura.xml`, sending a Coverlet artifact into `coverage json`
717
+ // conversion and returning reason 'malformed' (:548) before any format
718
+ // dispatch ran. `.cobertura.xml` is Cobertura; only `coverage.xml` is the
719
+ // pytest-cov artifact `coverage json` can read.
720
+ const isPythonCoverageXml = ext === '.xml' && basename.toLowerCase() === 'coverage.xml';
405
721
  // For Python .coverage binary or coverage.xml, try to convert to JSON first
406
722
  let actualPath = coveragePath;
407
723
  let tempFileToCleanup = null;
@@ -1,5 +1,5 @@
1
1
  export declare const crapCalcProvenance: {
2
2
  readonly tool: "checkchange";
3
- readonly version: "0.4.2";
3
+ readonly version: "0.4.4";
4
4
  };
5
5
  export declare function calculateCrap(cc: number, coveragePercent: number | null): number | null;
package/dist/crapCalc.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Provenance for the crapCalc lineage stage. Self tool version tracks package.json
2
2
  // (matches existing hard-coded '0.5.0' style for the core package).
3
- export const crapCalcProvenance = { tool: 'checkchange', version: '0.4.2' };
3
+ export const crapCalcProvenance = { tool: 'checkchange', version: '0.4.4' };
4
4
  export function calculateCrap(cc, coveragePercent) {
5
5
  if (coveragePercent == null) {
6
6
  return null;
@@ -31,7 +31,7 @@ export interface DiagnosticLineageEntry {
31
31
  }
32
32
  export declare const evidenceProvenance: {
33
33
  readonly tool: "checkchange";
34
- readonly version: "0.4.2";
34
+ readonly version: "0.4.4";
35
35
  };
36
36
  export interface EvidenceOutput {
37
37
  schemaVersion: string;
@@ -68,7 +68,7 @@ export interface UncoveredFunction {
68
68
  }
69
69
  export interface DiagnosticQuality {
70
70
  coverage: 'DIRECT' | 'UNAVAILABLE';
71
- complexity: 'NATIVE' | 'UNAVAILABLE';
71
+ complexity: 'NATIVE' | 'FALLBACK' | 'UNAVAILABLE';
72
72
  /**
73
73
  * Deterministic evidence score 0-100, closed-form arithmetic over evidence
74
74
  * values only (no model judgment). Formula:
package/dist/evidence.js CHANGED
@@ -4,8 +4,9 @@ import { readCoverage } from './coverage.js';
4
4
  import { attachCoverage } from './attribution.js';
5
5
  import { calculateCrap } from './crapCalc.js';
6
6
  import { pythonASTComplexityProvider } from './complexity-providers/pythonASTComplexityProvider.js';
7
+ import { csharpComplexityProvider } from './complexity-providers/csharpComplexityProvider.js';
7
8
  import { gitProvenance } from './git.js';
8
- import { complexityProvenance } from './complexity.js';
9
+ import { measurementProvenance, measurementQuality, measurementDegradations } from './complexity.js';
9
10
  import { coverageProvenance } from './coverage.js';
10
11
  import { attributionProvenance } from './attribution.js';
11
12
  import { crapCalcProvenance } from './crapCalc.js';
@@ -19,7 +20,7 @@ import * as path from 'path';
19
20
  import { loadProviderConfig, deriveRegistry, builtinConfig, createGenericCommandProvider } from './providers/index.js';
20
21
  const requireFromEvidence = createRequire(import.meta.url);
21
22
  // Self provenance; version mirrors package.json (existing codebase style hard-codes '0.5.0').
22
- export const evidenceProvenance = { tool: 'checkchange', version: '0.4.2' };
23
+ export const evidenceProvenance = { tool: 'checkchange', version: '0.4.4' };
23
24
  function sha256Hex(content) {
24
25
  return createHash('sha256').update(content).digest('hex');
25
26
  }
@@ -88,7 +89,7 @@ function buildQuality(params) {
88
89
  : null;
89
90
  const quality = {
90
91
  coverage: params.coverageUsable ? 'DIRECT' : 'UNAVAILABLE',
91
- complexity: stageComplete.complexity ? 'NATIVE' : 'UNAVAILABLE',
92
+ complexity: stageComplete.complexity ? (params.complexityQuality ?? 'NATIVE') : 'UNAVAILABLE',
92
93
  score,
93
94
  stageComplete,
94
95
  };
@@ -184,7 +185,7 @@ export function initProviderConfig(explicitPath, allowExternalConfig = false) {
184
185
  _providerRegistry = registry;
185
186
  // Derive extension priority from registry: reverse provider order so later providers
186
187
  // (e.g. python) get higher priority than earlier ones (e.g. javascript).
187
- // DEFAULT_EXTENSION_PRIORITY: .py > .ts > .tsx > .js > .jsx > .mjs > .cjs > .ts
188
+ // DEFAULT_EXTENSION_PRIORITY: .cs > .py > .ts > .tsx > .js > .jsx > .mjs > .cjs > .ts
188
189
  const seen = new Set();
189
190
  _extensionPriority = [];
190
191
  for (const entry of [...config.providers].reverse()) {
@@ -218,6 +219,12 @@ export function initProviderConfig(explicitPath, allowExternalConfig = false) {
218
219
  readCoverage: (...args) => readCoverage(...args),
219
220
  });
220
221
  }
222
+ else if (resolved.language === 'csharp') {
223
+ registerProvider(ext, {
224
+ collectComplexity: (...args) => csharpComplexityProvider.collectComplexity(...args),
225
+ readCoverage: (...args) => readCoverage(...args),
226
+ });
227
+ }
221
228
  }
222
229
  _supportedExtensions = new Set(registry.keys());
223
230
  rebuildLanguageMap();
@@ -324,11 +331,20 @@ export function detectExtension(intervals) {
324
331
  return '.ts';
325
332
  }
326
333
  // ---- Extracted helper: gate + completeness from rule results ----
334
+ // H1 (§5 vacuous-PASS ban, ADR 0023): `hasWarn ? 'WARN' : 'PASS'` answered PASS
335
+ // over a set where NOTHING was evaluated — every result NOT_EVALUATED (null CRAP,
336
+ // i.e. null coverage on the changed function). That is a bare PASS claiming a
337
+ // clean bill of health for a run that measured nothing. Non-empty AND all
338
+ // NOT_EVALUATED → NOT_EVALUATED: the EXISTING gate vocabulary (README:335,
339
+ // evidence.ts:679 applyAbsentCoverageGate), so no new enum value and no schema
340
+ // field. Deliberately narrow — one real PASS still passes, one real WARN still
341
+ // warns, empty still passes (nothing to claim).
327
342
  export function computeGateAndCompleteness(ruleResults) {
328
343
  const hasWarn = ruleResults.some((r) => r.result === 'WARN');
329
344
  const hasNotEvaluated = ruleResults.some((r) => r.result === 'NOT_EVALUATED');
345
+ const allNotEvaluated = ruleResults.length > 0 && ruleResults.every((r) => r.result === 'NOT_EVALUATED');
330
346
  return {
331
- gate: hasWarn ? 'WARN' : 'PASS',
347
+ gate: hasWarn ? 'WARN' : allNotEvaluated ? 'NOT_EVALUATED' : 'PASS',
332
348
  completeness: hasNotEvaluated ? 'INCOMPLETE' : 'COMPLETE',
333
349
  };
334
350
  }
@@ -541,7 +557,11 @@ export function mapToMethodEvidence(attributedComplexity) {
541
557
  coverage: ac.coveragePercent,
542
558
  coverageKind: ac.coverageKind ?? 'N/A',
543
559
  analyzerStatus: (ac.coveragePercent !== null && ac.coveragePercent !== undefined ? 'passed' : 'skipped'),
544
- source: { tool: '@barney-media/crap-typescript-core', version: '0.5.0' },
560
+ // GAP 8: per-language, from the measurement. The TypeScript analyzer sets no
561
+ // provenance, so this returns `complexityProvenance` unchanged and the .ts
562
+ // evidence JSON is byte-identical to before. A .cs function reports the tool
563
+ // that actually measured it — the Roslyn vehicle or the fallback parser.
564
+ source: measurementProvenance(ac.info),
545
565
  }));
546
566
  }
547
567
  export function correlate(methodEvidence, intervals) {
@@ -612,7 +632,7 @@ export function buildOutput(base, changed, threshold = 30, capabilities = { git:
612
632
  * output when analysis should stop, or null to continue.
613
633
  * ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity.
614
634
  */
615
- function resolveCoverageFailure(coverageCapability, coverageErrorReason, autoGenerated, base, gitCapability, complexityCapability, threshold, lineage, complexityCapabilityForQuality) {
635
+ function resolveCoverageFailure(coverageCapability, coverageErrorReason, autoGenerated, base, gitCapability, complexityCapability, threshold, lineage, complexityCapabilityForQuality, complexityQuality) {
616
636
  let analysisStatus = 'SUCCESS';
617
637
  let gate = null;
618
638
  let completeness = 'COMPLETE';
@@ -624,7 +644,7 @@ function resolveCoverageFailure(coverageCapability, coverageErrorReason, autoGen
624
644
  analysisStatus = 'FAILED';
625
645
  completeness = 'INCOMPLETE';
626
646
  return {
627
- earlyReturn: withDiagnostics(buildFailedOutput(base, gitCapability, complexityCapability, 'failed', threshold, coverageErrorReason), lineage, buildQuality({ complexityCapability: complexityCapabilityForQuality, coverageUsable: false })),
647
+ earlyReturn: withDiagnostics(buildFailedOutput(base, gitCapability, complexityCapability, 'failed', threshold, coverageErrorReason), lineage, buildQuality({ complexityCapability: complexityCapabilityForQuality, complexityQuality, coverageUsable: false })),
628
648
  coverageCapability: 'failed', coverageErrorReason, analysisStatus, gate, completeness
629
649
  };
630
650
  }
@@ -657,7 +677,7 @@ async function attachCoverageWithTracking(complexityInfo, coverageResult, trace,
657
677
  trace.recordStage('attribution', Date.now() - t0, 'error');
658
678
  return {
659
679
  attributedComplexity: [],
660
- earlyReturn: withDiagnostics(buildFailedOutput(base, gitCapability, complexityCapability, coverageCapability, threshold, coverageErrorReason), lineage, buildQuality({ complexityCapability, coverageUsable: !coverageResult.error && coverageResult.available === true }))
680
+ earlyReturn: withDiagnostics(buildFailedOutput(base, gitCapability, complexityCapability, coverageCapability, threshold, coverageErrorReason), lineage, buildQuality({ complexityCapability, complexityQuality: measurementQuality(complexityInfo), coverageUsable: !coverageResult.error && coverageResult.available === true }))
661
681
  };
662
682
  }
663
683
  }
@@ -712,14 +732,24 @@ export async function buildEvidenceOutput(base, intervals, cwd, threshold = 30,
712
732
  }
713
733
  if (trace)
714
734
  trace.recordStage('complexity', Date.now() - t0Complexity, complexityCapability === 'failed' ? 'error' : 'ok');
735
+ // GAP 9, second half: `quality` says a stage fell back; these say WHY. Distinct
736
+ // provider reason codes (e.g. `csharp-analysis-failed`), provider-owned, read off
737
+ // the measurement. The key is spread in ONLY when non-empty, so a `.ts` run's
738
+ // lineage `inputs` key-set AND order are unchanged — native TypeScript sets no
739
+ // degradation, so `degradationCodes` is `[]` there.
740
+ const degradationCodes = measurementDegradations(complexityInfo);
715
741
  lineage.push({
716
742
  stage: 'complexity',
717
- ...complexityProvenance,
743
+ ...measurementProvenance(complexityInfo[0]),
718
744
  inputs: {
719
745
  extension: detectedExtension,
720
746
  functions: complexityInfo.length,
721
- // Canonical vocabulary (ADR-0001): native analyzer present => NATIVE, failed => UNAVAILABLE
722
- quality: complexityCapability === 'failed' ? 'UNAVAILABLE' : 'NATIVE'
747
+ // Canonical vocabulary (ADR-0001): native analyzer => NATIVE, an
748
+ // approximation of one => FALLBACK, provider threw => UNAVAILABLE.
749
+ // `DEGRADED` is NOT a contract value — it stays adapter prose in
750
+ // csharpComplexityProvider.describe() (SD-3).
751
+ quality: complexityCapability === 'failed' ? 'UNAVAILABLE' : measurementQuality(complexityInfo),
752
+ ...(degradationCodes.length > 0 ? { degradationCodes } : {})
723
753
  }
724
754
  });
725
755
  // Vacuous-PASS ban (§5): no files in diff + no supported extensions →
@@ -752,7 +782,7 @@ export async function buildEvidenceOutput(base, intervals, cwd, threshold = 30,
752
782
  analysisStatus: 'UNSUPPORTED',
753
783
  gate: null,
754
784
  completeness: 'INCOMPLETE'
755
- }, lineage, buildQuality({ complexityCapability, coverageUsable: false }));
785
+ }, lineage, buildQuality({ complexityCapability, complexityQuality: measurementQuality(complexityInfo), coverageUsable: false }));
756
786
  }
757
787
  // Step 2: Read coverage
758
788
  const t0Coverage = Date.now();
@@ -788,11 +818,11 @@ export async function buildEvidenceOutput(base, intervals, cwd, threshold = 30,
788
818
  analysisStatus: 'UNSUPPORTED',
789
819
  gate: null,
790
820
  completeness: 'NOT_APPLICABLE'
791
- }, lineage, buildQuality({ complexityCapability, coverageUsable: false }));
821
+ }, lineage, buildQuality({ complexityCapability, complexityQuality: measurementQuality(complexityInfo), coverageUsable: false }));
792
822
  return earlyReturn;
793
823
  }
794
824
  // If coverage provider failed (malformed)
795
- const covRes = resolveCoverageFailure(coverageCapability, coverageErrorReason, autoGenerated, base, gitCapability, complexityCapability, threshold, lineage, complexityCapability);
825
+ const covRes = resolveCoverageFailure(coverageCapability, coverageErrorReason, autoGenerated, base, gitCapability, complexityCapability, threshold, lineage, complexityCapability, measurementQuality(complexityInfo));
796
826
  if (covRes.earlyReturn)
797
827
  return covRes.earlyReturn;
798
828
  coverageCapability = covRes.coverageCapability;
@@ -874,6 +904,7 @@ export async function buildEvidenceOutput(base, intervals, cwd, threshold = 30,
874
904
  completeness: completenessValue
875
905
  }, lineage, buildQuality({
876
906
  complexityCapability,
907
+ complexityQuality: measurementQuality(complexityInfo),
877
908
  coverageUsable: coverageResult.available === true && coverageResult.error === false,
878
909
  attributionComplete: true,
879
910
  rulesComplete: true,
package/dist/help.js CHANGED
@@ -15,7 +15,7 @@ Options:
15
15
  --json Output JSON (default: false)
16
16
  --cache Enable incremental caching (default: off; also CHECKCHANGE_CACHE=1 env)
17
17
  --crap-threshold <number> CRAP threshold for WARN (default: 30)
18
- --coverage-file <path> Istanbul coverage JSON file path
18
+ --coverage-file <path> Coverage file: Istanbul JSON, Cobertura XML, or LCOV
19
19
  --auto-coverage Detect test runner, generate coverage artifact, retry [experimental]
20
20
  --format <name> Output format: github, junit, sarif (default: none)
21
21
  --provider-config <path> Path to checkchange.providers.json (overrides builtin defaults)
@@ -31,7 +31,7 @@ const CHECK = {
31
31
  { name: '--json', type: 'boolean', default: false, description: 'Output JSON' },
32
32
  { name: '--cache', type: 'boolean', default: false, description: 'Enable incremental caching (CHECKCHANGE_CACHE=1)' },
33
33
  { name: '--crap-threshold', type: 'number', default: 30, description: 'CRAP threshold for WARN' },
34
- { name: '--coverage-file', type: 'string', default: null, description: 'Istanbul coverage JSON file path' },
34
+ { name: '--coverage-file', type: 'string', default: null, description: 'Coverage file: Istanbul JSON, Cobertura XML, or LCOV' },
35
35
  { name: '--auto-coverage', type: 'boolean', default: false, description: 'Auto-generate coverage artifact [experimental]' },
36
36
  { name: '--format', type: 'string', default: null, description: 'Output format: github, junit, sarif' },
37
37
  { name: '--provider-config', type: 'string', default: null, description: 'Path to checkchange.providers.json' },
@@ -60,7 +60,8 @@ Probes (always run):
60
60
  gitRepo current directory is a git repo
61
61
  defaultBase origin/main or main auto-detected
62
62
  providerAvailability changed file extensions have registered providers
63
- coverageArtifact Istanbul coverage JSON present and parseable`,
63
+ coverageArtifact Istanbul JSON, Cobertura XML, or LCOV artifact present and parseable
64
+ csharpSdk dotnet --version exits 0 (C# complexity is SDK-based)`,
64
65
  flags: [
65
66
  { name: '--json', type: 'boolean', default: false, description: 'Output JSON' },
66
67
  { name: '--provider-config', type: 'string', default: null, description: 'Path to checkchange.providers.json' },