checkchange 0.4.0

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.
Files changed (61) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -0
  3. package/dist/attribution.d.ts +19 -0
  4. package/dist/attribution.js +175 -0
  5. package/dist/auto-coverage.d.ts +8 -0
  6. package/dist/auto-coverage.js +93 -0
  7. package/dist/cache.d.ts +70 -0
  8. package/dist/cache.js +458 -0
  9. package/dist/cli.d.ts +51 -0
  10. package/dist/cli.js +810 -0
  11. package/dist/complexity-providers/pythonASTComplexityProvider.d.ts +9 -0
  12. package/dist/complexity-providers/pythonASTComplexityProvider.js +148 -0
  13. package/dist/complexity-providers/pythonDescriptorProvider.d.ts +17 -0
  14. package/dist/complexity-providers/pythonDescriptorProvider.js +119 -0
  15. package/dist/complexity-providers.d.ts +6 -0
  16. package/dist/complexity-providers.js +1 -0
  17. package/dist/complexity.d.ts +14 -0
  18. package/dist/complexity.js +75 -0
  19. package/dist/coverage-providers/lcovProvider.d.ts +12 -0
  20. package/dist/coverage-providers/lcovProvider.js +126 -0
  21. package/dist/coverage.d.ts +28 -0
  22. package/dist/coverage.js +451 -0
  23. package/dist/crap.d.ts +31 -0
  24. package/dist/crap.js +84 -0
  25. package/dist/crapCalc.d.ts +5 -0
  26. package/dist/crapCalc.js +11 -0
  27. package/dist/delta.d.ts +100 -0
  28. package/dist/delta.js +214 -0
  29. package/dist/evidence.d.ts +201 -0
  30. package/dist/evidence.js +906 -0
  31. package/dist/execute.d.ts +59 -0
  32. package/dist/execute.js +92 -0
  33. package/dist/formatters/github.d.ts +5 -0
  34. package/dist/formatters/github.js +27 -0
  35. package/dist/formatters/index.d.ts +47 -0
  36. package/dist/formatters/index.js +14 -0
  37. package/dist/formatters/junit.d.ts +5 -0
  38. package/dist/formatters/junit.js +32 -0
  39. package/dist/formatters/sarif.d.ts +5 -0
  40. package/dist/formatters/sarif.js +35 -0
  41. package/dist/fs-safety.d.ts +10 -0
  42. package/dist/fs-safety.js +47 -0
  43. package/dist/git.d.ts +50 -0
  44. package/dist/git.js +137 -0
  45. package/dist/help.d.ts +40 -0
  46. package/dist/help.js +274 -0
  47. package/dist/index.d.ts +6 -0
  48. package/dist/index.js +4 -0
  49. package/dist/providers/config.d.ts +41 -0
  50. package/dist/providers/config.js +172 -0
  51. package/dist/providers/genericCommand.d.ts +3 -0
  52. package/dist/providers/genericCommand.js +89 -0
  53. package/dist/providers/index.d.ts +7 -0
  54. package/dist/providers/index.js +4 -0
  55. package/dist/providers/prepare.d.ts +124 -0
  56. package/dist/providers/prepare.js +459 -0
  57. package/dist/providers/runner-detection.d.ts +30 -0
  58. package/dist/providers/runner-detection.js +207 -0
  59. package/dist/rules.d.ts +27 -0
  60. package/dist/rules.js +54 -0
  61. package/package.json +52 -0
