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,397 @@
1
+ /**
2
+ * C# `MethodDescriptor` provider — BOTH modes, ONE shape.
3
+ *
4
+ * Dispatches on a single `dotnet --version` probe: SDK present → rich path
5
+ * (Roslyn vehicle), SDK absent → the pure-TS fallback parser
6
+ * (./csharpFallbackParser.ts). Both modes return the SAME `MethodDescriptor`
7
+ * type — it is re-exported from the fallback parser rather than redeclared, so
8
+ * "identical shape" (plan Task 3 acceptance item 7) is guaranteed by the module
9
+ * graph, not merely asserted by a test.
10
+ *
11
+ * WHY THE PROBE LIVES HERE AND NOT IN csharpComplexityProvider.ts: the plan's
12
+ * Task 3 seam REJECTED putting the probe inside collectComplexity, because the
13
+ * probe result is needed by BOTH this descriptor provider and the diagnostic
14
+ * surface. Placing it in the leaf that consumes it keeps the dependency
15
+ * one-directional — csharpComplexityProvider → this module — with no cycle.
16
+ *
17
+ * SECURITY POSTURE: every spawn is argv-only. There is no `sh -c`, no shell
18
+ * string, no interpolation of caller data into a command line. Mirrors
19
+ * commandProbeAvailable() at src/providers/runner-detection.ts:95-108.
20
+ *
21
+ * RICH PATH IS NOT A HARD REQUIREMENT. The vehicle is resolved at runtime and
22
+ * its availability is NOT assumed: it is still probed per file, and any failure
23
+ * — absent binary, no coverage artifact, unparseable payload, no span join —
24
+ * degrades to the fallback parser with a `csharp-analysis-failed` diagnostic.
25
+ * That is a documented, accepted outcome, not a silent one: the run still
26
+ * returns real CC values, and the degradation is reported through `diagnostic`
27
+ * and through `csharpComplexityProvider.describe()`. Cycle 1 REJECTED the
28
+ * vehicle on this machine only because the spawn form was dotnet-as-mux, which
29
+ * is measured to never work; the form and payload are now validated against a
30
+ * real Crap4DotNet 0.1.1 run (see RICH_VEHICLE below and
31
+ * .opencode/validation/csharp-rich-vehicle-decision.md).
32
+ */
33
+ import { spawnSync } from 'node:child_process';
34
+ import { existsSync, realpathSync } from 'node:fs';
35
+ import { homedir } from 'node:os';
36
+ import { dirname, join, resolve } from 'node:path';
37
+ import { parseCsharpFileMethods } from './csharpFallbackParser.js';
38
+ import { scanCoberturaUnderTestResults } from '../coverage.js';
39
+ // SD-4 / GAP 10: ONE knob for every provider subprocess. Reusing the existing
40
+ // env var (providers/genericCommand.ts:56) rather than adding a
41
+ // CHECKCHANGE_CSHARP_* twin — a second var for the same knob is duplication.
42
+ const PROBE_VERSION_TIMEOUT_MS = Number(process.env.CHECKCHANGE_PROVIDER_TIMEOUT_MS) || 10_000;
43
+ // Roslyn vehicle. NOT A DEPENDENCY and NOT A HARD REQUIREMENT: it is resolved at
44
+ // runtime and any failure degrades to the fallback parser with a diagnostic.
45
+ //
46
+ // SD-4: the command is `dotnet-crap` but the NuGet PACKAGE id is `Crap4DotNet`
47
+ // 0.1.1 — `dotnet tool install` takes the package id. Cycle 1 conflated the two,
48
+ // so the fix text told a human to install a package that does not exist. The
49
+ // version pin is `--version 0.1.1`: the `@0.1.1` shorthand is measured to fail
50
+ // with "not found in NuGet feeds" on this SDK.
51
+ //
52
+ // MEASURED, not assumed (.opencode/validation/csharp-rich-vehicle-decision.md, a
53
+ // real installed Crap4DotNet 0.1.1). Five facts this adapter is built on:
54
+ //
55
+ // 1. SPAWN FORM: the direct executable with the `analyze` subcommand is the ONLY
56
+ // form that works. `dotnet dotnet-crap …` exits 1 ("dotnet-dotnet-crap does
57
+ // not exist") and `dotnet crap4dotnet …` exits 1. The old argv here was
58
+ // dotnet-as-mux — a form measured NEVER to work.
59
+ // 2. BINARY RESOLUTION (C-1): `dotnet tool install -g` puts the shim in
60
+ // `~/.dotnet/tools`, which is NOT on PATH here (the shell PATH holds a
61
+ // literal, unexpanded `~` entry), so a bare-name spawn ENOENTs on a machine
62
+ // where the tool is installed and working. Resolve the shim by absolute
63
+ // path, fall back to the bare name for a PATH-installed copy. No shell
64
+ // profile is touched.
65
+ // 3. COVERAGE IS MANDATORY (C-2): without `--coverage` (or `--run-tests`) the
66
+ // tool exits 2 with `{error:{code:"COVERAGE_FILE_NOT_FOUND"}}` and emits no
67
+ // methods at all, so the rich path can never fire. The artifact is located
68
+ // with the SAME Coverlet locator coverage.ts already owns rather than a
69
+ // second, differently-behaving scan.
70
+ // 4. PAYLOAD IS AN OBJECT (C-5): the real JSON is
71
+ // `{schemaVersion,project,timestamp,threshold,stats,methods,histogram,hierarchy,
72
+ // warnings}` — the descriptors live at `payload.methods`. The old
73
+ // `Array.isArray(payload)` guard therefore rejected EVERY valid payload.
74
+ // 5. EXIT 0 IS NOT SUCCESS (C-7): an unrecognised flag or a missing subcommand
75
+ // exits 0 printing help text. Success is decided by the payload SHAPE, never
76
+ // by the exit status.
77
+ //
78
+ // C-4: `filePath` is ABSOLUTE for a single-file target and ROOT-RELATIVE
79
+ // (`./Calculator.cs`) for a directory target, so it is resolved against the
80
+ // analysed file's directory before the join — otherwise a directory-target run
81
+ // silently misses every method.
82
+ const RICH_VEHICLE = 'dotnet-crap';
83
+ const RICH_VEHICLE_PACKAGE = 'Crap4DotNet';
84
+ // spawnSync's overload widens stdout/stderr to `string | Buffer` even under
85
+ // encoding:'utf8'. This adapter only ever reads text.
86
+ function text(value) {
87
+ return typeof value === 'string' ? value : value == null ? '' : String(value);
88
+ }
89
+ // spawnSync reports a missing binary on `result.error` (ENOENT); it does NOT
90
+ // throw for that. It can only throw on an invalid argument list, which cannot
91
+ // happen here — every argv is a non-empty literal plus a file path. So neither
92
+ // call site needs a try/catch, and neither can throw at all.
93
+ function errorCode(value) {
94
+ const e = value;
95
+ return e?.code ?? e?.message ?? 'unknown error';
96
+ }
97
+ // ponytail: structural check of exactly the fields the adapter READS, not a full
98
+ // deserialiser. `crap`/`coverage`/`crapLoad`/`severity` are intentionally unread —
99
+ // their numeric semantics are UNVERIFIED (decision record §6), so no arithmetic
100
+ // depends on them.
101
+ function isVehicleMethod(value) {
102
+ if (!value || typeof value !== 'object')
103
+ return false;
104
+ const m = value;
105
+ return (typeof m.methodName === 'string' &&
106
+ typeof m.className === 'string' &&
107
+ typeof m.fullName === 'string' &&
108
+ typeof m.filePath === 'string' &&
109
+ typeof m.lineNumber === 'number' &&
110
+ typeof m.complexity === 'number');
111
+ }
112
+ /**
113
+ * The vehicle shim, by absolute path when `dotnet tool install -g` put it where
114
+ * this repo knows it lands (C-1), else the bare name for a PATH-installed copy.
115
+ * Never modifies PATH or any shell profile.
116
+ */
117
+ export function vehicleCommand() {
118
+ const shim = join(homedir(), '.dotnet', 'tools', RICH_VEHICLE);
119
+ return existsSync(shim) ? shim : RICH_VEHICLE;
120
+ }
121
+ /**
122
+ * Locate the Cobertura artifact the vehicle needs (C-2). Reuses
123
+ * coverage.ts's `scanCoberturaUnderTestResults` — the same locator the coverage
124
+ * stage uses — plus the two conventional in-tree names, so a repo that commits
125
+ * its artifact is not forced to mint a `TestResults/<GUID>/` tree. Returns null
126
+ * when there is none, which the caller turns into a `csharp-analysis-failed`
127
+ * diagnostic naming the reason (never a silent empty result).
128
+ */
129
+ function findCobertura(root) {
130
+ for (const name of ['coverage.cobertura.xml', 'coverage.xml']) {
131
+ const candidate = join(root, name);
132
+ if (existsSync(candidate))
133
+ return candidate;
134
+ }
135
+ return scanCoberturaUnderTestResults(root);
136
+ }
137
+ /**
138
+ * Canonical form of a path for the join comparison. `resolve()` normalises
139
+ * `..` and relative segments but does NOT resolve symlinks, and the two sides
140
+ * of the join come from different producers: the caller passes the path it was
141
+ * given, the vehicle echoes the realpath it walked. On macOS
142
+ * `/tmp/x/Calculator.cs` and `/private/tmp/x/Calculator.cs` are the same file,
143
+ * so the raw compare never matches and every method drops — measured, not
144
+ * hypothetical. Best-effort by design: a path that no longer exists (raced
145
+ * delete) falls back to its resolved form rather than throwing, so a missing
146
+ * file still fails the compare instead of crashing the run.
147
+ */
148
+ function canonical(p) {
149
+ const resolved = resolve(p);
150
+ try {
151
+ return realpathSync(resolved);
152
+ }
153
+ catch {
154
+ return resolved;
155
+ }
156
+ }
157
+ // ponytail: cached FOR the process lifetime, deliberately — there is no
158
+ // `resetDotnetProbe()`. That matches the one-shot `command --version` probe at
159
+ // src/providers/runner-detection.ts:95-108. A CLI check run is short-lived, and
160
+ // a long-lived host that must re-detect an SDK installed mid-process would
161
+ // export a reset; nothing in this repo does, so exporting one is dead weight.
162
+ let cachedProbe = null;
163
+ // The VEHICLE outcome, plumbed rather than re-probed: `degrade()` below records
164
+ // every rejection and the rich path clears it. `csharpComplexityProvider`
165
+ // destructures only `{ descriptors }` — ProviderFactory (src/evidence.ts:252-255)
166
+ // has no diagnostic channel — so without this slot a REJECTED vehicle would leave
167
+ // `describe()` claiming a healthy SDK while every file measured with the fallback.
168
+ let lastVehicleRejection = null;
169
+ /**
170
+ * The most recent vehicle rejection observed in this process, else null. NEVER a
171
+ * probe result: SDK-missing lives on `probeDotnetSdk().diagnostic`.
172
+ */
173
+ export function vehicleRejection() {
174
+ return lastVehicleRejection;
175
+ }
176
+ // The fallback parser is checkchange's OWN code (./csharpFallbackParser.ts), so
177
+ // its tool is checkchange and its version is the package version — same 0.4.2
178
+ // the other self-provenance consts hard-code (src/crapCalc.ts:3, src/rules.ts:4).
179
+ const FALLBACK_TOOL = 'checkchange';
180
+ const FALLBACK_TOOL_VERSION = '0.4.2';
181
+ // The vehicle's INSTALLED version is never probed: the rich path is
182
+ // documented-unreachable (see SPAWN FORM above), so `dotnet-crap --version` is
183
+ // never spawned to learn it, and no version is fabricated here. `unknown` is the
184
+ // honest report and satisfies the non-empty-version invariant every lineage
185
+ // provenance must meet (test/lineage.test.ts:43).
186
+ const VEHICLE_VERSION = 'unknown';
187
+ /**
188
+ * Which tool measured a file, per the mode `analyzeCsharpFile` returned. The
189
+ * two modes are the WHOLE point (GAP 8): a CC value approximated by the fallback
190
+ * parser is not a Roslyn measurement, and reporting the vehicle's name for it
191
+ * would be a false provenance claim.
192
+ *
193
+ * Lives here, next to `RICH_VEHICLE`, so the vehicle id stays this module's
194
+ * secret — the consumer (src/evidence.ts) learns the NAME from a returned value
195
+ * and never from a literal.
196
+ */
197
+ export function provenanceForMode(mode) {
198
+ return mode === 'rich'
199
+ ? { tool: RICH_VEHICLE, version: VEHICLE_VERSION, mode: 'NATIVE' }
200
+ : { tool: FALLBACK_TOOL, version: FALLBACK_TOOL_VERSION, mode: 'FALLBACK' };
201
+ }
202
+ /**
203
+ * Probe the .NET SDK once, at first use, and memoise. Mirrors the boolean
204
+ * `command --version` probe at src/providers/runner-detection.ts:95-108, but
205
+ * keeps the version string and the failure reason because the C# provider must
206
+ * REPORT degradation rather than just return false.
207
+ *
208
+ * `spawnSync('dotnet', ['--version'])` — argv only, never `sh -c`.
209
+ * Three failure shapes, all degrading (never throwing): spawn error (ENOENT =
210
+ * binary absent), non-zero exit (SDK present but unusable), timeout.
211
+ */
212
+ export function probeDotnetSdk() {
213
+ if (cachedProbe)
214
+ return cachedProbe;
215
+ const argv = ['--version'];
216
+ const command = `dotnet ${argv.join(' ')}`;
217
+ const res = spawnSync('dotnet', argv, { encoding: 'utf8', timeout: PROBE_VERSION_TIMEOUT_MS });
218
+ if (res.error) {
219
+ cachedProbe = {
220
+ available: false,
221
+ version: null,
222
+ diagnostic: {
223
+ code: 'csharp-sdk-missing',
224
+ message: 'The .NET SDK is not usable, so C# complexity is measured with the pure-TypeScript fallback parser: ' +
225
+ 'approximated cyclomatic complexity over comment/string-stripped source, not a Roslyn AST. ' +
226
+ 'Generic, expression-bodied and local-function members are missed (see csharpFallbackParser.ts).',
227
+ fix: 'Install the .NET SDK so the `dotnet` CLI is on PATH: https://dotnet.microsoft.com/download',
228
+ detail: `${command}: spawn failed (${errorCode(res.error)})`,
229
+ },
230
+ };
231
+ return cachedProbe;
232
+ }
233
+ if (res.status !== 0) {
234
+ const stderr = text(res.stderr).trim().slice(0, 200);
235
+ cachedProbe = {
236
+ available: false,
237
+ version: null,
238
+ diagnostic: {
239
+ code: 'csharp-sdk-missing',
240
+ message: '`dotnet --version` exited non-zero, so the .NET SDK cannot be used and C# complexity falls back to ' +
241
+ 'the pure-TypeScript approximation rather than a Roslyn AST.',
242
+ fix: 'Repair or reinstall the .NET SDK so `dotnet --version` exits 0: https://dotnet.microsoft.com/download',
243
+ detail: `${command}: exit code ${res.status}${stderr ? `, stderr ${JSON.stringify(stderr)}` : ''}`,
244
+ },
245
+ };
246
+ return cachedProbe;
247
+ }
248
+ cachedProbe = { available: true, version: text(res.stdout).trim(), diagnostic: null };
249
+ return cachedProbe;
250
+ }
251
+ /**
252
+ * Invoke the rich (Roslyn) vehicle for one file.
253
+ *
254
+ * REJECTED-probe contract (plan Task 3 acceptance item 8): when the vehicle is
255
+ * missing, crashes, emits no coverage, or emits output this adapter cannot read,
256
+ * this DELEGATES to the fallback parser and returns a `csharp-analysis-failed`
257
+ * diagnostic. It never returns an empty descriptor list for that reason (that
258
+ * would be a zero-scored phantom PASS) and never throws.
259
+ *
260
+ * HYBRID JOIN (C-6): the vehicle reports CC per method but carries NO spans, so
261
+ * `startLine`/`endLine`/`bodySpan` are taken from the fallback parser for the
262
+ * SAME file and matched on `functionName` + `lineNumber`. A method with no join
263
+ * partner is DROPPED, never given invented spans — an unattributed descriptor
264
+ * would attach coverage to the wrong lines, which is worse than absence. The
265
+ * vehicle's `complexity` is kept on every joined descriptor: that is the value
266
+ * this path exists to provide.
267
+ */
268
+ export async function runRichSdkAnalysis(filePath) {
269
+ const command = vehicleCommand();
270
+ const root = dirname(resolve(filePath));
271
+ const argv = ['analyze', filePath];
272
+ const shown = `${command} ${argv.join(' ')}`;
273
+ const degrade = async (detail) => {
274
+ const diagnostic = {
275
+ code: 'csharp-analysis-failed',
276
+ message: 'The .NET SDK is present but the Roslyn complexity vehicle could not be used, so this file was measured ' +
277
+ 'with the pure-TypeScript fallback parser instead. CC values are real but approximate.',
278
+ fix: `Install the package — \`dotnet tool install -g ${RICH_VEHICLE_PACKAGE}\` (that is the NuGet package id; the ` +
279
+ `command it installs is \`${RICH_VEHICLE}\`, which normally lands in ~/.dotnet/tools and may NOT be on PATH). ` +
280
+ `It is invoked as \`${RICH_VEHICLE} analyze <file> --coverage <cobertura.xml>\` and REQUIRES a Cobertura ` +
281
+ 'artifact: without one it exits 2 with COVERAGE_FILE_NOT_FOUND and reports no methods. If it still fails, ' +
282
+ 'the documented pure-TypeScript approximation is the expected outcome, not a regression.',
283
+ detail,
284
+ };
285
+ lastVehicleRejection = diagnostic;
286
+ return { descriptors: await parseCsharpFileMethods(filePath), diagnostic, mode: 'fallback' };
287
+ };
288
+ // C-2: coverage is mandatory. The vehicle exits 2 with no methods at all
289
+ // without it, so check FIRST and name the missing artifact in the diagnostic
290
+ // rather than surfacing the tool's generic exit code.
291
+ const coverage = findCobertura(root);
292
+ if (coverage === null) {
293
+ return degrade(`${shown}: no Cobertura coverage artifact found under ${root} — the vehicle requires one ` +
294
+ '(looked for coverage.cobertura.xml, coverage.xml, and TestResults/<run>/coverage.cobertura.xml)');
295
+ }
296
+ const res = spawnSync(command, [...argv, '--coverage', coverage], {
297
+ encoding: 'utf8',
298
+ timeout: PROBE_VERSION_TIMEOUT_MS,
299
+ });
300
+ if (res.error)
301
+ return degrade(`${shown} --coverage ${coverage}: spawn failed (${errorCode(res.error)})`);
302
+ // C-7: the exit status is NOT the success signal — a bad flag or a missing
303
+ // subcommand exits 0 with help text on stdout. Parse first, judge by shape.
304
+ let payload;
305
+ try {
306
+ payload = JSON.parse(text(res.stdout));
307
+ }
308
+ catch {
309
+ return degrade(`${shown} --coverage ${coverage}: exit code ${res.status} but stdout is not JSON — output unparseable`);
310
+ }
311
+ // C-5: the real payload is an OBJECT with descriptors at `methods`, not an
312
+ // array. Both the error object and the valid document are objects, so the
313
+ // `methods` array is the discriminator.
314
+ const methods = payload?.methods;
315
+ if (!Array.isArray(methods)) {
316
+ const code = payload?.error?.code;
317
+ return degrade(`${shown} --coverage ${coverage}: exit code ${res.status} but stdout carries no ` +
318
+ `\`methods\` array${code ? ` — the vehicle reported ${code}` : ''}`);
319
+ }
320
+ // Elements are validated too, not just the array: a `[null]` entry would
321
+ // otherwise be cast, then throw inside the join — a silently SKIPPED file,
322
+ // the exact silent-empty outcome this diagnostic exists to prevent.
323
+ if (!methods.every(isVehicleMethod)) {
324
+ return degrade(`${shown} --coverage ${coverage}: exit code ${res.status} but the methods array holds malformed records`);
325
+ }
326
+ // ponytail: ONE fallback parse for the whole file, indexed for the join. Spans
327
+ // are the fallback parser's real output, not derived from `lineNumber`.
328
+ const spans = new Map();
329
+ for (const d of await parseCsharpFileMethods(filePath))
330
+ spans.set(`${d.functionName}:${d.startLine}`, d);
331
+ const descriptors = [];
332
+ let unmatched = 0;
333
+ for (const m of methods) {
334
+ // C-4: the payload's filePath is absolute for a single-file target and
335
+ // root-relative for a directory target; resolve both against the analysed
336
+ // file so a directory-target run still joins. `canonical` also collapses
337
+ // symlinks, so a caller-supplied /tmp/... joins a vehicle-reported
338
+ // /private/tmp/... instead of dropping every method.
339
+ if (canonical(resolve(root, m.filePath)) !== canonical(filePath)) {
340
+ unmatched++;
341
+ continue;
342
+ }
343
+ const span = spans.get(`${m.methodName}:${m.lineNumber}`);
344
+ if (span === undefined) {
345
+ unmatched++;
346
+ continue;
347
+ }
348
+ descriptors.push({
349
+ ...span,
350
+ // The vehicle's `fullName` carries the signature (`Ns.Type.Name(int)`),
351
+ // which is not the descriptor `displayName` convention
352
+ // (`Container.Name`) that attribution keys on at src/attribution.ts:155.
353
+ // Keep the fallback's displayName and take only the vehicle's CC.
354
+ complexity: m.complexity,
355
+ });
356
+ }
357
+ if (descriptors.length === 0) {
358
+ return degrade(`${shown} --coverage ${coverage}: exit code ${res.status} and ${methods.length} method(s) reported, ` +
359
+ 'but none joined to a fallback span (file+line+name) — no descriptor was invented from `lineNumber` alone');
360
+ }
361
+ if (unmatched > 0) {
362
+ // Not a degradation: the joined methods are real measurements. The count is
363
+ // carried in the diagnostic so a shrinking join is visible, never silent.
364
+ lastVehicleRejection = {
365
+ code: 'csharp-analysis-failed',
366
+ message: `The Roslyn vehicle reported ${methods.length} method(s) but only ${descriptors.length} joined to a ` +
367
+ 'fallback line span; the rest were dropped rather than given invented spans, so this file is measured ' +
368
+ 'partially. Spans come from the pure-TypeScript fallback parser; CC comes from the vehicle.',
369
+ fix: 'Check that the vehicle and this adapter agree on declaration lines. The join is `functionName` + ' +
370
+ '`lineNumber` against the fallback parser; a Roslyn-only construct (expression-bodied, generic, or a ' +
371
+ 'local function) has no fallback partner and is dropped by design.',
372
+ detail: `${shown} --coverage ${coverage}: ${unmatched} of ${methods.length} method(s) unmatched`,
373
+ };
374
+ }
375
+ else {
376
+ lastVehicleRejection = null;
377
+ }
378
+ return { descriptors, mode: 'rich', diagnostic: lastVehicleRejection };
379
+ }
380
+ /**
381
+ * Both modes, one entry point. SDK present → rich path; SDK absent → fallback
382
+ * plus a `csharp-sdk-missing` diagnostic that is returned, never swallowed.
383
+ */
384
+ export async function analyzeCsharpFile(filePath) {
385
+ const probe = probeDotnetSdk();
386
+ if (!probe.available) {
387
+ return { descriptors: await parseCsharpFileMethods(filePath), mode: 'fallback', diagnostic: probe.diagnostic };
388
+ }
389
+ return runRichSdkAnalysis(filePath);
390
+ }
391
+ /**
392
+ * The `MethodDescriptor[]` surface attribution consumes, in BOTH modes. Same
393
+ * type, same fields, same order — only `complexity` richness may differ.
394
+ */
395
+ export async function parseCsharpDescriptors(filePath) {
396
+ return (await analyzeCsharpFile(filePath)).descriptors;
397
+ }
@@ -0,0 +1,17 @@
1
+ export interface MethodDescriptor {
2
+ functionName: string;
3
+ containerName: string | null;
4
+ displayName: string;
5
+ startLine: number;
6
+ endLine: number;
7
+ complexity: number;
8
+ bodySpan: {
9
+ startLine: number;
10
+ startColumn: number;
11
+ endLine: number;
12
+ endColumn: number;
13
+ };
14
+ expectsStatementCoverage: boolean;
15
+ expectsBranchCoverage: boolean;
16
+ }
17
+ export declare function parseCsharpFileMethods(filePath: string): Promise<MethodDescriptor[]>;