checkchange 0.4.1 → 0.4.3

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.
@@ -0,0 +1,188 @@
1
+ import * as path from 'node:path';
2
+ import * as fs from 'node:fs';
3
+ /**
4
+ * Typed parse failure. `reason` carries the EXISTING CoverageResult.reason
5
+ * value ('malformed', src/coverage.ts:487) so a caller maps a Cobertura refusal
6
+ * onto the current taxonomy without inventing a reason string.
7
+ * The size/line guards throw this too, so a single `instanceof` catch covers
8
+ * every provider-side refusal.
9
+ */
10
+ export class CoberturaParseError extends Error {
11
+ reason = 'malformed';
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = 'CoberturaParseError';
15
+ }
16
+ }
17
+ /**
18
+ * Parse Cobertura XML content and convert it to the same Map shape the core
19
+ * package's parseCoverageReport produces, so coverageForMethods can attribute
20
+ * methods.
21
+ * @param coberturaContent The Cobertura XML file content as string
22
+ * @param cwd Current working directory for path normalization
23
+ * @returns Map<filePath, { statements: Array<{ span: { startLine: number, startColumn: number, endLine: number, endColumn: number }, hits: number }>, branches: [], functions: [] }>
24
+ * Branches and functions are always empty: a `<line branch="true">` element
25
+ * does NOT fabricate a branches array (same precedent as LCOV BRDA being
26
+ * ignored at lcovProvider.ts:70-71). Merge Cobertura with LCOV via
27
+ * mergeCoverageMaps rather than by concatenating raw maps.
28
+ * @throws {CoberturaParseError} on an oversized / over-long / malformed document
29
+ */
30
+ export function parseCoberturaContent(coberturaContent, cwd) {
31
+ // Security: limit Cobertura size to prevent OOM — same cap as lcovProvider.ts:19
32
+ const MAX_SIZE = 100 * 1024 * 1024; // 100MB
33
+ if (coberturaContent.length > MAX_SIZE) {
34
+ throw new CoberturaParseError(`Cobertura content exceeds maximum allowed size of ${MAX_SIZE} bytes`);
35
+ }
36
+ const lines = coberturaContent.split('\n');
37
+ if (lines.length > 1_000_000) {
38
+ throw new CoberturaParseError('Cobertura contains too many lines (over 1,000,000)');
39
+ }
40
+ // Empty artifact yields an empty map, mirroring parseLcovContent's empty input.
41
+ if (coberturaContent.trim() === '') {
42
+ return new Map();
43
+ }
44
+ if (!/<coverage[\s/>]/.test(coberturaContent)) {
45
+ throw new CoberturaParseError('Cobertura document has no <coverage> root element');
46
+ }
47
+ if (!coberturaContent.includes('</coverage>')) {
48
+ throw new CoberturaParseError('Cobertura document is truncated: no closing </coverage>');
49
+ }
50
+ const result = new Map();
51
+ // <class filename> is relative to <sources><source> (Coverlet writes an
52
+ // absolute source root), so the base is needed to resolve the real file.
53
+ let sourceBase = '';
54
+ let currentFile = '';
55
+ // Keyed by line number so a repeated <line number="N"> overwrites, as in LCOV.
56
+ const statements = {};
57
+ const flush = () => {
58
+ if (currentFile && Object.keys(statements).length > 0) {
59
+ const joined = sourceBase ? path.join(sourceBase, currentFile) : currentFile;
60
+ const normalized = normalizePath(joined, cwd);
61
+ if (normalized !== null) {
62
+ const incoming = Object.values(statements);
63
+ const existing = result.get(normalized);
64
+ if (existing === undefined) {
65
+ // Single-class path: plain set, unchanged from before the merge.
66
+ result.set(normalized, { statements: incoming, branches: [], functions: [] });
67
+ }
68
+ else {
69
+ // One file can host several <class> elements (Coverlet emits one per
70
+ // type, all sharing filename="Foo.cs"), so flush() is called again
71
+ // for the same key. Overwriting here dropped the earlier classes'
72
+ // lines and left only the last <class> covered. Merge instead,
73
+ // deduped by start line with MAX hits — a line shared by two types is
74
+ // covered if EITHER type executed it.
75
+ for (const unit of incoming) {
76
+ const at = existing.statements.findIndex(s => s.span.startLine === unit.span.startLine);
77
+ if (at === -1)
78
+ existing.statements.push(unit);
79
+ else if (unit.hits > existing.statements[at].hits)
80
+ existing.statements[at] = unit;
81
+ }
82
+ }
83
+ }
84
+ }
85
+ Object.keys(statements).forEach(k => delete statements[k]);
86
+ currentFile = '';
87
+ };
88
+ for (const raw of lines) {
89
+ const line = raw.trim();
90
+ if (line === '')
91
+ continue;
92
+ const source = line.match(/<source>([^<]*)<\/source>/);
93
+ if (source) {
94
+ sourceBase = decodeXml(source[1]);
95
+ continue;
96
+ }
97
+ // The \b keeps these from also matching <sources>, <classes> and <lines>.
98
+ const openClass = line.match(/<class\b([^>]*)>/);
99
+ if (openClass) {
100
+ flush(); // finalize the previous class before starting a new one
101
+ currentFile = decodeXml(attr(openClass[1], 'filename') ?? '');
102
+ }
103
+ // No `continue` after either match: <class>, <lines>, <line> and </class>
104
+ // are commonly emitted on ONE line, and each must still be seen.
105
+ // Scan EVERY <line> occurrence — a compact document packs several per line.
106
+ for (const lineTag of line.matchAll(/<line\b([^>]*?)\/?>/g)) {
107
+ if (!currentFile)
108
+ continue;
109
+ const numberStr = attr(lineTag[1], 'number');
110
+ const hitsStr = attr(lineTag[1], 'hits');
111
+ const lineNum = numberStr === null ? NaN : Number(numberStr);
112
+ const hits = hitsStr === null ? NaN : Number(hitsStr);
113
+ // Record-level garbage is skipped, not fatal — same as a bad `DA:` line.
114
+ if (Number.isInteger(lineNum) && Number.isFinite(hits)) {
115
+ statements[numberStr] = {
116
+ // Cobertura reports no column info, assume 0
117
+ span: { startLine: lineNum, startColumn: 0, endLine: lineNum, endColumn: 0 },
118
+ hits
119
+ };
120
+ }
121
+ }
122
+ if (/<\/class>/.test(line)) {
123
+ flush();
124
+ }
125
+ }
126
+ flush(); // handle the last class
127
+ return result;
128
+ }
129
+ /** Read a `name="value"` attribute out of a captured start tag. */
130
+ function attr(attrs, name) {
131
+ const match = attrs.match(new RegExp(`\\b${name}="([^"]*)"`));
132
+ return match ? match[1] : null;
133
+ }
134
+ function decodeXml(value) {
135
+ return value
136
+ .replace(/&lt;/g, '<')
137
+ .replace(/&gt;/g, '>')
138
+ .replace(/&quot;/g, '"')
139
+ .replace(/&apos;/g, "'")
140
+ .replace(/&amp;/g, '&');
141
+ }
142
+ /**
143
+ * Check if an absolute file path is within the given cwd.
144
+ * ponytail: duplicated from lcovProvider.ts:94-132 instead of exported from
145
+ * there — this task's file scope is coberturaProvider.ts + coverage.ts + 2 test
146
+ * files, and widening lcovProvider.ts is out of scope. Collapse both copies into
147
+ * a shared module when a third format provider lands.
148
+ */
149
+ function isWithinCwd(filePath, cwd) {
150
+ if (!path.isAbsolute(filePath)) {
151
+ filePath = path.resolve(cwd, filePath);
152
+ }
153
+ const rel = path.relative(cwd, filePath);
154
+ return !rel.startsWith('..') && !path.isAbsolute(rel);
155
+ }
156
+ /**
157
+ * Normalize a Cobertura filename to be relative to cwd if possible, using the
158
+ * same suffix-rebase idea as normalizeCoveragePaths (src/coverage.ts:302-336):
159
+ * an absolute path from another checkout is re-based onto cwd by longest
160
+ * existing suffix.
161
+ * @returns normalized path within cwd, or null if the path escapes cwd and cannot be rebased
162
+ */
163
+ function normalizePath(filePath, cwd) {
164
+ if (!path.isAbsolute(filePath)) {
165
+ const resolved = path.resolve(cwd, filePath);
166
+ return isWithinCwd(resolved, cwd) ? resolved : null;
167
+ }
168
+ // If absolute, first check if it's already within cwd
169
+ if (isWithinCwd(filePath, cwd)) {
170
+ return filePath;
171
+ }
172
+ // Try to rebase to cwd by suffix
173
+ const segments = filePath.split(path.sep);
174
+ for (let i = 1; i < segments.length; i++) {
175
+ const candidate = path.join(cwd, ...segments.slice(i));
176
+ if (!isWithinCwd(candidate, cwd))
177
+ continue;
178
+ try {
179
+ if (fs.existsSync(candidate)) {
180
+ return candidate;
181
+ }
182
+ }
183
+ catch {
184
+ // ignore
185
+ }
186
+ }
187
+ return null;
188
+ }
@@ -14,11 +14,98 @@ export interface CoverageResult {
14
14
  contentSha256?: string;
15
15
  }
