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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 victorpetropoulos
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,150 @@
1
+ # checkchange
2
+ Independent, deterministic evidence and verification layer for AI-assisted software development.
3
+
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
5
+ [![Node: 24](https://img.shields.io/badge/Node-24-green.svg)](.nvmrc)
6
+
7
+ ## Install
8
+
9
+ Verified from-source (registry install available **after npm publish** — gated on `npm view checkchange version` returning 2xx):
10
+
11
+ ```bash
12
+ corepack enable
13
+ pnpm install --frozen-lockfile
14
+ pnpm run build
15
+ ```
16
+
17
+ ```bash
18
+ # after npm publish only:
19
+ npm install -g checkchange
20
+ ```
21
+
22
+ > **Warning:** Git URL install is not supported. `prepare` runs `pnpm run build` (needs pnpm + TypeScript toolchain). The npm registry tarball ships prebuilt `dist/cli.js`; from-source always builds.
23
+
24
+ ## Quickstart (<30s)
25
+
26
+ ```bash
27
+ pnpm exec vitest run --coverage
28
+ ```
29
+
30
+ ```text
31
+ Test Files 122 passed (122)
32
+ Tests 872 passed (872)
33
+
34
+ % Coverage report from v8
35
+ All files | 86.47 | 78.74 | 90.16 | 88.42 |
36
+ ```
37
+
38
+ ```bash
39
+ node dist/cli.js check --base main --json
40
+ ```
41
+
42
+ ```json
43
+ {
44
+ "schemaVersion": "0.5",
45
+ "analysis": {
46
+ "base": "2ca94cddb9c2f91a1a56cd6e065d34f4ca1c8de0",
47
+ "target": "current"
48
+ },
49
+ "capabilities": {
50
+ "git": "available",
51
+ "complexity": "unavailable",
52
+ "coverageArtifact": "unavailable"
53
+ },
54
+ "changedFunctions": [],
55
+ "ruleResults": [],
56
+ "policy": {
57
+ "crapThreshold": 30
58
+ },
59
+ "analysisStatus": "UNSUPPORTED",
60
+ "gate": "NOT_EVALUATED",
61
+ "completeness": "INCOMPLETE"
62
+ }
63
+ ```
64
+
65
+ `diagnostics.lineage` and `diagnostics.quality` follow; omitted above for brevity. A clean
66
+ checkout has no changed functions, so `changedFunctions` is empty and the gate is not evaluated.
67
+
68
+ ```bash
69
+ node dist/cli.js doctor
70
+ ```
71
+
72
+ ```text
73
+ gitExecutable: ok
74
+ gitRepo: ok
75
+ defaultBase: ok (origin/main)
76
+ providerAvailability: no-changed-files
77
+ ↳ no changed files detected against the base — stage a change and re-run (`git status` / `git diff --stat`). An empty diff is a valid stop: there is nothing to assess.
78
+ coverageArtifact: present
79
+ ```
80
+
81
+ ## Usage
82
+
83
+ Three canonical examples (verbatim from `src/help.ts:75-77`):
84
+
85
+ ```bash
86
+ checkchange check --base main --json
87
+ ```
88
+
89
+ ```bash
90
+ checkchange check --crap-threshold 25 --format github
91
+ ```
92
+
93
+ ```bash
94
+ checkchange check --auto-coverage --verbose
95
+ ```
96
+
97
+ Primary subcommands (`src/cli.ts:17`):
98
+
99
+ | Command | Purpose |
100
+ |---------|---------|
101
+ | `check` | Analyze changed functions, emit PASS/WARN/FAIL with evidence |
102
+ | `doctor` | Verify runtime prerequisites (Node, pnpm, coverage, git) |
103
+ | `prepare-repo` | Bootstrap test runners & coverage tooling (detect → plan → approve → install → verify) |
104
+ | `explain` | Show rule rationale for a given verdict |
105
+ | `trace` | Print evidence trace for a specific function |
106
+ | `delta` | Compare evidence between two refs |
107
+
108
+ Supported languages: TypeScript, JavaScript, Python (`src/cli.ts:22`).
109
+
110
+ ## How it works
111
+
112
+ Eight-stage pipeline (git → complexity → coverage → attribution → crapCalc → rules → evidence):
113
+
114
+ 1. **Git diff** — enumerate changed functions since `--base` (default: `origin/HEAD` → `main`/`master`)
115
+ 2. **Complexity** — per-function CRAP via `crap-typescript` (TS/JS) or `radon` (Python)
116
+ 3. **Coverage** — map LCOV/istanbul lines to changed functions (`src/coverage-providers/lcovProvider.ts`)
117
+ 4. **Attribution** — case-insensitive suffix match to provider-lowercased paths (`src/attribution.ts:91`)
118
+ 5. **crapCalc** — combine complexity + coverage → CRAP score (`src/crapCalc.ts:5`)
119
+ 6. **Rules** — INV-01..04 evaluated against thresholds (`src/evidence.ts:828`)
120
+ 7. **Evidence** — schema 0.5 (`src/evidence.ts:644`, `src/delta.ts:35`)
121
+ 8. **Output** — human-readable summary by default; JSON via `--json`, or `--format github|junit|sarif` for CI annotations
122
+
123
+ Default CRAP threshold: **30** (`src/help.ts:49`, `src/help.ts:66`).
124
+
125
+ Test suite: **122 test files**, 872 tests (`pnpm exec vitest run --coverage` in a clean clone). Hand-written specs live in `src/` (8) and `test/` (55); the run also picks up compiled `dist/` specs and spike suites.
126
+
127
+ ## Configuration
128
+
129
+ Key options (`src/help.ts` for full list):
130
+
131
+ | Flag | Description | Default |
132
+ |------|-------------|---------|
133
+ | `--base <ref>` | Git base ref for diff | auto-detect |
134
+ | `--crap-threshold <n>` | CRAP WARN threshold | 30 |
135
+ | `--coverage-file <path>` | Explicit LCOV/istanbul path | auto-detect |
136
+ | `--format <github\|junit\|sarif>` | Output format; JSON is the `--json` flag | none |
137
+
138
+ Provider config precedence: explicit `--provider-config <path>` > repo-root `./checkchange.providers.json` > builtin providers.
139
+
140
+ ## Contributing
141
+
142
+ Contributions via GitHub issues and pull requests.
143
+
144
+ ## License
145
+
146
+ MIT — see [LICENSE](LICENSE:1-3).
147
+
148
+ ## Changelog
149
+
150
+ See [CHANGELOG.md](CHANGELOG.md).
@@ -0,0 +1,19 @@
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
+ }
9
+ export declare const attributionProvenance: {
10
+ readonly tool: "@barney-media/crap-typescript-core";
11
+ readonly version: "0.5.0";
12
+ };
13
+ export interface AttributedComplexity {
14
+ info: ComplexityInfo;
15
+ coveragePercent: number | null;
16
+ coverageKind: string | null;
17
+ }
18
+ export declare function attachCoverage(complexityInfo: ComplexityInfo[], coverageResult: CoverageResult): Promise<AttributedComplexity[]>;
19
+ export {};
@@ -0,0 +1,175 @@
1
+ import { parseFileMethods } from '@barney-media/crap-typescript-core';
2
+ import { coverageForMethods } from '@barney-media/crap-typescript-core';
3
+ import { parsePythonFileMethods } from './complexity-providers/pythonDescriptorProvider.js';
4
+ // Provenance for the attribution lineage stage: coverageForMethods/parseFileMethods from the core package.
5
+ export const attributionProvenance = { tool: '@barney-media/crap-typescript-core', version: '0.5.0' };
6
+ export async function attachCoverage(complexityInfo, coverageResult) {
7
+ // If coverage is not available or has error, return null for coverage
8
+ if (!coverageResult.available || coverageResult.error) {
9
+ return nullCoverageForAll(complexityInfo);
10
+ }
11
+ // Cache for parsed method descriptors per file
12
+ const descriptorCache = new Map();
13
+ // Result map: keyed by (filePath, methodName, startLine) to coverage data
14
+ const coverageMap = new Map();
15
+ // Group complexity info by file
16
+ const complexityByFile = new Map();
17
+ for (const info of complexityInfo) {
18
+ if (!complexityByFile.has(info.file)) {
19
+ complexityByFile.set(info.file, []);
20
+ }
21
+ complexityByFile.get(info.file).push(info);
22
+ }
23
+ // Process each file that has coverage
24
+ for (const [filePath, fileCoverage] of coverageResult.coverageMap) {
25
+ // We'll find all complexity files where the absolute coverage path ends with the relative complexity path
26
+ const fileComplexity = matchingComplexityForFile(filePath, complexityByFile);
27
+ if (fileComplexity === undefined) {
28
+ // No exact match or ambiguous -> skip this coverage file (no attribution from it)
29
+ continue;
30
+ }
31
+ const methodDescriptors = await descriptorsForFile(filePath, descriptorCache);
32
+ if (methodDescriptors === undefined) {
33
+ // If parsing fails, treat as no coverage for this file's methods
34
+ for (const info of fileComplexity) {
35
+ coverageMap.set(coverageKeyFor(info), nullCoverageEntry());
36
+ }
37
+ continue;
38
+ }
39
+ attributeFile(fileComplexity, fileCoverage, descriptorIndex(methodDescriptors), coverageMap);
40
+ }
41
+ return assembleResult(complexityInfo, coverageMap);
42
+ }
43
+ // Input normalization: coverage is absent or errored, so every entry reports null coverage.
44
+ function nullCoverageForAll(complexityInfo) {
45
+ return complexityInfo.map(info => ({
46
+ info,
47
+ coveragePercent: null,
48
+ coverageKind: null
49
+ }));
50
+ }
51
+ // File matching: resolve the complexity entries a coverage file belongs to. Exactly one
52
+ // case-insensitive suffix match wins; zero matches or an ambiguous multi-match declines
53
+ // attribution for that coverage file.
54
+ function matchingComplexityForFile(filePath, complexityByFile) {
55
+ const normalizedFilePath = filePath.replace(/\\/g, '/');
56
+ const matches = [];
57
+ for (const [rel, list] of complexityByFile.entries()) {
58
+ const normalizedRel = rel.replace(/\\/g, '/');
59
+ // case-insensitive suffix match to handle provider lowercasing (e.g., crapCalc.ts)
60
+ if (normalizedFilePath.toLowerCase().endsWith(normalizedRel.toLowerCase())) {
61
+ matches.push({ rel, list });
62
+ }
63
+ }
64
+ let fileComplexity;
65
+ if (matches.length === 1) {
66
+ fileComplexity = matches[0].list;
67
+ }
68
+ else if (matches.length > 1) {
69
+ // Ambiguous match: decline attribution for this coverage file
70
+ fileComplexity = undefined;
71
+ }
72
+ else {
73
+ // No match
74
+ fileComplexity = undefined;
75
+ }
76
+ return fileComplexity;
77
+ }
78
+ // Result-map key for one complexity entry.
79
+ function coverageKeyFor(info) {
80
+ return `${info.file}:${info.method}:${info.lineStart}`;
81
+ }
82
+ // Null result entry: records "no coverage attributed" for one complexity entry.
83
+ function nullCoverageEntry() {
84
+ return { coveragePercent: null, coverageKind: null };
85
+ }
86
+ // Descriptor lookup: parse this file's method descriptors (Python-aware) through the
87
+ // caller-owned cache. undefined means parsing failed, so the caller records no coverage.
88
+ async function descriptorsForFile(filePath, descriptorCache) {
89
+ const cached = descriptorCache.get(filePath);
90
+ if (cached !== undefined) {
91
+ return cached;
92
+ }
93
+ try {
94
+ const methodDescriptors = filePath.endsWith('.py')
95
+ ? await parsePythonFileMethods(filePath)
96
+ : await parseFileMethods(filePath);
97
+ descriptorCache.set(filePath, methodDescriptors);
98
+ return methodDescriptors;
99
+ }
100
+ catch {
101
+ return undefined;
102
+ }
103
+ }
104
+ // Create a map from descriptor key to descriptor for quick lookup
105
+ function descriptorIndex(methodDescriptors) {
106
+ const descriptorMap = new Map();
107
+ for (const descriptor of methodDescriptors) {
108
+ const key = `${descriptor.containerName ? descriptor.containerName + '.' : ''}${descriptor.functionName}:${descriptor.startLine}`;
109
+ descriptorMap.set(key, descriptor);
110
+ }
111
+ return descriptorMap;
112
+ }
113
+ // For each complexity info in this file, find matching descriptor and compute coverage
114
+ function attributeFile(fileComplexity, fileCoverage, descriptorMap, coverageMap) {
115
+ for (const info of fileComplexity) {
116
+ const descriptor = descriptorMap.get(`${info.method}:${info.lineStart}`);
117
+ if (!descriptor) {
118
+ // No matching descriptor found
119
+ coverageMap.set(coverageKeyFor(info), nullCoverageEntry());
120
+ continue;
121
+ }
122
+ try {
123
+ const methodCoverage = coverageForMethods([descriptor], fileCoverage)[0];
124
+ if (!methodCoverage) {
125
+ // No coverage data returned
126
+ coverageMap.set(coverageKeyFor(info), nullCoverageEntry());
127
+ continue;
128
+ }
129
+ // Determine coverageKind based on statement and branch coverage
130
+ const stmtPercent = methodCoverage.statementCoverage.percent;
131
+ const branchPercent = methodCoverage.branchCoverage.percent;
132
+ let coverageKind = null;
133
+ if (stmtPercent === null && branchPercent === null) {
134
+ coverageKind = null;
135
+ }
136
+ else if (stmtPercent === null) {
137
+ coverageKind = 'branch';
138
+ }
139
+ else if (branchPercent === null) {
140
+ coverageKind = 'stmt';
141
+ }
142
+ else if (stmtPercent < branchPercent) {
143
+ coverageKind = 'stmt';
144
+ }
145
+ else if (branchPercent < stmtPercent) {
146
+ coverageKind = 'branch';
147
+ }
148
+ else {
149
+ coverageKind = 'stmt'; // arbitrary choice when equal
150
+ }
151
+ coverageMap.set(coverageKeyFor(info), {
152
+ coveragePercent: methodCoverage.coverage.percent,
153
+ coverageKind
154
+ });
155
+ }
156
+ catch {
157
+ // Error in coverage attribution
158
+ coverageMap.set(coverageKeyFor(info), nullCoverageEntry());
159
+ }
160
+ }
161
+ }
162
+ // Result assembly: build the result in the same order as complexityInfo. A single
163
+ // forward pass, so the result order always matches the input order.
164
+ function assembleResult(complexityInfo, coverageMap) {
165
+ const result = [];
166
+ for (const info of complexityInfo) {
167
+ const coverageData = coverageMap.get(coverageKeyFor(info)) ?? nullCoverageEntry();
168
+ result.push({
169
+ info,
170
+ coveragePercent: coverageData.coveragePercent,
171
+ coverageKind: coverageData.coverageKind
172
+ });
173
+ }
174
+ return result;
175
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Detect runner, spawn ONE coverage run (120s timeout), return expected artifact path or null.
3
+ * On timeout/failure: returns null (caller falls back to absent path — never forced FAILED).
4
+ */
5
+ export declare function autoCoverage(cwd: string): {
6
+ generatedPath: string | null;
7
+ hint: string | null;
8
+ };
@@ -0,0 +1,93 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { loadProviderConfig, deriveRegistry, resolveRunner, builtinConfig } from './providers/index.js';
5
+ const COV_TIMEOUT = 120_000;
6
+ /**
7
+ * Detect which test runner is available and return its coverage command + expected artifact path.
8
+ * Precedence: vitest > jest > pytest.
9
+ * ponytail: config glob + package.json dep check is enough; no runner introspection needed.
10
+ */
11
+ function detectRunner(cwd) {
12
+ // Vitest: config files exist or vitest in devDependencies
13
+ if (hasVitest(cwd)) {
14
+ return { command: 'npx', args: ['vitest', 'run', '--coverage'], artifact: path.join(cwd, 'coverage', 'coverage-final.json') };
15
+ }
16
+ // Jest: config files exist or jest in devDependencies
17
+ if (hasJest(cwd)) {
18
+ return { command: 'npx', args: ['jest', '--coverage'], artifact: path.join(cwd, 'coverage', 'coverage-final.json') };
19
+ }
20
+ // pytest: pyproject.toml/pytest.ini + .py files
21
+ if (hasPytest(cwd)) {
22
+ return { command: 'python3', args: ['-m', 'pytest', '--cov', '--cov-report=xml'], artifact: path.join(cwd, 'coverage.xml') };
23
+ }
24
+ return null;
25
+ }
26
+ function hasVitest(cwd) {
27
+ const configGlob = fs.readdirSync(cwd).some(f => f.startsWith('vitest.config'));
28
+ if (configGlob)
29
+ return true;
30
+ try {
31
+ const pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
32
+ return !!(pkg.devDependencies?.vitest || pkg.dependencies?.vitest);
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ function hasJest(cwd) {
39
+ const configGlob = fs.readdirSync(cwd).some(f => f.startsWith('jest.config'));
40
+ if (configGlob)
41
+ return true;
42
+ try {
43
+ const pkg = JSON.parse(fs.readFileSync(path.join(cwd, 'package.json'), 'utf8'));
44
+ return !!(pkg.devDependencies?.jest || pkg.dependencies?.jest);
45
+ }
46
+ catch {
47
+ return false;
48
+ }
49
+ }
50
+ function hasPytest(cwd) {
51
+ const configFiles = ['pyproject.toml', 'pytest.ini', 'setup.cfg'];
52
+ const hasConfig = configFiles.some(f => fs.existsSync(path.join(cwd, f)));
53
+ if (!hasConfig)
54
+ return false;
55
+ return fs.readdirSync(cwd, { recursive: true }).some(f => typeof f === 'string' && f.endsWith('.py'));
56
+ }
57
+ /**
58
+ * Detect runner, spawn ONE coverage run (120s timeout), return expected artifact path or null.
59
+ * On timeout/failure: returns null (caller falls back to absent path — never forced FAILED).
60
+ */
61
+ export function autoCoverage(cwd) {
62
+ let runner = detectRunner(cwd);
63
+ const cfg = loadProviderConfig(cwd, undefined);
64
+ const registry = deriveRegistry(cfg.config, cfg.source);
65
+ const resolved = resolveRunner(cwd, registry);
66
+ if (resolved.size > 0) {
67
+ const first = resolved.values().next().value;
68
+ const [cmd, ...args] = first.command;
69
+ runner = { command: cmd, args, artifact: path.join(cwd, first.artifact) };
70
+ }
71
+ if (!runner) {
72
+ return { generatedPath: null, hint: 'No test runner detected. Install vitest, jest, or pytest to use --auto-coverage.' };
73
+ }
74
+ const fullCommand = [runner.command, ...runner.args];
75
+ const isBuiltinRunner = builtinConfig().providers.some(({ testRunners }) => testRunners?.some(({ command }) => command.length === fullCommand.length && command.every((arg, index) => arg === fullCommand[index])));
76
+ if (!isBuiltinRunner) {
77
+ return { generatedPath: null, hint: `Coverage runner rejected: ${fullCommand.join(' ')} is not a built-in runner.` };
78
+ }
79
+ const result = spawnSync(runner.command, runner.args, {
80
+ cwd,
81
+ encoding: 'utf8',
82
+ timeout: COV_TIMEOUT,
83
+ });
84
+ if (result.status !== 0) {
85
+ const exitDesc = result.error?.code === 'ETIMEDOUT' ? 'timed out after 120s' : `exited ${result.status}`;
86
+ return { generatedPath: null, hint: `Coverage generation failed (${runner.command} ${exitDesc}). Run manually: ${runner.command} ${runner.args.join(' ')}` };
87
+ }
88
+ // Verify artifact was created
89
+ if (!fs.existsSync(runner.artifact)) {
90
+ return { generatedPath: null, hint: `Coverage command succeeded but artifact not found at ${runner.artifact}. Run manually: ${runner.command} ${runner.args.join(' ')}` };
91
+ }
92
+ return { generatedPath: runner.artifact, hint: null };
93
+ }
@@ -0,0 +1,70 @@
1
+ import { type CoverageResult } from './coverage.js';
2
+ export declare const CACHE_TTL_MS: number;
3
+ export declare const MAX_CACHE_TOTAL_BYTES: number;
4
+ export declare const MAX_CACHE_ENTRY_BYTES: number;
5
+ export type MissReason = 'absent' | 'expired' | 'corrupt' | 'oversized' | 'guard';
6
+ export type CacheLookup<T> = {
7
+ hit: true;
8
+ value: T;
9
+ } | {
10
+ hit: false;
11
+ value: T;
12
+ reason: MissReason;
13
+ };
14
+ /** Run-shard key inputs (all values from the current run — deterministic). */
15
+ export interface RunKeyInputs {
16
+ fileKeys: string[];
17
+ coverageHash: string;
18
+ threshold: number;
19
+ engine: string;
20
+ base: string;
21
+ intervalsSha256: string;
22
+ }
23
+ export type CacheKeyInput = {
24
+ kind: 'file';
25
+ fileContent: string;
26
+ providerVersion: string;
27
+ changedFilesHash?: string;
28
+ } | {
29
+ kind: 'coverage';
30
+ coverageHash: string;
31
+ providerVersion: string;
32
+ } | ({
33
+ kind: 'run';
34
+ } & RunKeyInputs);
35
+ /**
36
+ * Cache root resolution and the allowed-root rule:
37
+ * - Default: realpath(cwd)/.checkchange/cache — always inside the analyzed repo.
38
+ * - CHECKCHANGE_CACHE_DIR override: must be an ABSOLUTE path whose realpath
39
+ * resolves. It MAY live outside cwd (operator explicitly opts in, e.g. a CI
40
+ * shared cache dir); "escaping the allowed root" therefore means an ENTRY
41
+ * escaping the resolved root — every cache path is isWithin-checked against
42
+ * the resolved root on read and write, so symlinked or swapped entries that
43
+ * resolve outside it are rejected as misses ('guard'). Relative overrides and
44
+ * unresolvable paths are rejected outright (null => caching disabled).
45
+ */
46
+ export declare function resolveCacheRoot(cwd: string, env?: NodeJS.ProcessEnv): string | null;
47
+ /** Tier (a): per-file complexity entry key = sha256(fileContent) + provider version, plus optional changed-file scope. */
48
+ export declare function complexityFileKey(fileContent: string, providerVersion: string, changedFilesHash?: string): string;
49
+ /** Tier (b): per-run coverage entry key = coverage artifact hash + ':' + provider version. */
50
+ export declare function coverageEntryKey(coverageHash: string, providerVersion: string): string;
51
+ /** Whole-run shard: sha256 over canonical JSON, sliced to 12 hex chars for the filename. */
52
+ export declare function runShardKey(inputs: RunKeyInputs): string;
53
+ /**
54
+ * Lookup `key` in the cache; on miss (or any uncertainty) run `compute`,
55
+ * write through, and return the computed value with `hit: false`.
56
+ * Value must be JSON-serializable (the cache stores `{key, value}` as JSON).
57
+ * Never throws on cache IO; `compute` errors propagate to the caller.
58
+ */
59
+ export declare function getOrCompute<T>(cwd: string, key: CacheKeyInput, compute: () => T | Promise<T>): Promise<CacheLookup<T>>;
60
+ /** Wipe the resolved cache dir. Returns false when the root is unusable. */
61
+ export declare function clear(cwd: string, env?: NodeJS.ProcessEnv): Promise<boolean>;
62
+ type CoverageMapValue = NonNullable<CoverageResult['coverageMap']> extends Map<string, infer V> ? V : never;
63
+ /** Coverage cache payload: CoverageResult with the Map serialized to entries. */
64
+ export interface CachedCoverageValue extends Omit<CoverageResult, 'coverageMap'> {
65
+ coverageEntries: [string, CoverageMapValue][] | null;
66
+ }
67
+ export declare function getCacheWarnings(): readonly string[];
68
+ export declare function clearCacheWarnings(): void;
69
+ export declare function registerCachedProviders(): void;
70
+ export {};