checkchange 0.4.2 → 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.
package/README.md CHANGED
@@ -109,7 +109,7 @@ Those are evidence states, not judgments about whether the software is ultimatel
109
109
 
110
110
  The package is published on npm as `checkchange`.
111
111
 
112
- Current registry version: **0.4.1**
112
+ Current registry version: **0.4.2**
113
113
 
114
114
  ### npm
115
115
 
@@ -159,7 +159,7 @@ node dist/cli.js check --base main --json
159
159
 
160
160
  The repository includes an `.nvmrc` and the required pnpm version is specified in `package.json`.
161
161
 
162
- For repositories using the Python analysis path, Python 3 plus the relevant testing/coverage tooling may also be required.
162
+ For repositories using the Python analysis path, Python 3 plus the relevant testing/coverage tooling may also be required. For C# repositories, the .NET SDK is optional — without it, CheckChange analyses `.cs` files via a pure-TypeScript fallback parser in degraded mode rather than failing.
163
163
 
164
164
  ---
165
165
 
@@ -264,8 +264,9 @@ The current implementation supports analysis for:
264
264
  - TypeScript
265
265
  - JavaScript
266
266
  - Python
267
+ - C#
267
268
 
268
- Coverage can be supplied through the supported coverage paths, including Istanbul-compatible coverage and LCOV.
269
+ Coverage can be supplied through the supported coverage paths, including Istanbul-compatible coverage, LCOV, and Coverlet Cobertura XML.
269
270
 
270
271
  CheckChange also supports CI-oriented output formats:
271
272
 
@@ -446,7 +447,7 @@ The main runtime requirements are:
446
447
  - pnpm 11.17.0
447
448
  - Git
448
449
 
449
- The supported analysis paths also use packages for TypeScript/JavaScript complexity and coverage processing, along with Python tooling where the Python analysis path is used.
450
+ The supported analysis paths also use packages for TypeScript/JavaScript complexity and coverage processing, along with Python tooling where the Python analysis path is used. For C# analysis, the .NET SDK is optional — when present, CheckChange probes for a Roslyn-based vehicle (`dotnet-crap`, the Crap4DotNet 0.1.1 tool); if the SDK is available and the tool is installed, it serves rich cyclomatic complexity with a fallback bodySpan hybrid join when the vehicle succeeds; `csharp-analysis-failed` is emitted only when the vehicle itself fails (spawn error, no coverage artifact, unparseable payload, or no span join). When the SDK is absent, a `csharp-sdk-missing` diagnostic and fix proposal are emitted with the fallback parser.
450
451
 
451
452
  For the authoritative dependency versions and provider details, see `package.json` and the project documentation.
452
453
 
@@ -1,11 +1,5 @@
1
1
  import type { CoverageResult } from './coverage.js';
