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.
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.1' };
23
+ export const evidenceProvenance = { tool: 'checkchange', version: '0.4.2' };
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' },
@@ -21,7 +21,6 @@ export interface ProviderEntry {
21
21
  export interface ProviderConfig {
22
22
  version: number;
23
23
  providers: ProviderEntry[];
24
- allowlist?: string[];
25
24
  }
26
25
  export interface ResolvedProvider {
27
26
  language: string;
@@ -27,6 +27,29 @@ const PYTEST_RUNNER = {
27
27
  command: ['python3', '-m', 'pytest', '--cov', '--cov-report=xml'],
28
28
  artifact: 'coverage.xml',
29
29
  };
30
+ // Coverlet ships in the `dotnet` SDK; the XPlat collector needs no extra package,
31
+ // hence no `install` (no builtin runner declares one — see PYTEST/JEST/VITEST).
32
+ // binaryProbes must be a COMMAND probe: probeRunner treats a space-free entry as a
33
+ // literal path (`fs.accessSync(path.join(cwd, bp))`, runner-detection.ts:148-156),
34
+ // so a bare `dotnet` could never match. Same shape as PYTEST's `python3 -m pytest`.
35
+ // ponytail: MEASURED (dotnet 9.0.121, coverlet.collector 6.0.4) — the XPlat
36
+ // collector always writes `TestResults/<guid>/coverage.cobertura.xml`. The GUID comes
37
+ // from vstest, not Coverlet, and `--results-directory` pins only the PARENT, so no
38
+ // literal can name it. Runsettings `<Output>` (relative AND absolute) and inline
39
+ // `Output=` are SILENTLY IGNORED — verified: artifact still landed in the GUID dir.
40
+ // Coverlet also exposes no `Output` knob at all (only `ReportFormat`). This `artifact`
41
+ // literal is therefore permanently INERT: no consumer globs. Real discovery works
42
+ // anyway, via two live paths — the TestResults scan in readCoverage (src/coverage.ts)
43
+ // and an explicit `--coverage-file <path>`. Both are measured green on a real repo
44
+ // (auto-detect, no flag, no config change). Do not "fix" this with a glob: globs are
45
+ // inert in every coverage consumer — see Task 4 acceptance item 11.
46
+ const DOTNET_RUNNER = {
47
+ name: 'dotnet',
48
+ configFiles: ['*.csproj', '*.sln'],
49
+ binaryProbes: ['dotnet --version'],
50
+ command: ['dotnet', 'test', '--collect:XPlat Code Coverage'],
51
+ artifact: 'TestResults/coverage.cobertura.xml',
52
+ };
30
53
  export function builtinConfig() {
31
54
  return {
32
55
  version: 1,
@@ -47,11 +70,29 @@ export function builtinConfig() {
47
70
  language: 'python',
48
71
  extensions: PY_EXTENSIONS,
49
72
  coverageFiles: ['.coverage', 'coverage.xml', 'coverage.json', 'coverage/coverage-final.json'],
50
- coverageCmd: 'coverage json -o {out}',
51
73
  testRunners: [PYTEST_RUNNER],
52
74
  },
75
+ {
76
+ language: 'csharp',
77
+ extensions: ['.cs'],
78
+ // ponytail: no complexityCmd — createGenericCommandProvider returns null for
79
+ // an entry without one (genericCommand.ts:35), which is INTENDED: the csharp
80
+ // provider is composed by the registration branch at evidence.ts, not by a
81
+ // shell command. coverageFiles are LITERAL paths (acceptance item 11): both
82
+ // consumers path.join + access() them and silently skip a miss, so a glob
83
+ // entry would be inert.
84
+ // Deliberately EMPTY. A Coverlet artifact lands in a per-run
85
+ // `TestResults/<GUID>/` directory whose name vstest generates; no literal
86
+ // can name it, and the three plausible-looking candidates previously listed
87
+ // here were never observed on disk. Discovery is the automatic TestResults
88
+ // scan in src/coverage.ts (scanCoberturaUnderTestResults) plus an explicit
89
+ // `--coverage-file`. Adding unverifiable paths here would be worse than a
90
+ // recorded gap: an entry that misses is silently skipped, so it buys nothing
91
+ // and misleads the next reader about what was actually tested.
92
+ coverageFiles: [],
93
+ testRunners: [DOTNET_RUNNER],
94
+ },
53
95
  ],
54
- allowlist: ['./checkchange.providers.json', './.checkchange/providers.json'],
55
96
  };
56
97
  }
57
98
  // ---- Config loading ----
@@ -82,6 +123,24 @@ function validateInstallField(install, i, j) {
82
123
  if (!Array.isArray(install.packages))
83
124
  throw new Error(`config: providers[${i}].testRunners[${j}].install.packages must be an array`);
84
125
  }
126
+ // BEHAVIOR CHANGE: providers[].coverageCmd moves from silently-ignored to REJECTED at load.
127
+ // It was declared (ProviderEntry.coverageCmd) and mapped (deriveRegistry) but never executed —
128
+ // nothing in src/ spawns it. Exact error text:
129
+ // config: providers[<i>].coverageCmd not supported (never executed); remove the key
130
+ // Option (a) taken: reject at validateConfig (the schema choke point for both file-based load
131
+ // paths, :166 + :187) and strip builtinConfig's own copy, since the builtin path :189 bypasses
132
+ // validateConfig. deriveRegistry stays a pure mapper. Any present value rejects, including an
133
+ // explicit `coverageCmd: null` — the operator wrote the key, so tell them to delete it rather
134
+ // than silently accept a field the tool ignores.
135
+ // Migration: delete coverageCmd from checkchange.providers.json / .checkchange/providers.json.
136
+ // The same change removed the dead `allowlist` field (zero readers; it duplicated
137
+ // REPO_ROOT_NAMES below). JSON configs carrying it still load unchanged, so no migration.
138
+ // ponytail: own function to match validateTestRunner/validateInstallField above.
139
+ function rejectCoverageCmd(entry, i) {
140
+ if (entry.coverageCmd !== undefined) {
141
+ throw new Error(`config: providers[${i}].coverageCmd not supported (never executed); remove the key`);
142
+ }
143
+ }
85
144
  function validateConfig(raw) {
86
145
  if (!isRecord(raw))
87
146
  throw new Error('config: not an object');
@@ -96,6 +155,7 @@ function validateConfig(raw) {
96
155
  throw new Error(`config: providers[${i}].language missing`);
97
156
  if (!Array.isArray(entry.extensions))
98
157
  throw new Error(`config: providers[${i}].extensions missing`);
158
+ rejectCoverageCmd(entry, i);
99
159
  if (entry.testRunners !== undefined) {
100
160
  if (!Array.isArray(entry.testRunners))
101
161
  throw new Error(`config: providers[${i}].testRunners not an array`);
@@ -98,8 +98,10 @@ export declare function executeInstallPlan(plan: InstallPlan[], options: Prepare
98
98
  * Flush config pins (provider install specs) to disk after a successful install.
99
99
  * Reads the existing config file (JSON.parse if present, else empty {}), merges
100
100
  * pin provider entries by language → testRunner name (updating `install` on match,
101
- * appending otherwise), and writes atomically via tmp file + rename.
102
- * Returns the config-file keys that were written.
101
+ * appending otherwise), and writes atomically via a pid-suffixed tmp file created
102
+ * with O_EXCL + rename, after a realpath containment check against cwd (the sync
103
+ * mirror of the hardened pattern in src/cache.ts writeEntry()). Returns the
104
+ * config-file keys that were written.
103
105
  */
104
106
  export declare function flushConfigUpdates(plan: InstallPlan[], cwd: string): string[];
105
107
  /** Per self-analyzer probe result. */
@@ -119,6 +121,7 @@ export interface VerifyReport {
119
121
  * (a) Node import probe: `@barney-media/crap-typescript-core` resolvable
120
122
  * (b) CLI version probe: `npx --no-install crap-typescript --version` exit 0
121
123
  * (c) Python stdlib probe: venv-aware `python -c "import ast"`
124
+ * (d) .NET SDK probe: `dotnet --version` exit 0
122
125
  * Returns re-detected stack, per-probe status, and aggregate `ok`.
123
126
  */
124
127
  export declare function verifyInstall(stack: DetectedStack, options: PrepareOptions): Promise<VerifyReport>;
@@ -71,6 +71,18 @@ function packageManagerCommand(lockfile, language) {
71
71
  }
72
72
  if (language === 'python')
73
73
  return ['pip', 'install'];
74
+ // csharp returns null ON PURPOSE. `dotnet restore` takes a PROJECT OR SOLUTION,
75
+ // never package names — spreading declared packages onto it is
76
+ // `dotnet restore Crap4DotNet`, which is MSB1009 "Project file does not exist",
77
+ // i.e. an install action that can NEVER succeed. Cycle 1 did exactly that (this
78
+ // branch returned ['dotnet','restore'] and the caller appended the packages).
79
+ // C# packages are .NET GLOBAL TOOLS, so buildInstallPlan emits a per-package
80
+ // `dotnet tool install -g <pkg>` action for each one instead. Returning null here
81
+ // makes MSB1009 unreachable BY CONSTRUCTION: no package id can reach a restore
82
+ // verb, because no restore verb is ever produced for csharp. The Roslyn vehicle
83
+ // id stays a csharpDescriptorProvider secret (SD-2/SD-5).
84
+ if (language === 'csharp')
85
+ return null;
74
86
  return null;
75
87
  }
76
88
  /** Derive a --version probe from the runner's command. */
@@ -117,14 +129,33 @@ export function createInstallPlan(stack, registry, config, cwd) {
117
129
  }
118
130
  // install-lockfile: install packages via lockfile-precedence package manager
119
131
  if (packages.length > 0) {
120
- const pmCmd = packageManagerCommand(lockfile, lang);
121
- if (pmCmd) {
122
- actions.push({
123
- kind: 'install-lockfile',
124
- command: [...pmCmd, ...packages],
125
- packages,
126
- description: `Install ${packages.join(', ')} via ${pmCmd[0]}`,
127
- });
132
+ if (lang === 'csharp') {
133
+ // ONE action PER package: `dotnet tool install -g <pkg>` — the only form
134
+ // that installs a .NET global tool. `-g` matches the remediation the C#
135
+ // descriptor provider prints (csharpDescriptorProvider.ts:219), so
136
+ // `prepare-repo` installs exactly what the fix text tells the user to
137
+ // install. `packageManagerCommand` returns null for csharp, so this branch
138
+ // is the ONLY way a csharp install action is produced — a package id can
139
+ // never be appended to `dotnet restore`.
140
+ for (const pkg of packages) {
141
+ actions.push({
142
+ kind: 'install-lockfile',
143
+ command: ['dotnet', 'tool', 'install', '-g', pkg],
144
+ packages: [pkg],
145
+ description: `Install .NET global tool ${pkg} via dotnet tool install -g`,
146
+ });
147
+ }
148
+ }
149
+ else {
150
+ const pmCmd = packageManagerCommand(lockfile, lang);
151
+ if (pmCmd) {
152
+ actions.push({
153
+ kind: 'install-lockfile',
154
+ command: [...pmCmd, ...packages],
155
+ packages,
156
+ description: `Install ${packages.join(', ')} via ${pmCmd[0]}`,
157
+ });
158
+ }
128
159
  }
129
160
  }
130
161
  // verify-tool: probe tool availability
@@ -244,7 +275,7 @@ const INSTALL_ALLOWLIST = new Set([
244
275
  'create-venv',
245
276
  ]);
246
277
  /** Binaries each allowlisted install kind may spawn, compared by basename. Covers every in-repo
247
- * command producer: packageManagerCommand -> pnpm|yarn|npm|pip, create-venv -> python3,
278
+ * command producer: packageManagerCommand -> pnpm|yarn|npm|pip|dotnet, create-venv -> python3,
248
279
  * install-lockfile spreads that command after its own flags, resolvePipCommand -> venv `python` | python3.
249
280
  *
250
281
  * LIMIT: gates the EXECUTABLE NAME only — never the arguments, never the script that executable
@@ -253,7 +284,7 @@ const INSTALL_ALLOWLIST = new Set([
253
284
  * confinement: a passing allowlist is not proof that the spawned process is sandboxed.
254
285
  */
255
286
  const INSTALL_BINARY_ALLOWLIST = new Map([
256
- ['install-lockfile', new Set(['npm', 'pnpm', 'yarn', 'pip', 'python', 'python3'])],
287
+ ['install-lockfile', new Set(['npm', 'pnpm', 'yarn', 'pip', 'python', 'python3', 'dotnet'])],
257
288
  ['create-venv', new Set(['python', 'python3'])],
258
289
  ]);
259
290
  const INSTALL_TIMEOUT_MS = 60_000;
@@ -330,12 +361,45 @@ export async function executeInstallPlan(plan, options) {
330
361
  ok: !actions.some((r) => r.status === 'failed'),
331
362
  };
332
363
  }
364
+ /**
365
+ * Containment guard, sync mirror of cache.ts isWithin(): the candidate must
366
+ * realpath inside root. Best-effort, not a proof — the realpath arm and the
367
+ * write that follows are separate operations, so a swap between them is not
368
+ * covered. The lexical fallback is what keeps the check usable BEFORE the
369
+ * config file exists (first flush into a fresh repo).
370
+ */
371
+ function resolvesWithin(candidate, root) {
372
+ let realCandidate = candidate;
373
+ let realRoot = root;
374
+ try {
375
+ realCandidate = fs.realpathSync(candidate);
376
+ realRoot = fs.realpathSync(root);
377
+ }
378
+ catch {
379
+ // one of the two does not resolve yet — fall back to the lexical check
380
+ }
381
+ const rel = path.relative(realRoot, realCandidate);
382
+ return !rel.startsWith('..') && !path.isAbsolute(rel);
383
+ }
384
+ /** Unlink that never throws. unlink does not follow symlinks, so this frees a
385
+ * tmp slot without ever touching a link target. A stale tmp costs one skipped
386
+ * write, never a crash. */
387
+ function unlinkQuiet(p) {
388
+ try {
389
+ fs.unlinkSync(p);
390
+ }
391
+ catch {
392
+ // best effort
393
+ }
394
+ }
333
395
  /**
334
396
  * Flush config pins (provider install specs) to disk after a successful install.
335
397
  * Reads the existing config file (JSON.parse if present, else empty {}), merges
336
398
  * pin provider entries by language → testRunner name (updating `install` on match,
337
- * appending otherwise), and writes atomically via tmp file + rename.
338
- * Returns the config-file keys that were written.
399
+ * appending otherwise), and writes atomically via a pid-suffixed tmp file created
400
+ * with O_EXCL + rename, after a realpath containment check against cwd (the sync
401
+ * mirror of the hardened pattern in src/cache.ts writeEntry()). Returns the
402
+ * config-file keys that were written.
339
403
  */
340
404
  export function flushConfigUpdates(plan, cwd) {
341
405
  const written = new Set();
@@ -350,6 +414,10 @@ export function flushConfigUpdates(plan, cwd) {
350
414
  if (!pinProviders?.length)
351
415
  continue;
352
416
  const configPath = path.resolve(cwd, configKey);
417
+ // Containment BEFORE any I/O: a symlink holding configPath (or a swapped
418
+ // cwd) would otherwise be read through and then clobbered by the rename.
419
+ if (!resolvesWithin(configPath, cwd))
420
+ continue;
353
421
  let existing;
354
422
  try {
355
423
  existing = JSON.parse(fs.readFileSync(configPath, 'utf8'));
@@ -381,9 +449,31 @@ export function flushConfigUpdates(plan, cwd) {
381
449
  existingProviders.push(pinProvider);
382
450
  }
383
451
  }
384
- const tmpPath = `${configPath}.tmp`;
385
- fs.writeFileSync(tmpPath, JSON.stringify(existing, null, 2));
386
- fs.renameSync(tmpPath, configPath);
452
+ // Atomic write. The tmp name is pid-suffixed so concurrent flushes do not
453
+ // share a slot, and `flag: 'wx'` (O_EXCL) makes the create fail EEXIST
454
+ // rather than write THROUGH anything already holding that name — a planted
455
+ // symlink's target is therefore never modified. On any failure the name is
456
+ // unlinked so a later flush retries on a clean slot, the key is left out of
457
+ // `written`, and a console.warn names the failure — an absent JSON entry alone
458
+ // was not enough, since the human path prints nothing about the config write.
459
+ const tmpPath = `${configPath}.tmp.${process.pid}`;
460
+ try {
461
+ fs.writeFileSync(tmpPath, JSON.stringify(existing, null, 2), { flag: 'wx' });
462
+ // Re-check both endpoints after the write, before the rename overwrites.
463
+ if (!resolvesWithin(tmpPath, cwd) || !resolvesWithin(configPath, cwd)) {
464
+ unlinkQuiet(tmpPath);
465
+ continue;
466
+ }
467
+ fs.renameSync(tmpPath, configPath);
468
+ }
469
+ catch (err) {
470
+ unlinkQuiet(tmpPath);
471
+ // Never silent: the caller derives its exit code from install.ok alone,
472
+ // so a swallowed failure here would leave the operator believing the
473
+ // provider pin was recorded when it was not.
474
+ console.warn(`prepare-repo: could not write ${configKey} via ${tmpPath}: ${err instanceof Error ? err.message : String(err)}`);
475
+ continue;
476
+ }
387
477
  written.add(configKey);
388
478
  }
389
479
  }
@@ -405,6 +495,7 @@ function resolvePython(cwd) {
405
495
  * (a) Node import probe: `@barney-media/crap-typescript-core` resolvable
406
496
  * (b) CLI version probe: `npx --no-install crap-typescript --version` exit 0
407
497
  * (c) Python stdlib probe: venv-aware `python -c "import ast"`
498
+ * (d) .NET SDK probe: `dotnet --version` exit 0
408
499
  * Returns re-detected stack, per-probe status, and aggregate `ok`.
409
500
  */
410
501
  export async function verifyInstall(stack, options) {
@@ -451,6 +542,23 @@ export async function verifyInstall(stack, options) {
451
542
  : `${pyBin} not found; create .venv via "python3 -m venv .venv" and re-run`;
452
543
  analyzers.push({ name: 'python-stdlib-ast', status: 'unfixable', detail: guidance });
453
544
  }
545
+ // (d) .NET SDK probe — `dotnet --version` exit 0. LANGUAGE-UNGUARDED, matching
546
+ // (a)/(b)/(c): all four run for every repo. Plan Task 7 item 8 forbids a language gate
547
+ // here — it would diverge from the sibling probes. Consequence, recorded in the task
548
+ // report: `ok` now depends on the .NET SDK being on PATH, exactly as it already
549
+ // depends on python3 for probe (c).
550
+ try {
551
+ const { stdout } = await execFileAsync('dotnet', ['--version'], { cwd, timeout: INSTALL_TIMEOUT_MS });
552
+ const line = stdout.split('\n')[0]?.trim() ?? '';
553
+ analyzers.push({ name: 'dotnet-sdk', status: 'ok', detail: `exit 0: ${line}` });
554
+ }
555
+ catch {
556
+ analyzers.push({
557
+ name: 'dotnet-sdk',
558
+ status: 'unfixable',
559
+ detail: 'dotnet not found on PATH; install the .NET SDK from https://dotnet.microsoft.com/download and re-run prepare-repo',
560
+ });
561
+ }
454
562
  return {
455
563
  reDetected,
456
564
  analyzers,
package/dist/rules.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ChangedFunction } from './evidence.js';
2
2
  export declare const rulesProvenance: {
3
3
  readonly tool: "checkchange";
4
- readonly version: "0.4.1";
4
+ readonly version: "0.4.2";
5
5
  };
6
6
  export interface RuleResult {
7
7
  ruleId: string;
package/dist/rules.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // Provenance for the rules lineage stage. Self tool version tracks package.json.
2
- export const rulesProvenance = { tool: 'checkchange', version: '0.4.1' };
2
+ export const rulesProvenance = { tool: 'checkchange', version: '0.4.2' };
3
3
  /**
4
4
  * Evaluate changed functions against the high-CRAP rule.
5
5
  * @param changed Array of changed functions
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "checkchange",
3
- "version": "0.4.1",
3
+ "version": "0.4.3",
4
4
  "license": "MIT",
5
5
  "packageManager": "pnpm@11.17.0",
6
6
  "type": "module",
7
7
  "bin": {
8
- "checkchange": "./dist/cli.js",
9
- "code-risk": "./dist/cli.js"
8
+ "checkchange": "dist/cli.js",
9
+ "code-risk": "dist/cli.js"
10
10
  },
11
11
  "files": [
12
12
  "dist/",