16
16
  export declare const PYTHON_COVERAGE_FILES: readonly string[];
17
+ /**
18
+ * Union two coverage maps by file path — the seam a Cobertura artifact and an
19
+ * LCOV artifact feed (parseCoberturaContent + parseLcovContent).
20
+ *
21
+ * A path in only one map is carried through unchanged. A path in both has its
22
+ * statements concatenated and then deduped by start line, keeping the MAX hits:
23
+ * both formats report one statement per source line, so the same line reported
24
+ * twice is one statement, and the higher count is the honest one. Branch and
25
+ * function units are concatenated without dedupe — Cobertura never populates
26
+ * them, and this keeps the seam a plain union rather than a guess about which
27
+ * side is authoritative.
28
+ *
29
+ * KEY MATCHING IS CASE-INSENSITIVE. The parsers disagree on casing for the same
30
+ * file: `parseCoverageReport` (Istanbul) lowercases the whole absolute path,
31
+ * while `parseCoberturaContent` / `parseLcovContent` keep native case. Merging
32
+ * those two with a plain `Map.get(key)` silently matched nothing — one file
33
+ * landed in the merged map TWICE and the MAX-on-conflict rule never ran, which
34
+ * defeats the entire point of merging. Lookup is therefore folded to lower case;
35
+ * the FIRST-SEEN spelling is what the merged map emits, so a map whose keys all
36
+ * agree (Cobertura+LCOV, or any single format) round-trips byte-identical.
37
+ *
38
+ * ponytail: fold for LOOKUP only. Emitting the folded key would rewrite every
39
+ * key of a same-case merge, breaking callers that assert exact key spelling.
40
+ * First-seen wins, which keeps this a pure lookup change and leaves key casing
41
+ * as a property of whichever artifact the caller passed first.
42
+ *
43
+ * Neither input Map nor its FileCoverage values are mutated.
44
+ */
45
+ export declare function mergeCoverageMaps(a: CoverageMap, b: CoverageMap): CoverageMap;
46
+ /**
47
+ * Depth-bounded readdir scan for a `coverage.cobertura.xml` inside any per-run
48
+ * subdirectory of a `TestResults` directory under cwd.
49
+ *
50
+ * Bounded by construction: the `TestResults` directory name is matched at depth 1,
51
+ * 2 and 3 only (cwd itself, each direct child, and each grandchild), so the walk is
52
+ * O(entries in those dirs) with no glob dependency and no unbounded recursion.
53
+ * Depth 3 is required because `dotnet test` run from a REPO ROOT writes the artifact
54
+ * under the TEST PROJECT's directory, not the root — `test/GuardClauses.UnitTests/
55
+ * TestResults/<guid>/` (measured, SHA f96b823e). See `SKIP_SCAN_DIRS` for the prune
56
+ * that keeps `node_modules` out of the grandchild pass.
57
+ *
58
+ * Newest-mtime wins: vstest mints a fresh GUID directory per run and never prunes
59
+ * the old ones, so the most recently written artifact is the one that matches the
60
+ * working tree. Ties break on the lexicographically smaller absolute path so the
61
+ * result is deterministic across filesystems.
62
+ *
63
+ /**
64
+ * EXPORTED for the cached path: src/cache.ts calls this as its last resort so a
65
+ * cached C# run sees the same Coverlet `TestResults/<GUID>/` artifact an uncached
66
+ * run does. The cache used to document that divergence as a KNOWN LIMITATION
67
+ * because this function was module-private.
68
+ *
69
+ * @returns absolute path of the newest match, or null when there is none
70
+ */
71
+ export declare function scanCoberturaUnderTestResults(cwd: string): string | null;
72
+ /**
73
+ * Read the coverage artifacts discoverable under `cwd`.
74
+ *
75
+ * PRECEDENCE (top wins):
76
+ * 1. explicit `--coverage-file` — read alone, returned as-is, never merged
77
+ * 2. literal `coverageFiles` candidates — EVERY readable one is parsed and
78
+ * the resulting maps are REDUCED with `mergeCoverageMaps` in scan order
79
+ * 3. `TestResults` scan (newest mtime) — last resort, only when no literal
80
+ * candidate produced a map
81
+ *
82
+ * Multi-artifact merge (WS2.1): a repo routinely emits more than one coverage
83
+ * format at once (Coverlet Cobertura + an Istanbul `coverage.json`, or pytest-cov
84
+ * + LCOV). First-success-return silently dropped every artifact after the first,
85
+ * so a format that is the ONLY source of coverage for a given file reported it as
86
+ * uncovered. Accumulate-then-reduce unions them instead, keeping MAX hits per
87
+ * source line (`mergeFileCoverage`), which is the honest value when two tools
88
+ * instrument the same line.
89
+ *
90
+ * @lineage `contentSha256` is the hash of the FIRST artifact that produced a map
91
+ * (scan order), NOT of the merged result. `CoverageResult` carries a single hash
92
+ * and `src/evidence.ts:439` consumes it as the coverage lineage input, so the
93
+ * merged-map lineage stays per-artifact and is NOT a digest of the union. Any
94
+ * future consumer needing full-merge lineage must widen `CoverageResult` (a
95
+ * separate, schema-touching change) rather than silently reinterpreting this one.
96
+ *
97
+ * Malformed taxonomy is unchanged: if >=1 candidate was READABLE but none parsed,
98
+ * this returns `{ available:true, error:true, reason:'malformed' }` exactly as
99
+ * before — a partial success is a success, not a malformed read.
100
+ */
17
101
  export declare function readCoverage(cwd: string, coverageFile?: string, trace?: TraceRun, autoGenerated?: boolean): Promise<CoverageResult>;