2
- interface ComplexityInfo {
3
- file: string;
4
- method: string;
5
- lineStart: number;
6
- lineEnd: number;
7
- cc: number;
8
- }
2
+ import type { ComplexityInfo } from './complexity.js';
9
3
  export declare const attributionProvenance: {
10
4
  readonly tool: "@barney-media/crap-typescript-core";
11
5
  readonly version: "0.5.0";
@@ -16,4 +10,3 @@ export interface AttributedComplexity {
16
10
  coverageKind: string | null;
17
11
  }
18
12
  export declare function attachCoverage(complexityInfo: ComplexityInfo[], coverageResult: CoverageResult): Promise<AttributedComplexity[]>;
19
- export {};
@@ -1,6 +1,18 @@
1
1
  import { parseFileMethods } from '@barney-media/crap-typescript-core';
2
2
  import { coverageForMethods } from '@barney-media/crap-typescript-core';
3
3
  import { parsePythonFileMethods } from './complexity-providers/pythonDescriptorProvider.js';
4
+ // Language-specific descriptor parsers. `coverageForMethods` is language-
5
+ // agnostic (it attributes by `bodySpan` containment), so a parser that emits
6
+ // the shared MethodDescriptor shape is all the join needs per language.
7
+ //
8
+ // KNOWN LIMITATION (deliberate, not an oversight): the rich vehicle's output is
9
+ // NOT consulted here. `csharpDescriptorProvider.isRichDescriptor`
10
+ // (csharpDescriptorProvider.ts:65) does not require `bodySpan`, so a descriptor
11
+ // set from that path can be missing the field `coverageForMethods` needs.
12
+ // Attribution therefore always uses the fallback parser's span. Closing that
13
+ // gap means teaching the rich vehicle to emit bodySpan, which is a larger
14
+ // change than this fix and is tracked separately.
15
+ import { parseCsharpFileMethods } from './complexity-providers/csharpFallbackParser.js';
4
16
  // Provenance for the attribution lineage stage: coverageForMethods/parseFileMethods from the core package.
5
17
  export const attributionProvenance = { tool: '@barney-media/crap-typescript-core', version: '0.5.0' };
6
18
  export async function attachCoverage(complexityInfo, coverageResult) {
@@ -93,7 +105,9 @@ async function descriptorsForFile(filePath, descriptorCache) {
93
105
  try {
94
106
  const methodDescriptors = filePath.endsWith('.py')
95
107
  ? await parsePythonFileMethods(filePath)
96
- : await parseFileMethods(filePath);
108
+ : filePath.endsWith('.cs')
109
+ ? await parseCsharpFileMethods(filePath)
110
+ : await parseFileMethods(filePath);
97
111
  descriptorCache.set(filePath, methodDescriptors);
98
112
  return methodDescriptors;
99
113
  }
@@ -69,7 +69,13 @@ export function autoCoverage(cwd) {
69
69
  runner = { command: cmd, args, artifact: path.join(cwd, first.artifact) };
70
70
  }
71
71
  if (!runner) {
72
- return { generatedPath: null, hint: 'No test runner detected. Install vitest, jest, or pytest to use --auto-coverage.' };
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, to use --auto-coverage.' };
73
79
  }
74
80
  const fullCommand = [runner.command, ...runner.args];
75
81
  const isBuiltinRunner = builtinConfig().providers.some(({ testRunners }) => testRunners?.some(({ command }) => command.length === fullCommand.length && command.every((arg, index) => arg === fullCommand[index])));
package/dist/cache.js CHANGED
@@ -11,7 +11,7 @@ import { access, constants, mkdir, readFile, readdir, rename, rm, stat, unlink,
11
11
  import { openWithinRoot } from './fs-safety.js';
12
12
  import { findAllTypeScriptFilesUnderSourceRoots, parseFileMethods } from '@barney-media/crap-typescript-core';
13
13
  import { getGitTrackedCodeFiles, complexityProvenance } from './complexity.js';
14
- import { readCoverage, coverageProvenance } from './coverage.js';
14
+ import { readCoverage, coverageProvenance, scanCoberturaUnderTestResults, mergeCoverageMaps } from './coverage.js';
15
15
  import { registerProvider, providerRegistry, getProvider } from './evidence.js';
16
16
  export const CACHE_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days, mtime-based (no clock in key)
17
17
  export const MAX_CACHE_TOTAL_BYTES = 500 * 1024 * 1024; // 500MB total, LRU-pruned on write-through
@@ -377,22 +377,51 @@ async function cachedReadCoveragePath(coveragePath, cwd) {
377
377
  }
378
378
  }
379
379
  // ponytail: extracted candidate-search loop from cachedReadCoverage to reduce CRAP.
380
- // Iterates coverageCandidates; returns first accessible, non-error result.
380
+ // Iterates coverageCandidates; ACCUMULATES every accessible, non-error result and
381
+ // reduces them with mergeCoverageMaps in scan order — the same accumulate-then-reduce
382
+ // seam the uncached readCoverage applies (src/coverage.ts, WS2.1). A repo emitting
383
+ // more than one coverage format (Coverlet Cobertura + an Istanbul coverage.json) had
384
+ // every artifact after the first silently dropped on this path too.
385
+ //
386
+ // Symmetry is trivial here because the cache is keyed PER ARTIFACT
387
+ // (`{kind:'coverage', coverageHash}` over one file's bytes, :390-391): each component
388
+ // is cached and invalidated independently by its own artifact hash, and the merge
389
+ // happens in memory after the per-artifact lookup — so merging cannot serve a stale
390
+ // union that no single artifact's hash would have invalidated.
391
+ //
392
+ // @lineage mirrors readCoverage: the returned `contentSha256` is the FIRST artifact
393
+ // that produced a map (scan order), not a digest of the merged map.
394
+ //
395
+ // Returns null when no candidate produced a map, which is what leaves the
396
+ // TestResults scan (and its documented residual limit below) reachable.
381
397
  async function findCoverageCandidate(candidates, cwd) {
398
+ let mergedMap = null;
399
+ let mergedSha256;
382
400
  for (const candidate of candidates) {
383
401
  const filePath = path.join(cwd, candidate);
384
402
  try {
385
403
  await access(filePath, constants.R_OK);
386
404
  const result = await cachedReadCoveragePath(filePath, cwd);
387
- if (!result.error)
388
- return result;
405
+ if (!result.error) {
406
+ if (result.coverageMap) {
407
+ mergedMap = mergedMap === null ? result.coverageMap : mergeCoverageMaps(mergedMap, result.coverageMap);
408
+ if (mergedSha256 === undefined)
409
+ mergedSha256 = result.contentSha256;
410
+ }
411
+ continue;
412
+ }
389
413
  cacheWarnings.push(`Coverage conversion failed for ${filePath}: ${result.reason}`);
390
414
  }
391
415
  catch {
392
416
  // not accessible, continue
393
417
  }
394
418
  }
395
- return null;
419
+ if (mergedMap === null)
420
+ return null;
421
+ const out = { available: true, coverageMap: mergedMap, error: false };
422
+ if (mergedSha256 !== undefined)
423
+ out.contentSha256 = mergedSha256;
424
+ return out;
396
425
  }
397
426
  async function cachedReadCoverage(cwd, coverageFile) {
398
427
  if (coverageFile !== undefined && coverageFile !== null && coverageFile !== '') {
@@ -410,8 +439,35 @@ async function cachedReadCoverage(cwd, coverageFile) {
410
439
  const coverageCandidates = registry
411
440
  ? [...new Set([...registry.values()].flatMap((r) => r.coverageFiles))]
412
441
  : ['.coverage', 'coverage.xml', 'coverage.json', 'coverage/coverage-final.json']; // builtin defaults
442
+ // Coverlet parity (GAP: cached C# runs reported "no coverage"). `dotnet test
443
+ // --collect:"XPlat Code Coverage"` writes TestResults/<GUID>/coverage.cobertura.xml,
444
+ // a per-run GUID no literal config candidate can name — so this scan is the ONLY
445
+ // way a cached C# run reaches that artifact. It runs LAST, after every literal
446
+ // candidate failed to produce a map, which is the same precedence the uncached
447
+ // path applies (`if (mergedMap !== null) return` before its scan): a readable or
448
+ // convertible literal candidate still wins, and `--coverage-file` still
449
+ // short-circuits everything above. WS2.2 made the literal side merge rather than
450
+ // take the first hit, so both paths now agree on the accumulated result.
451
+ //
452
+ // RESIDUAL LIMIT (deliberate, not an oversight): when the scan FINDS an artifact
453
+ // that then fails conversion, this returns `{ available: false }` where the
454
+ // uncached path returns `{ available: true, error: true, reason: 'malformed' }`.
455
+ // The cached path has always warned-and-continued for an unconvertible literal
456
+ // candidate instead of failing hard; changing that taxonomy here would alter
457
+ // behaviour for every language, which is a separate change with its own blast
458
+ // radius. The case that was actually broken — a GOOD artifact invisible to the
459
+ // cache — is closed.
413
460
  const found = await findCoverageCandidate(coverageCandidates, cwd);
414
- return found ?? { available: false, coverageMap: null, error: false };
461
+ if (found)
462
+ return found;
463
+ const scanned = scanCoberturaUnderTestResults(cwd);
464
+ if (scanned !== null) {
465
+ const result = await cachedReadCoveragePath(scanned, cwd);
466
+ if (!result.error)
467
+ return result;
468
+ cacheWarnings.push(`Coverage conversion failed for ${scanned}: ${result.reason}`);
469
+ }
470
+ return { available: false, coverageMap: null, error: false };
415
471
  }
416
472
  export function registerCachedProviders() {
417
473
  cacheWarnings.length = 0; // reset per registration — in-process re-invocations must not accumulate stale warnings
package/dist/cli.d.ts CHANGED
@@ -29,6 +29,10 @@ interface EvidenceOutputShape {
29
29
  complexity?: string;
30
30
  coverage?: string;
31
31
  };
32
+ lineage?: {
33
+ stage: string;
34
+ inputs: Record<string, unknown>;
35
+ }[];
32
36
  };
33
37
  }
34
38
  /**
package/dist/cli.js CHANGED
@@ -10,13 +10,14 @@ 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
12
  import { formatHelpText, formatHelpJson, formatVersion } from './help.js';
13
+ import { probeDotnetSdk } from './complexity-providers/csharpDescriptorProvider.js';
13
14
  // Subcommand dispatcher (check|doctor|explain|trace|delta). Legacy check path
14
15
  // output is byte-identical to the pre-dispatcher CLI; doctor/explain/trace/delta
15
16
  // emit sidecar diagnostics only — never EvidenceOutput-shaped data.
16
17
  const SUBCOMMANDS = ['check', 'doctor', 'explain', 'trace', 'delta', 'prepare-repo'];
17
18
  // File extensions that map to a registered provider (evidence.ts registerProvider).
18
19
  // Replaced by config-derived set after initProviderConfig() in runDoctor/runCheck.
19
- let SUPPORTED_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.py']);
20
+ let SUPPORTED_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.py', '.cs']);
20
21
  /**
21
22
  * Parses command line arguments for the `check` subcommand.
22
23
  * Returns parsed args or prints error and exits.
@@ -186,6 +187,16 @@ export function parseCliArgs(argv = process.argv.slice(2)) {
186
187
  }
187
188
  return { base, json, crapThreshold, coverageFile, verbose, allowExternalConfig, ...(cache ? { cache: true } : {}), ...(autoCoverage ? { autoCoverage: true } : {}), ...(format === undefined ? {} : { format }), ...(providerConfigPath === undefined ? {} : { providerConfig: providerConfigPath }) };
188
189
  }
190
+ /**
191
+ * H2: the degradation codes behind the complexity stage's fallback, in
192
+ * first-seen order. Empty for a native TypeScript run (the key is spread in only
193
+ * when non-empty), so the text path below stays byte-identical there.
194
+ */
195
+ function degradationCodes(output) {
196
+ const entry = output.diagnostics?.lineage?.find((l) => l.stage === 'complexity');
197
+ const codes = entry?.inputs.degradationCodes;
198
+ return Array.isArray(codes) ? codes : [];
199
+ }
189
200
  /**
190
201
  * Auto-detect base reference. If base is non-null returns it directly,
191
202
  * otherwise tries detectDefaultBase. Exits on failure.
@@ -232,6 +243,13 @@ export function formatOutput(output, opts, resolvedBase, cacheEnabled) {
232
243
  else {
233
244
  // For WP1, we primarily want JSON, but let's output a simple summary if not JSON
234
245
  console.log(`Analysis complete. Base: ${resolvedBase}, Changed functions: ${output.changedFunctions.length}`);
246
+ // H2: a FALLBACK complexity stage is otherwise invisible in the text path —
247
+ // the run reports PASS/NOT_EVALUATED over approximate measurements. Warn on
248
+ // stderr (stdout stays the machine-readable summary); nothing is printed when
249
+ // no degradation code exists, so a native TypeScript run is unchanged.
250
+ for (const code of degradationCodes(output)) {
251
+ console.error(`Warning: complexity measurement degraded (${code}) — results are approximate`);
252
+ }
235
253
  }
236
254
  if (output.analysisStatus === 'FAILED') {
237
255
  if (output.coverageErrorReason === 'missing') {
@@ -312,6 +330,11 @@ function probe(name, status, detail, remediation) {
312
330
  function errorMessage(error) {
313
331
  return error instanceof Error ? error.message : String(error);
314
332
  }
333
+ // GAP 5: the .NET/Coverlet half of the coverageArtifact remediation. The command
334
+ // is the builtin DOTNET_RUNNER command (src/providers/config.ts:94) and the
335
+ // artifact note is honest about the GUID directory readCoverage actually scans
336
+ // (src/coverage.ts:491) — no literal path can name it.
337
+ const DOTNET_COVERAGE_HINT = ' or `dotnet test --collect:"XPlat Code Coverage"` (C#/Coverlet — scanned at TestResults/<guid>/coverage.cobertura.xml)';
315
338
  /**
316
339
  * `doctor` subcommand: environment probes. Reuses existing validate/detect
317
340
  * helpers and covered read paths (readCoverage applies MAX_SIZE + path guards);
@@ -378,8 +401,13 @@ async function runDoctor(argv) {
378
401
  // 5. coverage artifact presence (reuse readCoverage — LCOV guards inside)
379
402
  const coverage = await readCoverage(cwd);
380
403
  let note;
404
+ // GAP 5: the Coverlet command is only meaningful when a C# runner is in scope,
405
+ // so the remediation stays byte-identical to the pre-C# text for a JS/TS-only
406
+ // repo. `rr` is resolved once and reused by BOTH the note and this condition.
407
+ let csharpInScope = false;
381
408
  try {
382
409
  const rr = resolveRunner(cwd, registry);
410
+ csharpInScope = rr.has('csharp');
383
411
  note = rr.size > 0
384
412
  ? ' Detected runners: ' + [...rr.entries()].map(([l, r]) => l + '->' + r.command.join(' ')).join('; ')
385
413
  : ' No test runner detected for this repo layout.';
@@ -391,7 +419,17 @@ async function runDoctor(argv) {
391
419
  ? probe('coverageArtifact', 'malformed', coverage.reason ?? '', 'coverage artifact present but could not be parsed — inspect it and regenerate a valid coverage JSON (e.g. `npx vitest run --coverage`).')
392
420
  : coverage.available
393
421
  ? probe('coverageArtifact', 'present')
394
- : probe('coverageArtifact', 'missing', undefined, 'coverage artifact not found — generate one: `npx vitest run --coverage` (JS/TS) or `coverage run -m pytest && coverage json` (Python), then pass `--coverage-file <path>.`' + note));
422
+ : probe('coverageArtifact', 'missing', undefined, 'coverage artifact not found — generate one: `npx vitest run --coverage` (JS/TS) or `coverage run -m pytest && coverage json` (Python)' + (csharpInScope ? DOTNET_COVERAGE_HINT : '') + ', then pass `--coverage-file <path>.`' + note));
423
+ // 6. .NET SDK usability for C# (GAP 4). The CSharpDiagnostic computed by the
424
+ // provider has NO consumer in src/ — `describe()` was its only sink — so the
425
+ // fix proposal never reached the user. Reuse the provider's memoised
426
+ // `probeDotnetSdk()`; cli.ts spawns nothing itself (no second `dotnet
427
+ // --version`, which the memo at csharpDescriptorProvider.ts:132 exists to
428
+ // prevent). Status and fix are passed through verbatim, never re-invented.
429
+ const sdk = probeDotnetSdk();
430
+ probes.push(sdk.available
431
+ ? probe('csharpSdk', 'ok', sdk.version ?? undefined)
432
+ : probe('csharpSdk', 'unfixable', sdk.diagnostic?.detail, sdk.diagnostic?.fix));
395
433
  if (json) {
396
434
  console.log(JSON.stringify({ command: 'doctor', probes }, null, 2));
397
435
  }
@@ -0,0 +1,9 @@
1
+ import type { ComplexityInfo } from '../complexity.ts';
2
+ import { type CoverageResult } from '../coverage.js';
3
+ export interface CSharpComplexityProvider {
4
+ extensions: string[];
5
+ collectComplexity: (cwd: string) => Promise<ComplexityInfo[]>;
6
+ describe(): string;
7
+ readCoverage: (cwd: string, file?: string) => Promise<CoverageResult>;
8
+ }
9
+ export declare const csharpComplexityProvider: CSharpComplexityProvider;
@@ -0,0 +1,142 @@
1
+ /**
2
+ * C# complexity provider — the dispatcher registered as a ProviderFactory in
3
+ * Task 4. Mirrors src/complexity-providers/pythonASTComplexityProvider.ts:
4
+ * the interface at :6-11, the exported singleton at :13, and the readCoverage
5
+ * delegation at :169 (this adapter calls `readCoverage(cwd, file)` from
6
+ * src/coverage.ts rather than re-reading artifacts).
7
+ *
8
+ * It does NOT re-implement parsing or probing — those live in
9
+ * ./csharpDescriptorProvider.ts (probe + rich/fallback dispatch) and
10
+ * ./csharpFallbackParser.ts (pure-TS approximation). This module's whole job is
11
+ * the repo walk plus the ComplexityInfo projection attribution consumes.
12
+ *
13
+ * There is deliberately NO diagnostic channel here. ProviderFactory
14
+ * (src/evidence.ts:252-255) exposes only `collectComplexity` + `readCoverage`,
15
+ * and src/evidence.ts reads neither `describe()` nor any diagnostic surface, so
16
+ * inventing one would be dead weight. Degradation is instead observable three
17
+ * ways that already exist: `probeDotnetSdk()` / `analyzeCsharpFile()` return the
18
+ * diagnostic object directly, and `describe()` carries the human-readable
19
+ * degraded-mode note with its fix proposal.
20
+ *
21
+ * `collectComplexity` consumes BOTH halves of the diagnostic, at two different
22
+ * sinks. The machine-readable half rides as `ComplexityInfo.provenance`
23
+ * (`provenanceForMode(mode)` plus `diagnostic.code` as `degradation`) — no new
24
+ * channel on ProviderFactory is needed, and `measurementQuality` /
25
+ * `measurementDegradations` in src/complexity.ts read it without ever learning a
26
+ * csharp vehicle id. The human-readable half stays in `describe()`. So the two
27
+ * sinks answer two different questions and neither duplicates the other.
28
+ *
29
+ * SECURITY POSTURE: the file walk is `spawnSync('find', [...])` — argv-only,
30
+ * no `sh -c`, no shell string — copied from the Python provider for parity.
31
+ */
32
+ import { spawnSync } from 'node:child_process';
33
+ import { relative } from 'node:path';
34
+ import { readCoverage } from '../coverage.js';
35
+ import { analyzeCsharpFile, probeDotnetSdk, provenanceForMode, vehicleRejection } from './csharpDescriptorProvider.js';
36
+ /**
37
+ * Locate `.cs` files under cwd, pruning node_modules and .git. Same `find`
38
+ * argv-only invocation as pythonASTComplexityProvider.ts:18.
39
+ *
40
+ * No filename-guard copy is made here: `./csharpFallbackParser.ts` already owns
41
+ * the byte-for-byte `isValidFileName` guard (pythonDescriptorProvider.ts:21-24
42
+ * parity) and THROWS on a traversal or shell-metacharacter payload. The
43
+ * per-file catch below turns that throw into a skip, which is the same outcome a
44
+ * pre-filter would give without duplicating the predicate a fourth time.
45
+ */
46
+ function findCsharpFiles(cwd) {
47
+ const res = spawnSync('find', [
48
+ cwd,
49
+ '-path',
50
+ `${cwd}/node_modules`,
51
+ '-prune',
52
+ '-o',
53
+ '-path',
54
+ `${cwd}/.git`,
55
+ '-prune',
56
+ '-o',
57
+ '-name',
58
+ '*.cs',
59
+ '-type',
60
+ 'f',
61
+ '-print',
62
+ ], { encoding: 'utf8' });
63
+ if (res.status !== 0)
64
+ return [];
65
+ return String(res.stdout ?? '')
66
+ .split('\n')
67
+ .map((line) => line.trim())
68
+ .filter((line) => line.length > 0);
69
+ }
70
+ export const csharpComplexityProvider = {
71
+ extensions: ['.cs'],
72
+ collectComplexity: async (cwd) => {
73
+ const info = [];
74
+ for (const file of findCsharpFiles(cwd)) {
75
+ try {
76
+ const { descriptors, mode, diagnostic } = await analyzeCsharpFile(file);
77
+ // ponytail: ONE provenance value for the whole file — `mode` is per-file,
78
+ // so a repo measured half rich and half fallback reports BOTH tools
79
+ // truthfully per function rather than one averaged lie.
80
+ const provenance = provenanceForMode(mode);
81
+ // The CSharpDiagnostic's machine code rides along so the complexity
82
+ // LINEAGE entry can name WHY the stage fell back. It had no sink at all
83
+ // before: `describe()` is never called from src/, so `csharp-analysis-failed`
84
+ // reached no consumer, and `doctor` cannot reach it either — nothing has
85
+ // invoked the vehicle in a doctor run.
86
+ const measured = diagnostic === null ? provenance : { ...provenance, degradation: diagnostic.code };
87
+ for (const d of descriptors) {
88
+ info.push({
89
+ // Repo-relative, verbatim in spirit from pythonASTComplexityProvider.ts:149
90
+ // ("Convert to relative path for consistency with other providers").
91
+ // Mandatory, not cosmetic: `find` prints ABSOLUTE paths, but
92
+ // correlate() looks the file up in the changed-interval Map whose keys
93
+ // come from `git diff` (repo-relative). Absolute ⇒ lookup miss ⇒
94
+ // changedFunctions empty for every .cs repo, with analysisStatus still
95
+ // SUCCESS — a silent nothing. Backslash normalisation matches python so a
96
+ // Windows-generated Coverlet `filename` key lines up too.
97
+ file: relative(cwd, file).replace(/\\/g, '/'),
98
+ // displayName is already `Container.Name` (or bare `Name` at top
99
+ // level), which is exactly the `info.method` form attribution keys
100
+ // against at src/attribution.ts:144.
101
+ method: d.displayName,
102
+ lineStart: d.startLine,
103
+ lineEnd: d.endLine,
104
+ cc: d.complexity,
105
+ // GAP 8: which analyzer produced THIS value, and whether it was an
106
+ // approximation. Consumed by measurementProvenance (source.tool) and
107
+ // measurementQuality (diagnostics.quality.complexity === 'FALLBACK').
108
+ provenance: measured,
109
+ });
110
+ }
111
+ }
112
+ catch {
113
+ // An unreadable path is a caller bug and the fallback parser THROWS on
114
+ // it. One bad file must not abort the batch, so it is skipped — the same
115
+ // non-aborting posture as the Python provider.
116
+ }
117
+ }
118
+ return info;
119
+ },
120
+ describe() {
121
+ const probe = probeDotnetSdk();
122
+ if (!probe.available) {
123
+ const d = probe.diagnostic;
124
+ return `C# complexity provider — DEGRADED [${d.code}]: ${d.message} Fix: ${d.fix} (probe: ${d.detail})`;
125
+ }
126
+ // An SDK on PATH is NOT healthy on its own. If the vehicle was ever rejected,
127
+ // every C# file measured so far used the fallback approximation — so say that,
128
+ // rather than reporting a healthy provider over approximate CC.
129
+ const rejected = vehicleRejection();
130
+ if (rejected) {
131
+ return `C# complexity provider — DEGRADED [${rejected.code}]: ${rejected.message} Fix: ${rejected.fix} (vehicle: ${rejected.detail})`;
132
+ }
133
+ return (
134
+ // `||` not `??`: a healthy SDK that prints nothing yields '', not null, and
135
+ // `??` would render a blank version in the note.
136
+ `C# complexity provider — dotnet ${probe.version || 'unknown'} detected; the Roslyn vehicle is probed per ` +
137
+ 'file and degrades to the pure-TypeScript approximation with a csharp-analysis-failed diagnostic when unusable.');
138
+ },
139
+ // Delegation verbatim in spirit from pythonASTComplexityProvider.ts:169 —
140
+ // reuse src/coverage.ts, never re-read the artifact.
141
+ readCoverage: (cwd, file) => readCoverage(cwd, file),
142
+ };
@@ -0,0 +1,84 @@
1
+ import type { MeasurementProvenance } from '../complexity.ts';
2
+ export type { MethodDescriptor } from './csharpFallbackParser.js';
3
+ import type { MethodDescriptor } from './csharpFallbackParser.js';
4
+ /**
5
+ * The vehicle shim, by absolute path when `dotnet tool install -g` put it where
6
+ * this repo knows it lands (C-1), else the bare name for a PATH-installed copy.
7
+ * Never modifies PATH or any shell profile.
8
+ */
9
+ export declare function vehicleCommand(): string;
10
+ export interface CSharpDiagnostic {
11
+ /** Stable machine-readable reason. Never a bare failure. */
12
+ code: 'csharp-sdk-missing' | 'csharp-analysis-failed';
13
+ /** What is degraded, in plain words. */
14
+ message: string;
15
+ /** A concrete action a human can take. `csharp-sdk-missing` always names `dotnet`. */
16
+ fix: string;
17
+ /** The exact probe command and its observed result. */
18
+ detail: string;
19
+ }
20
+ export interface DotnetProbe {
21
+ available: boolean;
22
+ version: string | null;
23
+ diagnostic: CSharpDiagnostic | null;
24
+ }
25
+ export interface CSharpAnalysis {
26
+ descriptors: MethodDescriptor[];
27
+ mode: 'rich' | 'fallback';
28
+ diagnostic: CSharpDiagnostic | null;
29
+ }
30
+ /**
31
+ * The most recent vehicle rejection observed in this process, else null. NEVER a
32
+ * probe result: SDK-missing lives on `probeDotnetSdk().diagnostic`.
33
+ */
34
+ export declare function vehicleRejection(): CSharpDiagnostic | null;
35
+ /**
36
+ * Which tool measured a file, per the mode `analyzeCsharpFile` returned. The
37
+ * two modes are the WHOLE point (GAP 8): a CC value approximated by the fallback
38
+ * parser is not a Roslyn measurement, and reporting the vehicle's name for it
39
+ * would be a false provenance claim.
40
+ *
41
+ * Lives here, next to `RICH_VEHICLE`, so the vehicle id stays this module's
42
+ * secret — the consumer (src/evidence.ts) learns the NAME from a returned value
43
+ * and never from a literal.
44
+ */
45
+ export declare function provenanceForMode(mode: 'rich' | 'fallback'): MeasurementProvenance;
46
+ /**
47
+ * Probe the .NET SDK once, at first use, and memoise. Mirrors the boolean
48
+ * `command --version` probe at src/providers/runner-detection.ts:95-108, but
49
+ * keeps the version string and the failure reason because the C# provider must
50
+ * REPORT degradation rather than just return false.
51
+ *
52
+ * `spawnSync('dotnet', ['--version'])` — argv only, never `sh -c`.
53
+ * Three failure shapes, all degrading (never throwing): spawn error (ENOENT =
54
+ * binary absent), non-zero exit (SDK present but unusable), timeout.
55
+ */
56
+ export declare function probeDotnetSdk(): DotnetProbe;
57
+ /**
58
+ * Invoke the rich (Roslyn) vehicle for one file.
59
+ *
60
+ * REJECTED-probe contract (plan Task 3 acceptance item 8): when the vehicle is
61
+ * missing, crashes, emits no coverage, or emits output this adapter cannot read,
62
+ * this DELEGATES to the fallback parser and returns a `csharp-analysis-failed`
63
+ * diagnostic. It never returns an empty descriptor list for that reason (that
64
+ * would be a zero-scored phantom PASS) and never throws.
65
+ *
66
+ * HYBRID JOIN (C-6): the vehicle reports CC per method but carries NO spans, so
67
+ * `startLine`/`endLine`/`bodySpan` are taken from the fallback parser for the
68
+ * SAME file and matched on `functionName` + `lineNumber`. A method with no join
69
+ * partner is DROPPED, never given invented spans — an unattributed descriptor
70
+ * would attach coverage to the wrong lines, which is worse than absence. The
71
+ * vehicle's `complexity` is kept on every joined descriptor: that is the value
72
+ * this path exists to provide.
73
+ */
74
+ export declare function runRichSdkAnalysis(filePath: string): Promise<CSharpAnalysis>;
75
+ /**
76
+ * Both modes, one entry point. SDK present → rich path; SDK absent → fallback
77
+ * plus a `csharp-sdk-missing` diagnostic that is returned, never swallowed.
78
+ */
79
+ export declare function analyzeCsharpFile(filePath: string): Promise<CSharpAnalysis>;
80
+ /**
81
+ * The `MethodDescriptor[]` surface attribution consumes, in BOTH modes. Same
82
+ * type, same fields, same order — only `complexity` richness may differ.
83
+ */
84
+ export declare function parseCsharpDescriptors(filePath: string): Promise<MethodDescriptor[]>;