@@ -0,0 +1,124 @@
1
+ import type { ProviderConfig, ResolvedProvider } from './config.js';
2
+ import { type ResolvedRunner } from './runner-detection.js';
3
+ /** Options shared across prepare phases. */
4
+ export interface PrepareOptions {
5
+ cwd: string;
6
+ dryRun: boolean;
7
+ json: boolean;
8
+ yes: boolean;
9
+ }
10
+ /**
11
+ * Phase 1 result: detected languages, resolved runners per language,
12
+ * and lockfiles found per language (spec lines 58-62).
13
+ */
14
+ export interface DetectedStack {
15
+ languages: string[];
16
+ runners: Map<string, ResolvedRunner>;
17
+ lockfiles: Map<string, string | null>;
18
+ }
19
+ /** An ordered action a single install phase can execute. */
20
+ export type InstallActionKind = 'install' | 'create-venv' | 'install-lockfile' | 'verify-tool';
21
+ export interface InstallAction {
22
+ kind: InstallActionKind;
23
+ command?: string[];
24
+ packages?: string[];
25
+ description: string;
26
+ }
27
+ /**
28
+ * Phase 2 result: per-language plan with ordered actions and
29
+ * config file updates to flush (spec lines 63-71).
30
+ */
31
+ export interface InstallPlan {
32
+ language: string;
33
+ actions: InstallAction[];
34
+ configUpdates: Record<string, unknown>;
35
+ }
36
+ /** Per-language verification status after install. */
37
+ export type PrepareStatus = 'installed' | 'missing' | 'unfixable';
38
+ export interface PrepareReport {
39
+ languages: string[];
40
+ status: Map<string, PrepareStatus>;
41
+ artifacts: Map<string, string[]>;
42
+ exitHint: string;
43
+ resumeHint: string;
44
+ }
45
+ /** Result of the approval phase (Task 5). */
46
+ export interface PromptApprovalResult {
47
+ approved: boolean;
48
+ preamble: string;
49
+ /** Set when non-interactive without --yes or --dry-run. */
50
+ refused?: boolean;
51
+ }
52
+ /**
53
+ * Detect available test runners and lockfiles for the repo at cwd.
54
+ * Reuses resolveRunner from runner-detection.ts.
55
+ */
56
+ export declare function detectStack(cwd: string, registry: Map<string, ResolvedProvider>): DetectedStack;
57
+ /**
58
+ * Build an install plan per detected language by consulting the TestRunner
59
+ * registry install field (single-source-of-truth, spec D1).
60
+ *
61
+ * `cwd` is the caller's repo root: the .venv probe reads it so library callers
62
+ * get their own tree instead of the process-global cwd.
63
+ */
64
+ export declare function createInstallPlan(stack: DetectedStack, registry: Map<string, ResolvedProvider>, config: ProviderConfig, cwd: string): InstallPlan[];
65
+ /**
66
+ * Build a human-readable plain-English summary of an install plan.
67
+ * Describes what each language will do, why, and the blast radius.
68
+ * Used by promptApproval and agent callers.
69
+ */
70
+ export declare function buildPreamble(plan: InstallPlan[]): string;
71
+ /**
72
+ * Present plan for approval or auto-decide based on flags.
73
+ * - dryRun: return preamble, no prompt, approved=false (exit-0 semantics)
74
+ * - yes: auto-approve
75
+ * - TTY: print preamble, prompt 'Proceed? [y/N]'
76
+ * - non-TTY no flags: refused=true
77
+ */
78
+ export declare function promptApproval(plan: InstallPlan[], options: PrepareOptions): Promise<PromptApprovalResult>;
79
+ /** Per-action outcome of the install phase. */
80
+ export interface InstallActionResult {
81
+ kind: InstallActionKind;
82
+ status: 'installed' | 'skipped' | 'failed';
83
+ detail: string;
84
+ }
85
+ /** Aggregate result of executing an install plan. */
86
+ export interface ExecuteResult {
87
+ actions: InstallActionResult[];
88
+ ok: boolean;
89
+ }
90
+ /**
91
+ * Execute allowlisted install actions per plan. 60s timeout per action, no shell
92
+ * (execFile directly). Actions outside the install allowlist (e.g. verify-tool probes)
93
+ * are skipped. `sudo` anywhere in the command is rejected, and the executable's
94
+ * basename must be in INSTALL_BINARY_ALLOWLIST for the action's kind.
95
+ */
96
+ export declare function executeInstallPlan(plan: InstallPlan[], options: PrepareOptions): Promise<ExecuteResult>;
97
+ /**
98
+ * Flush config pins (provider install specs) to disk after a successful install.
99
+ * Reads the existing config file (JSON.parse if present, else empty {}), merges
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.
103
+ */
104
+ export declare function flushConfigUpdates(plan: InstallPlan[], cwd: string): string[];
105
+ /** Per self-analyzer probe result. */
106
+ export interface VerifyAnalyzer {
107
+ name: string;
108
+ status: 'ok' | 'unfixable';
109
+ detail: string;
110
+ }
111
+ /** Phase 5 report: re-detected stack + analyzer self-probes + aggregate ok. */
112
+ export interface VerifyReport {
113
+ reDetected: DetectedStack;
114
+ analyzers: VerifyAnalyzer[];
115
+ ok: boolean;
116
+ }
117
+ /**
118
+ * Re-detect stack and run resolveRunner-independent self-analyzer probes:
119
+ * (a) Node import probe: `@barney-media/crap-typescript-core` resolvable
120
+ * (b) CLI version probe: `npx --no-install crap-typescript --version` exit 0
121
+ * (c) Python stdlib probe: venv-aware `python -c "import ast"`
122
+ * Returns re-detected stack, per-probe status, and aggregate `ok`.
123
+ */
124
+ export declare function verifyInstall(stack: DetectedStack, options: PrepareOptions): Promise<VerifyReport>;
@@ -0,0 +1,459 @@
1
+ /**
2
+ * prepare-repo orchestrator (Tasks 2-7 of prepare-repo spec).
3
+ *
4
+ * 5-phase lifecycle: detect → plan → approve → install → verify.
5
+ */
6
+ import * as fs from 'node:fs';
7
+ import * as path from 'node:path';
8
+ import { deriveRegistry, loadProviderConfig } from './config.js';
9
+ import { resolveRunner } from './runner-detection.js';
10
+ import { createInterface } from 'node:readline';
11
+ import { execFile } from 'node:child_process';
12
+ import { promisify } from 'node:util';
13
+ // ---- Phase 1: detect ----
14
+ /** Lockfile search order per language (first match wins). */
15
+ const LOCKFILES_BY_LANGUAGE = {
16
+ javascript: ['pnpm-lock.yaml', 'yarn.lock', 'package-lock.json', 'package.json'],
17
+ typescript: ['pnpm-lock.yaml', 'yarn.lock', 'package-lock.json', 'package.json'],
18
+ python: ['pyproject.toml', 'pytest.ini', 'setup.cfg', 'requirements.txt'],
19
+ };
20
+ function detectLockfile(cwd, language) {
21
+ const candidates = LOCKFILES_BY_LANGUAGE[language];
22
+ if (!candidates)
23
+ return null;
24
+ for (const file of candidates) {
25
+ if (fs.existsSync(path.join(cwd, file)))
26
+ return file;
27
+ }
28
+ return null;
29
+ }
30
+ /**
31
+ * Detect available test runners and lockfiles for the repo at cwd.
32
+ * Reuses resolveRunner from runner-detection.ts.
33
+ */
34
+ export function detectStack(cwd, registry) {
35
+ const runners = resolveRunner(cwd, registry);
36
+ const languages = Array.from(runners.keys());
37
+ const lockfiles = new Map();
38
+ for (const language of languages) {
39
+ lockfiles.set(language, detectLockfile(cwd, language));
40
+ }
41
+ return { languages, runners, lockfiles };
42
+ }
43
+ // ---- Phase 2: plan ----
44
+ /** Match a resolved runner's command back to its source TestRunner + provider in the registry. */
45
+ function findProviderAndRunner(registry, language, command) {
46
+ const seen = new Set();
47
+ for (const provider of registry.values()) {
48
+ if (seen.has(provider))
49
+ continue;
50
+ seen.add(provider);
51
+ if (provider.language !== language)
52
+ continue;
53
+ if (!provider.testRunners)
54
+ continue;
55
+ for (const runner of provider.testRunners) {
56
+ if (JSON.stringify(runner.command) === JSON.stringify(command)) {
57
+ return { provider, runner };
58
+ }
59
+ }
60
+ }
61
+ return null;
62
+ }
63
+ /** Derive package-manager install command from lockfile precedence (pnpm > yarn > npm; python pip). */
64
+ function packageManagerCommand(lockfile, language) {
65
+ if (language === 'javascript' || language === 'typescript') {
66
+ if (lockfile === 'pnpm-lock.yaml')
67
+ return ['pnpm', 'add', '-D'];
68
+ if (lockfile === 'yarn.lock')
69
+ return ['yarn', 'add', '-D'];
70
+ return ['npm', 'install', '-D'];
71
+ }
72
+ if (language === 'python')
73
+ return ['pip', 'install'];
74
+ return null;
75
+ }
76
+ /** Derive a --version probe from the runner's command. */
77
+ function verifyCommand(runnerCommand) {
78
+ const [first, second, third] = runnerCommand;
79
+ if (first === 'npx' && second) {
80
+ return ['npx', '--no-install', second, '--version'];
81
+ }
82
+ if (first === 'python3' && second === '-m' && third) {
83
+ return ['python3', '-m', third, '--version'];
84
+ }
85
+ return [...runnerCommand, '--version'];
86
+ }
87
+ /**
88
+ * Build an install plan per detected language by consulting the TestRunner
89
+ * registry install field (single-source-of-truth, spec D1).
90
+ *
91
+ * `cwd` is the caller's repo root: the .venv probe reads it so library callers
92
+ * get their own tree instead of the process-global cwd.
93
+ */
94
+ export function createInstallPlan(stack, registry, config, cwd) {
95
+ const plans = [];
96
+ for (const lang of stack.languages) {
97
+ const runner = stack.runners.get(lang);
98
+ if (!runner)
99
+ continue;
100
+ const found = findProviderAndRunner(registry, lang, runner.command);
101
+ const testRunner = found?.runner ?? null;
102
+ const provider = found?.provider ?? null;
103
+ const lockfile = stack.lockfiles.get(lang) ?? null;
104
+ const packages = testRunner?.install?.packages ?? [];
105
+ const actions = [];
106
+ // create-venv: python when no .venv exists (must precede install-lockfile
107
+ // so executeInstallPlan can rewrite pip → venv python at spawn time)
108
+ if (lang === 'python') {
109
+ const venvPath = path.join(cwd, '.venv');
110
+ if (!fs.existsSync(venvPath)) {
111
+ actions.push({
112
+ kind: 'create-venv',
113
+ command: ['python3', '-m', 'venv', '.venv'],
114
+ description: 'Create Python virtual environment at .venv',
115
+ });
116
+ }
117
+ }
118
+ // install-lockfile: install packages via lockfile-precedence package manager
119
+ 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
+ });
128
+ }
129
+ }
130
+ // verify-tool: probe tool availability
131
+ actions.push({
132
+ kind: 'verify-tool',
133
+ command: verifyCommand(runner.command),
134
+ description: `Verify ${testRunner?.name ?? runner.command.join(' ')} is installed`,
135
+ });
136
+ // configUpdates: pin install packages in checkchange.providers.json when source is builtin
137
+ const configUpdates = {};
138
+ if (packages.length > 0 && testRunner && provider?.source === 'builtin') {
139
+ configUpdates['checkchange.providers.json'] = {
140
+ version: config.version,
141
+ providers: [
142
+ {
143
+ language: lang,
144
+ testRunners: [
145
+ {
146
+ name: testRunner.name,
147
+ install: { packages },
148
+ },
149
+ ],
150
+ },
151
+ ],
152
+ };
153
+ }
154
+ plans.push({ language: lang, actions, configUpdates });
155
+ }
156
+ return plans;
157
+ }
158
+ // ---- Phase 3: approve ----
159
+ /**
160
+ * Build a human-readable plain-English summary of an install plan.
161
+ * Describes what each language will do, why, and the blast radius.
162
+ * Used by promptApproval and agent callers.
163
+ */
164
+ export function buildPreamble(plan) {
165
+ if (plan.length === 0) {
166
+ return 'No changes — all test runners already available.';
167
+ }
168
+ const lines = [];
169
+ lines.push(`checkchange prepare — ${plan.length} language(s): ` +
170
+ `${plan.map((p) => p.language).join(', ')}`);
171
+ for (const p of plan) {
172
+ lines.push('', `${p.language}:`);
173
+ for (const a of p.actions) {
174
+ lines.push(` - ${a.description}`);
175
+ if (a.command) {
176
+ lines.push(` command: ${a.command.join(' ')}`);
177
+ }
178
+ }
179
+ const configKeys = Object.keys(p.configUpdates);
180
+ if (configKeys.length > 0) {
181
+ lines.push(` config pins: ${configKeys.join(', ')}`);
182
+ }
183
+ }
184
+ // Blast radius
185
+ const blasts = new Set();
186
+ for (const p of plan) {
187
+ for (const a of p.actions) {
188
+ if (a.kind === 'install-lockfile')
189
+ blasts.add('package files (package.json + lockfile)');
190
+ if (a.kind === 'create-venv')
191
+ blasts.add('.venv directory');
192
+ }
193
+ if (Object.keys(p.configUpdates).length > 0) {
194
+ blasts.add(`config file: ${Object.keys(p.configUpdates).join(', ')}`);
195
+ }
196
+ }
197
+ if (blasts.size > 0) {
198
+ lines.push('', `Blast radius: ${[...blasts].join(', ')}`);
199
+ }
200
+ return lines.join('\n');
201
+ }
202
+ /** Prompt the user with a yes/no question via node:readline. */
203
+ function askProceed(query) {
204
+ return new Promise((resolve) => {
205
+ const rl = createInterface({
206
+ input: process.stdin,
207
+ output: process.stdout,
208
+ });
209
+ rl.question(query, (answer) => {
210
+ rl.close();
211
+ resolve(answer);
212
+ });
213
+ });
214
+ }
215
+ /**
216
+ * Present plan for approval or auto-decide based on flags.
217
+ * - dryRun: return preamble, no prompt, approved=false (exit-0 semantics)
218
+ * - yes: auto-approve
219
+ * - TTY: print preamble, prompt 'Proceed? [y/N]'
220
+ * - non-TTY no flags: refused=true
221
+ */
222
+ export async function promptApproval(plan, options) {
223
+ const preamble = buildPreamble(plan);
224
+ if (options.dryRun) {
225
+ return { approved: false, preamble };
226
+ }
227
+ if (options.yes) {
228
+ return { approved: true, preamble };
229
+ }
230
+ if (process.stdin.isTTY) {
231
+ process.stdout.write(preamble + '\n');
232
+ const answer = await askProceed('Proceed? [y/N] ');
233
+ const approved = /^y(es)?$/i.test(answer.trim());
234
+ return { approved, preamble };
235
+ }
236
+ return { approved: false, preamble, refused: true };
237
+ }
238
+ // ---- Phase 4: install ----
239
+ /** Install action kinds the install phase may execute (Task 6 trimmed allowlist).
240
+ * Maps to createInstallPlan kinds: install-lockfile (npm/pnpm/yarn/pip) + create-venv
241
+ * (== venv-create). verify-tool is a probe, not an install action. */
242
+ const INSTALL_ALLOWLIST = new Set([
243
+ 'install-lockfile',
244
+ 'create-venv',
245
+ ]);
246
+ /** 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,
248
+ * install-lockfile spreads that command after its own flags, resolvePipCommand -> venv `python` | python3.
249
+ *
250
+ * LIMIT: gates the EXECUTABLE NAME only — never the arguments, never the script that executable
251
+ * then runs. `python3 -c …` under install-lockfile, npm/pnpm/yarn lifecycle scripts, and pip sdist
252
+ * setup.py builds all run arbitrary code by design. This buys "a known installer runs", not
253
+ * confinement: a passing allowlist is not proof that the spawned process is sandboxed.
254
+ */
255
+ const INSTALL_BINARY_ALLOWLIST = new Map([
256
+ ['install-lockfile', new Set(['npm', 'pnpm', 'yarn', 'pip', 'python', 'python3'])],
257
+ ['create-venv', new Set(['python', 'python3'])],
258
+ ]);
259
+ const INSTALL_TIMEOUT_MS = 60_000;
260
+ const execFileAsync = promisify(execFile);
261
+ /** Rewrite a bare `pip install` command to run through the venv interpreter when a
262
+ * `.venv` exists, else `python3 -m pip`. Never uses --user (plain pip per lockfile). */
263
+ function resolvePipCommand(command, cwd) {
264
+ const packages = command.slice(2); // drop ['pip', 'install']
265
+ const venvPython = path.join(cwd, '.venv', 'bin', 'python');
266
+ if (fs.existsSync(venvPython)) {
267
+ return [venvPython, '-m', 'pip', 'install', ...packages];
268
+ }
269
+ return ['python3', '-m', 'pip', 'install', ...packages];
270
+ }
271
+ /**
272
+ * Execute allowlisted install actions per plan. 60s timeout per action, no shell
273
+ * (execFile directly). Actions outside the install allowlist (e.g. verify-tool probes)
274
+ * are skipped. `sudo` anywhere in the command is rejected, and the executable's
275
+ * basename must be in INSTALL_BINARY_ALLOWLIST for the action's kind.
276
+ */
277
+ export async function executeInstallPlan(plan, options) {
278
+ const cwd = options.cwd;
279
+ const actions = [];
280
+ for (const entry of plan) {
281
+ for (const action of entry.actions) {
282
+ if (!INSTALL_ALLOWLIST.has(action.kind)) {
283
+ actions.push({ kind: action.kind, status: 'skipped', detail: 'not in install allowlist' });
284
+ continue;
285
+ }
286
+ const command = action.command;
287
+ if (!command || command.length === 0) {
288
+ actions.push({ kind: action.kind, status: 'skipped', detail: 'no command' });
289
+ continue;
290
+ }
291
+ let resolved = command;
292
+ // pip installs route through the venv interpreter when present, else python3 -m pip
293
+ if (action.kind === 'install-lockfile' && command[0] === 'pip') {
294
+ resolved = resolvePipCommand(command, cwd);
295
+ }
296
+ if (resolved.includes('sudo')) {
297
+ actions.push({ kind: action.kind, status: 'failed', detail: 'rejected: command contains sudo' });
298
+ continue;
299
+ }
300
+ const [cmd, ...args] = resolved;
301
+ if (!cmd) {
302
+ actions.push({ kind: action.kind, status: 'skipped', detail: 'no command' });
303
+ continue;
304
+ }
305
+ // Two layers, both fail-closed. The whole-array test above already refuses a
306
+ // bare `sudo` element; this one catches the path forms it misses (/usr/bin/sudo,
307
+ // ./sudo) and, being a basename compare, cannot be satisfied by an argument.
308
+ const binary = path.basename(cmd);
309
+ if (binary === 'sudo') {
310
+ actions.push({ kind: action.kind, status: 'failed', detail: 'rejected: command contains sudo' });
311
+ continue;
312
+ }
313
+ if (!INSTALL_BINARY_ALLOWLIST.get(action.kind)?.has(binary)) {
314
+ actions.push({ kind: action.kind, status: 'failed', detail: `rejected: binary not allowed: ${cmd}` });
315
+ continue;
316
+ }
317
+ try {
318
+ await execFileAsync(cmd, args, { cwd, timeout: INSTALL_TIMEOUT_MS, maxBuffer: 10_000_000 });
319
+ actions.push({ kind: action.kind, status: 'installed', detail: `${cmd} ${args.join(' ')}` });
320
+ }
321
+ catch (e) {
322
+ const err = e;
323
+ const detail = err.killed ? 'timed out after 60s' : err.message ?? 'failed';
324
+ actions.push({ kind: action.kind, status: 'failed', detail });
325
+ }
326
+ }
327
+ }
328
+ return {
329
+ actions,
330
+ ok: !actions.some((r) => r.status === 'failed'),
331
+ };
332
+ }
333
+ /**
334
+ * Flush config pins (provider install specs) to disk after a successful install.
335
+ * Reads the existing config file (JSON.parse if present, else empty {}), merges
336
+ * 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.
339
+ */
340
+ export function flushConfigUpdates(plan, cwd) {
341
+ const written = new Set();
342
+ for (const entry of plan) {
343
+ for (const [configKey, pin] of Object.entries(entry.configUpdates)) {
344
+ if (configKey !== 'checkchange.providers.json')
345
+ continue;
346
+ if (!pin)
347
+ continue;
348
+ const pinConfig = pin;
349
+ const pinProviders = pinConfig.providers;
350
+ if (!pinProviders?.length)
351
+ continue;
352
+ const configPath = path.resolve(cwd, configKey);
353
+ let existing;
354
+ try {
355
+ existing = JSON.parse(fs.readFileSync(configPath, 'utf8'));
356
+ }
357
+ catch {
358
+ existing = {};
359
+ }
360
+ if (!Array.isArray(existing.providers))
361
+ existing.providers = [];
362
+ if (existing.version === undefined)
363
+ existing.version = pinConfig.version ?? 1;
364
+ const existingProviders = existing.providers;
365
+ for (const pinProvider of pinProviders) {
366
+ const match = existingProviders.find((p) => p.language === pinProvider.language);
367
+ if (match) {
368
+ const runners = match.testRunners ??= [];
369
+ for (const pinRunner of pinProvider.testRunners ?? []) {
370
+ const rm = runners.find((r) => r.name === pinRunner.name);
371
+ if (rm) {
372
+ if (pinRunner.install)
373
+ rm.install = pinRunner.install;
374
+ }
375
+ else {
376
+ runners.push(pinRunner);
377
+ }
378
+ }
379
+ }
380
+ else {
381
+ existingProviders.push(pinProvider);
382
+ }
383
+ }
384
+ const tmpPath = `${configPath}.tmp`;
385
+ fs.writeFileSync(tmpPath, JSON.stringify(existing, null, 2));
386
+ fs.renameSync(tmpPath, configPath);
387
+ written.add(configKey);
388
+ }
389
+ }
390
+ return [...written];
391
+ }
392
+ /** Resolve the Python interpreter venv-aware:
393
+ * `.venv/bin/python` > $VIRTUAL_ENV/bin/python > `python3`. */
394
+ function resolvePython(cwd) {
395
+ const venvLocal = path.join(cwd, '.venv', 'bin', 'python');
396
+ if (fs.existsSync(venvLocal))
397
+ return [venvLocal];
398
+ const venvEnv = process.env.VIRTUAL_ENV;
399
+ if (venvEnv)
400
+ return [path.join(venvEnv, 'bin', 'python')];
401
+ return ['python3'];
402
+ }
403
+ /**
404
+ * Re-detect stack and run resolveRunner-independent self-analyzer probes:
405
+ * (a) Node import probe: `@barney-media/crap-typescript-core` resolvable
406
+ * (b) CLI version probe: `npx --no-install crap-typescript --version` exit 0
407
+ * (c) Python stdlib probe: venv-aware `python -c "import ast"`
408
+ * Returns re-detected stack, per-probe status, and aggregate `ok`.
409
+ */
410
+ export async function verifyInstall(stack, options) {
411
+ const cwd = options.cwd;
412
+ // Phase 5 re-runs detection (spec §1 Phase 5); re-derive registry from config.
413
+ const { config, source } = loadProviderConfig(cwd);
414
+ const registry = deriveRegistry(config, source);
415
+ const reDetected = detectStack(cwd, registry);
416
+ const analyzers = [];
417
+ // (a) Node import probe — @barney-media/crap-typescript-core resolvable?
418
+ try {
419
+ const mod = await import('@barney-media/crap-typescript-core');
420
+ const exports = Object.keys(mod);
421
+ analyzers.push({
422
+ name: 'crap-typescript-core-import',
423
+ status: 'ok',
424
+ detail: `resolvable: ${exports.length ? exports.join(', ') : 'no exports'}`,
425
+ });
426
+ }
427
+ catch {
428
+ analyzers.push({ name: 'crap-typescript-core-import', status: 'unfixable', detail: 'reinstall checkchange' });
429
+ }
430
+ // (b) CLI availability probe — npx --no-install crap-typescript --help exit 0.
431
+ // NOTE: `--version` is unsupported by the binary (exits 1 "Unknown option");
432
+ // `--help` exits 0 per the tool's own usage contract (matches src/crap.ts:30 npx shape).
433
+ try {
434
+ const { stdout } = await execFileAsync('npx', ['--no-install', 'crap-typescript', '--help'], { cwd, timeout: 60_000 });
435
+ const line = stdout.split('\n')[0]?.trim() ?? '';
436
+ analyzers.push({ name: 'crap-typescript-cli', status: 'ok', detail: `exit 0: ${line}` });
437
+ }
438
+ catch {
439
+ analyzers.push({ name: 'crap-typescript-cli', status: 'unfixable', detail: 'reinstall checkchange' });
440
+ }
441
+ // (c) Python stdlib probe — venv-aware python -c "import ast"
442
+ const pyCmd = resolvePython(cwd);
443
+ const [pyBin, ...pyArgs] = pyCmd;
444
+ try {
445
+ await execFileAsync(pyBin, [...pyArgs, '-c', 'import ast'], { cwd, timeout: 60_000 });
446
+ analyzers.push({ name: 'python-stdlib-ast', status: 'ok', detail: 'import ast ok' });
447
+ }
448
+ catch {
449
+ const guidance = pyBin === 'python3'
450
+ ? 'python3 not found on PATH; install Python 3 and re-run prepare-repo'
451
+ : `${pyBin} not found; create .venv via "python3 -m venv .venv" and re-run`;
452
+ analyzers.push({ name: 'python-stdlib-ast', status: 'unfixable', detail: guidance });
453
+ }
454
+ return {
455
+ reDetected,
456
+ analyzers,
457
+ ok: !analyzers.some((a) => a.status === 'unfixable'),
458
+ };
459
+ }
@@ -0,0 +1,30 @@
1
+ import type { ResolvedProvider } from './config.js';
2
+ export interface ResolvedRunner {
3
+ /** Full spawn command, e.g. ['npx','vitest','run','--coverage']. */
4
+ command: string[];
5
+ /** Coverage artifact path (relative, as configured). */
6
+ artifact: string;
7
+ /** Human-readable evidence, e.g. 'pytest.ini + .venv/bin/pytest'. */
8
+ provenance: string;
9
+ }
10
+ /**
11
+ * Resolve available test runners per language.
12
+ * Returns one entry per language whose source files are present AND whose
13
+ * first-available runner (by configFiles/binaryProbes) probes successfully.
14
+ * Empty map if none detected.
15
+ *
16
+ * RESOLUTION PHASE (selection only):
17
+ * - Iterates providers with source files present
18
+ * - For each provider's testRunners, calls probeRunner() (PROBE PHASE)
19
+ * - First successful probe per language wins (short-circuits)
20
+ * - Returns ResolvedRunner with:
21
+ * * command: full spawn command for EXECUTION (e.g. ['npx','vitest','run','--coverage'])
22
+ * * artifact: expected coverage artifact path
23
+ * * provenance: human-readable evidence string from probe
24
+ *
25
+ * EXECUTION BOUNDARY:
26
+ * - This function ONLY selects and returns the command to run.
27
+ * - Actual test execution with coverage happens in auto-coverage.ts:82-86
28
+ * via spawnSync(runner.command, runner.args, ...) — separate process, full test run.
29
+ */
30
+ export declare function resolveRunner(cwd: string, registry: Map<string, ResolvedProvider>): Map<string, ResolvedRunner>;