18
102
  /**
19
103
  * Detect the coverage format and dispatch to the matching parser.
20
104
  *
21
105
  * Routes:
106
+ * - Cobertura: by basename ending `.cobertura.xml`, BEFORE the Python-JSON probe.
107
+ * Coverlet and pytest-cov emit the same Cobertura schema, so the filename is the
108
+ * only robust discriminator; content sniffing cannot separate them.
22
109
  * - LCOV: by extension (`.info`/`.lcov`) or content sniffing (TN:/SF:/DA: lines).
23
110
  * - Python coverage JSON (files key + meta/summary/totals): transformed to Istanbul
24
111
  * first, unless alreadyConverted (i.e. convertPythonCoverageToJson already ran).
package/dist/coverage.js CHANGED
@@ -5,6 +5,7 @@ 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,15 +282,220 @@ 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))]
@@ -300,9 +506,15 @@ export async function readCoverage(cwd, coverageFile, trace, autoGenerated) {
300
506
  await access(filePath, constants.R_OK);
301
507
  artifactFound = true;
302
508
  const result = await readCoverageFile(filePath, cwd, false);
303
- // If conversion/read succeeded (error: false), return it
509
+ // Conversion/read succeeded — ACCUMULATE, never return early
304
510
  if (!result.error) {
305
- return result;
511
+ if (result.coverageMap) {
512
+ mergedMap = mergedMap === null ? result.coverageMap : mergeCoverageMaps(mergedMap, result.coverageMap);
513
+ // First artifact that produced a map owns the reported lineage hash
514
+ if (mergedSha256 === undefined)
515
+ mergedSha256 = result.contentSha256;
516
+ }
517
+ continue;
306
518
  }
307
519
  // Conversion/read failed - warn and continue to next candidate
308
520
  const message = `Coverage conversion failed for ${filePath}: ${result.reason}`;
@@ -318,9 +530,46 @@ export async function readCoverage(cwd, coverageFile, trace, autoGenerated) {
318
530
  // File doesn't exist or not readable, continue to next
319
531
  }
320
532
  }
533
+ // ponytail: a literal candidate produced a map — the merged result wins and the
534
+ // TestResults scan is NOT consulted, so the `artifactFound` short-circuit that
535
+ // test/coverage-cobertura-routing.test.ts:244 pins still holds. Placed before
536
+ // the scan (not after) because the scan's own result must never displace a map
537
+ // the literals already produced.
538
+ if (mergedMap !== null) {
539
+ const out = { available: true, coverageMap: mergedMap, error: false };
540
+ if (mergedSha256 !== undefined)
541
+ out.contentSha256 = mergedSha256;
542
+ return out;
543
+ }
544
+ // 2b. Scan fallback for Coverlet: `dotnet test --collect:"XPlat Code Coverage"`
545
+ // writes TestResults/<GUID>/coverage.cobertura.xml, where the GUID is generated
546
+ // per run by vstest — no literal path can name it, so the config-driven
547
+ // coverageFiles list above can never match. Runs only when NO literal candidate
548
+ // produced a MAP (the merged-map return above already left this branch for a
549
+ // literal hit), so the existing precedence and the malformed-taxonomy behaviour
550
+ // of "found but unconvertible" are untouched. The scan finds exactly ONE
551
+ // artifact (newest mtime), so there is nothing here to merge.
552
+ if (!artifactFound) {
553
+ const scanned = scanCoberturaUnderTestResults(cwd);
554
+ if (scanned !== null) {
555
+ artifactFound = true;
556
+ const result = await readCoverageFile(scanned, cwd, false);
557
+ if (!result.error)
558
+ return result;
559
+ const message = `Coverage conversion failed for ${scanned}: ${result.reason}`;
560
+ if (trace) {
561
+ trace.recordWarning('coverage', message);
562
+ }
563
+ else {
564
+ console.warn(message);
565
+ }
566
+ }
567
+ }
321
568
  // 3. All candidates exhausted
322
569
  if (artifactFound) {
323
- // At least one artifact existed but all failed conversion
570
+ // At least one artifact existed but all failed conversion. Under
571
+ // accumulate-then-reduce this is now "every readable candidate was read and
572
+ // NONE produced a map" — same taxonomy, same shape as the first-success era.
324
573
  return { available: true, coverageMap: null, error: true, reason: 'malformed' };
325
574
  }
326
575
  else {
@@ -332,12 +581,22 @@ export async function readCoverage(cwd, coverageFile, trace, autoGenerated) {
332
581
  * Detect the coverage format and dispatch to the matching parser.
333
582
  *
334
583
  * Routes:
584
+ * - Cobertura: by basename ending `.cobertura.xml`, BEFORE the Python-JSON probe.
585
+ * Coverlet and pytest-cov emit the same Cobertura schema, so the filename is the
586
+ * only robust discriminator; content sniffing cannot separate them.
335
587
  * - LCOV: by extension (`.info`/`.lcov`) or content sniffing (TN:/SF:/DA: lines).
336
588
  * - Python coverage JSON (files key + meta/summary/totals): transformed to Istanbul
337
589
  * first, unless alreadyConverted (i.e. convertPythonCoverageToJson already ran).
338
590
  * - Otherwise: parsed directly as Istanbul JSON.
339
591
  */
340
592
  export async function detectCoverageFormat(content, actualPath, cwd, isLcovByExt, alreadyConverted) {
593
+ // Cobertura first, keyed on basename: a `.cobertura.xml` artifact is Cobertura
594
+ // whether it came from Coverlet or pytest-cov, and it is never Istanbul JSON,
595
+ // so answering before the LCOV and Python-JSON probes below is what keeps it
596
+ // off the `coverage json` conversion path.
597
+ if (isCoberturaBasename(actualPath)) {
598
+ return parseCoberturaContent(content, cwd);
599
+ }
341
600
  // Check if LCOV by content
342
601
  let isLcov = isLcovByExt;
343
602
  if (!isLcovByExt) {
@@ -401,7 +660,12 @@ async function readCoverageFile(coveragePath, cwd, isExplicit, autoGenerated) {
401
660
  const basename = path.basename(coveragePath);
402
661
  const isLcovByExt = ext === '.info' || ext === '.lcov';
403
662
  const isPythonCoverageBinary = basename === '.coverage';
404
- const isPythonCoverageXml = ext === '.xml' && basename.startsWith('coverage');
663
+ // Exact basename, not `startsWith('coverage')`: the prefix form also claimed
664
+ // `coverage.cobertura.xml`, sending a Coverlet artifact into `coverage json`
665
+ // conversion and returning reason 'malformed' (:548) before any format
666
+ // dispatch ran. `.cobertura.xml` is Cobertura; only `coverage.xml` is the
667
+ // pytest-cov artifact `coverage json` can read.
668
+ const isPythonCoverageXml = ext === '.xml' && basename === 'coverage.xml';
405
669
  // For Python .coverage binary or coverage.xml, try to convert to JSON first
406
670
  let actualPath = coveragePath;
407
671
  let tempFileToCleanup = null;
@@ -1,5 +1,5 @@
1
1
  export declare const crapCalcProvenance: {
2
2
  readonly tool: "checkchange";
3
- readonly version: "0.4.1";
3
+ readonly version: "0.4.2";
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.1' };
3
+ export const crapCalcProvenance = { tool: 'checkchange', version: '0.4.2' };
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.1";
34
+ readonly version: "0.4.2";
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: