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.
- package/LICENSE +21 -0
- package/README.md +150 -0
- package/dist/attribution.d.ts +19 -0
- package/dist/attribution.js +175 -0
- package/dist/auto-coverage.d.ts +8 -0
- package/dist/auto-coverage.js +93 -0
- package/dist/cache.d.ts +70 -0
- package/dist/cache.js +458 -0
- package/dist/cli.d.ts +51 -0
- package/dist/cli.js +810 -0
- package/dist/complexity-providers/pythonASTComplexityProvider.d.ts +9 -0
- package/dist/complexity-providers/pythonASTComplexityProvider.js +148 -0
- package/dist/complexity-providers/pythonDescriptorProvider.d.ts +17 -0
- package/dist/complexity-providers/pythonDescriptorProvider.js +119 -0
- package/dist/complexity-providers.d.ts +6 -0
- package/dist/complexity-providers.js +1 -0
- package/dist/complexity.d.ts +14 -0
- package/dist/complexity.js +75 -0
- package/dist/coverage-providers/lcovProvider.d.ts +12 -0
- package/dist/coverage-providers/lcovProvider.js +126 -0
- package/dist/coverage.d.ts +28 -0
- package/dist/coverage.js +451 -0
- package/dist/crap.d.ts +31 -0
- package/dist/crap.js +84 -0
- package/dist/crapCalc.d.ts +5 -0
- package/dist/crapCalc.js +11 -0
- package/dist/delta.d.ts +100 -0
- package/dist/delta.js +214 -0
- package/dist/evidence.d.ts +201 -0
- package/dist/evidence.js +906 -0
- package/dist/execute.d.ts +59 -0
- package/dist/execute.js +92 -0
- package/dist/formatters/github.d.ts +5 -0
- package/dist/formatters/github.js +27 -0
- package/dist/formatters/index.d.ts +47 -0
- package/dist/formatters/index.js +14 -0
- package/dist/formatters/junit.d.ts +5 -0
- package/dist/formatters/junit.js +32 -0
- package/dist/formatters/sarif.d.ts +5 -0
- package/dist/formatters/sarif.js +35 -0
- package/dist/fs-safety.d.ts +10 -0
- package/dist/fs-safety.js +47 -0
- package/dist/git.d.ts +50 -0
- package/dist/git.js +137 -0
- package/dist/help.d.ts +40 -0
- package/dist/help.js +274 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/providers/config.d.ts +41 -0
- package/dist/providers/config.js +172 -0
- package/dist/providers/genericCommand.d.ts +3 -0
- package/dist/providers/genericCommand.js +89 -0
- package/dist/providers/index.d.ts +7 -0
- package/dist/providers/index.js +4 -0
- package/dist/providers/prepare.d.ts +124 -0
- package/dist/providers/prepare.js +459 -0
- package/dist/providers/runner-detection.d.ts +30 -0
- package/dist/providers/runner-detection.js +207 -0
- package/dist/rules.d.ts +27 -0
- package/dist/rules.js +54 -0
- package/package.json +52 -0
package/dist/evidence.js
ADDED
|
@@ -0,0 +1,906 @@
|
|
|
1
|
+
import { evaluateHighCrap } from './rules.js';
|
|
2
|
+
import { collectComplexity } from './complexity.js';
|
|
3
|
+
import { readCoverage } from './coverage.js';
|
|
4
|
+
import { attachCoverage } from './attribution.js';
|
|
5
|
+
import { calculateCrap } from './crapCalc.js';
|
|
6
|
+
import { pythonASTComplexityProvider } from './complexity-providers/pythonASTComplexityProvider.js';
|
|
7
|
+
import { gitProvenance } from './git.js';
|
|
8
|
+
import { complexityProvenance } from './complexity.js';
|
|
9
|
+
import { coverageProvenance } from './coverage.js';
|
|
10
|
+
import { attributionProvenance } from './attribution.js';
|
|
11
|
+
import { crapCalcProvenance } from './crapCalc.js';
|
|
12
|
+
import { rulesProvenance } from './rules.js';
|
|
13
|
+
import { createHash } from 'node:crypto';
|
|
14
|
+
import { execFileSync } from 'node:child_process';
|
|
15
|
+
import { fileURLToPath } from 'node:url';
|
|
16
|
+
import { createRequire } from 'node:module';
|
|
17
|
+
import * as fs from 'fs';
|
|
18
|
+
import * as path from 'path';
|
|
19
|
+
import { loadProviderConfig, deriveRegistry, builtinConfig, createGenericCommandProvider } from './providers/index.js';
|
|
20
|
+
const requireFromEvidence = createRequire(import.meta.url);
|
|
21
|
+
// Self provenance; version mirrors package.json (existing codebase style hard-codes '0.5.0').
|
|
22
|
+
export const evidenceProvenance = { tool: 'checkchange', version: '0.4.0' };
|
|
23
|
+
function sha256Hex(content) {
|
|
24
|
+
return createHash('sha256').update(content).digest('hex');
|
|
25
|
+
}
|
|
26
|
+
// Engine identity for the evidence lineage stage: HEAD commit of the repo this
|
|
27
|
+
// code runs FROM (walk up from this module to its own .git — NOT cwd, which is
|
|
28
|
+
// the analyzed target repo). Deterministic; never throws.
|
|
29
|
+
let engineIdentityMemo;
|
|
30
|
+
function engineIdentity() {
|
|
31
|
+
if (engineIdentityMemo !== undefined)
|
|
32
|
+
return engineIdentityMemo;
|
|
33
|
+
const fallback = () => {
|
|
34
|
+
try {
|
|
35
|
+
// moduleDir is src/ or dist/; own package.json sits one level up
|
|
36
|
+
const moduleDir = path.dirname(fileURLToPath(import.meta.url));
|
|
37
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(moduleDir, '..', 'package.json'), 'utf8'));
|
|
38
|
+
return `${pkg.version}/${process.version}`;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return `${evidenceProvenance.version}/${process.version}`;
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
try {
|
|
45
|
+
let dir = path.dirname(fileURLToPath(import.meta.url));
|
|
46
|
+
for (;;) {
|
|
47
|
+
if (fs.existsSync(path.join(dir, '.git'))) {
|
|
48
|
+
const sha = execFileSync('git', ['rev-parse', 'HEAD'], {
|
|
49
|
+
cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore']
|
|
50
|
+
}).trim();
|
|
51
|
+
engineIdentityMemo = sha || fallback();
|
|
52
|
+
return engineIdentityMemo;
|
|
53
|
+
}
|
|
54
|
+
const parent = path.dirname(dir);
|
|
55
|
+
if (parent === dir) {
|
|
56
|
+
engineIdentityMemo = fallback();
|
|
57
|
+
return engineIdentityMemo;
|
|
58
|
+
}
|
|
59
|
+
dir = parent;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
engineIdentityMemo = fallback();
|
|
64
|
+
return engineIdentityMemo;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Builds diagnostics.quality from the per-run evidence state. Deterministic:
|
|
69
|
+
* every input is a values of the current run (capabilities, coverage usability,
|
|
70
|
+
* analyzed functions) — no timing, paths, or model judgment.
|
|
71
|
+
*/
|
|
72
|
+
function buildQuality(params) {
|
|
73
|
+
const stageComplete = {
|
|
74
|
+
git: true, // base resolved + intervals present; git failure handled upstream in cli.ts
|
|
75
|
+
complexity: params.complexityCapability !== 'failed',
|
|
76
|
+
coverage: params.coverageUsable,
|
|
77
|
+
attribution: params.attributionComplete === true,
|
|
78
|
+
rules: params.rulesComplete === true,
|
|
79
|
+
};
|
|
80
|
+
const weights = { git: 10, complexity: 20, coverage: 40, attribution: 20, rules: 10 };
|
|
81
|
+
const completeness = Object.keys(stageComplete)
|
|
82
|
+
.reduce((sum, s) => sum + (stageComplete[s] ? weights[s] : 0), 0);
|
|
83
|
+
const fns = params.changedFunctions ?? [];
|
|
84
|
+
const covered = fns.filter((f) => f.coverage !== null && f.coverage > 0).length;
|
|
85
|
+
const coverageRatio = fns.length === 0 ? 1 : covered / fns.length;
|
|
86
|
+
const score = stageComplete.coverage && stageComplete.attribution && stageComplete.rules
|
|
87
|
+
? Math.round(0.7 * completeness + 0.3 * 100 * coverageRatio)
|
|
88
|
+
: null;
|
|
89
|
+
const quality = {
|
|
90
|
+
coverage: params.coverageUsable ? 'DIRECT' : 'UNAVAILABLE',
|
|
91
|
+
complexity: stageComplete.complexity ? 'NATIVE' : 'UNAVAILABLE',
|
|
92
|
+
score,
|
|
93
|
+
stageComplete,
|
|
94
|
+
};
|
|
95
|
+
if (params.coverageUsable) {
|
|
96
|
+
quality.uncoveredFunctions = fns
|
|
97
|
+
.filter((f) => f.coverage === 0)
|
|
98
|
+
.map((f) => ({ file: f.file, method: f.method, lineStart: f.lineStart, lineEnd: f.lineEnd }));
|
|
99
|
+
}
|
|
100
|
+
return quality;
|
|
101
|
+
}
|
|
102
|
+
// ---- Diagnostics fingerprints (Experiment A task 5: optional diagnostics.fingerprints{}) ----
|
|
103
|
+
/**
|
|
104
|
+
* Deterministic function fingerprint: SHA-256 hex digest (64 lowercase chars)
|
|
105
|
+
* over the normalized function identity (relative file path + method +
|
|
106
|
+
* lineStart + lineEnd + cc). Inputs are analyzed run values only — no timing,
|
|
107
|
+
* no PIDs, no absolute paths — so identical runs produce identical hashes
|
|
108
|
+
* (evidence-contract.md:341). Normalization: repo-relative path with forward
|
|
109
|
+
* slashes (`\` → `/`), CRLF → LF line endings. Algorithm documented in
|
|
110
|
+
* docs/decisions/diagnostics-schema-design.md.
|
|
111
|
+
*/
|
|
112
|
+
function fingerprintFor(f) {
|
|
113
|
+
const file = f.file.split('\\').join('/');
|
|
114
|
+
const input = [file, f.method, f.lineStart, f.lineEnd, f.cc].join('\n').replace(/\r\n/g, '\n');
|
|
115
|
+
return sha256Hex(input);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Builds diagnostics.fingerprints, keyed by `file:method:lineStart` per
|
|
119
|
+
* diagnostics-schema-design.md. Covers changed functions only.
|
|
120
|
+
*/
|
|
121
|
+
function buildFingerprints(changedFunctions) {
|
|
122
|
+
const fingerprints = {};
|
|
123
|
+
for (const f of changedFunctions) {
|
|
124
|
+
fingerprints[`${f.file}:${f.method}:${f.lineStart}`] = fingerprintFor(f);
|
|
125
|
+
}
|
|
126
|
+
return fingerprints;
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Attaches optional diagnostics.{lineage,quality,fingerprints} to the output. When no
|
|
130
|
+
* lineage was collected, returns the output unchanged (byte-identical legacy
|
|
131
|
+
* behavior). fingerprints emitted only when non-empty. All values deterministic
|
|
132
|
+
* per evidence-contract.md:341.
|
|
133
|
+
*/
|
|
134
|
+
function withDiagnostics(output, lineage, quality, fingerprints) {
|
|
135
|
+
const fpEntries = fingerprints ? Object.keys(fingerprints).length : 0;
|
|
136
|
+
if (lineage.length === 0)
|
|
137
|
+
return output;
|
|
138
|
+
return {
|
|
139
|
+
...output,
|
|
140
|
+
diagnostics: { lineage, quality, ...(fpEntries > 0 ? { fingerprints } : {}) },
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
const providers = new Map();
|
|
144
|
+
export function registerProvider(ext, factory) { providers.set(ext, factory); }
|
|
145
|
+
export function getProvider(ext) { return providers.get(ext); }
|
|
146
|
+
// ---- Config-driven provider registry ----
|
|
147
|
+
let _providerConfig = null;
|
|
148
|
+
let _providerRegistry = null;
|
|
149
|
+
let _extensionPriority = [];
|
|
150
|
+
let _supportedExtensions = null;
|
|
151
|
+
// ponytail: derived from builtinConfig() so defaults stay in sync with config
|
|
152
|
+
const _builtinDefaults = builtinConfig();
|
|
153
|
+
const DEFAULT_EXTENSION_PRIORITY = (() => {
|
|
154
|
+
const seen = new Set();
|
|
155
|
+
const out = [];
|
|
156
|
+
for (const entry of [..._builtinDefaults.providers].reverse()) {
|
|
157
|
+
for (const ext of entry.extensions) {
|
|
158
|
+
if (!seen.has(ext)) {
|
|
159
|
+
seen.add(ext);
|
|
160
|
+
out.push(ext);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return out;
|
|
165
|
+
})();
|
|
166
|
+
const DEFAULT_SUPPORTED_EXTENSIONS = new Set(_builtinDefaults.providers.flatMap((p) => p.extensions));
|
|
167
|
+
const DEFAULT_LANGUAGE_MAP = (() => {
|
|
168
|
+
const map = {};
|
|
169
|
+
for (const entry of _builtinDefaults.providers) {
|
|
170
|
+
for (const ext of entry.extensions) {
|
|
171
|
+
if (!map[ext])
|
|
172
|
+
map[ext] = entry.language;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return map;
|
|
176
|
+
})();
|
|
177
|
+
/** Load provider config and populate providers Map. Call once at startup. */
|
|
178
|
+
export function initProviderConfig(explicitPath, allowExternalConfig = false) {
|
|
179
|
+
const cwd = process.cwd();
|
|
180
|
+
// This opt-in authorizes config location only; runner identity remains independently guarded.
|
|
181
|
+
const { config, source } = loadProviderConfig(cwd, explicitPath, allowExternalConfig);
|
|
182
|
+
const registry = deriveRegistry(config, source);
|
|
183
|
+
_providerConfig = config;
|
|
184
|
+
_providerRegistry = registry;
|
|
185
|
+
// Derive extension priority from registry: reverse provider order so later providers
|
|
186
|
+
// (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
|
+
const seen = new Set();
|
|
189
|
+
_extensionPriority = [];
|
|
190
|
+
for (const entry of [...config.providers].reverse()) {
|
|
191
|
+
for (const ext of entry.extensions) {
|
|
192
|
+
if (!seen.has(ext)) {
|
|
193
|
+
seen.add(ext);
|
|
194
|
+
_extensionPriority.push(ext);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
// Populate providers Map from registry
|
|
199
|
+
providers.clear();
|
|
200
|
+
for (const [ext, resolved] of registry) {
|
|
201
|
+
const generic = createGenericCommandProvider(resolved, cwd);
|
|
202
|
+
if (generic) {
|
|
203
|
+
registerProvider(ext, {
|
|
204
|
+
collectComplexity: (cwd) => generic.collectComplexity(cwd),
|
|
205
|
+
readCoverage: (...args) => readCoverage(...args),
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
else if (resolved.language === 'typescript') {
|
|
209
|
+
// Builtin TS provider: delegation preserves vi.spyOn mocks
|
|
210
|
+
registerProvider(ext, {
|
|
211
|
+
collectComplexity: (...args) => collectComplexity(...args),
|
|
212
|
+
readCoverage: (...args) => readCoverage(...args),
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
else if (resolved.language === 'python') {
|
|
216
|
+
registerProvider(ext, {
|
|
217
|
+
collectComplexity: (...args) => pythonASTComplexityProvider.collectComplexity(...args),
|
|
218
|
+
readCoverage: (...args) => readCoverage(...args),
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
_supportedExtensions = new Set(registry.keys());
|
|
223
|
+
rebuildLanguageMap();
|
|
224
|
+
return { config, registry, source };
|
|
225
|
+
}
|
|
226
|
+
/** Extension priority list (derived from config). Lazily falls back to hardcoded defaults. */
|
|
227
|
+
export function extensionPriority() {
|
|
228
|
+
if (_extensionPriority.length > 0)
|
|
229
|
+
return _extensionPriority;
|
|
230
|
+
// ponytail: lazy init with hardcoded priority when initProviderConfig() not called
|
|
231
|
+
_extensionPriority = [...DEFAULT_EXTENSION_PRIORITY];
|
|
232
|
+
return _extensionPriority;
|
|
233
|
+
}
|
|
234
|
+
/** Supported extensions set (derived from config). Lazily falls back to hardcoded defaults. */
|
|
235
|
+
export function supportedExtensions() {
|
|
236
|
+
if (_supportedExtensions)
|
|
237
|
+
return _supportedExtensions;
|
|
238
|
+
// ponytail: lazy init with hardcoded set when initProviderConfig() not called
|
|
239
|
+
_supportedExtensions = new Set(DEFAULT_SUPPORTED_EXTENSIONS);
|
|
240
|
+
return _supportedExtensions;
|
|
241
|
+
}
|
|
242
|
+
/** Loaded provider config (or null if not initialized). */
|
|
243
|
+
export function providerConfig() { return _providerConfig; }
|
|
244
|
+
/** Loaded provider registry (or null if not initialized). */
|
|
245
|
+
export function providerRegistry() { return _providerRegistry; }
|
|
246
|
+
/** Get the language for a file from the loaded registry. Falls back to hardcoded defaults. */
|
|
247
|
+
export function getLanguageForFile(filePath) {
|
|
248
|
+
const map = Object.keys(LANGUAGE_MAP).length > 0 ? LANGUAGE_MAP : DEFAULT_LANGUAGE_MAP;
|
|
249
|
+
const ext = Object.keys(map).find((key) => filePath.endsWith(key));
|
|
250
|
+
return ext ? map[ext] : undefined;
|
|
251
|
+
}
|
|
252
|
+
// Derive LANGUAGE_MAP from loaded config (or fallback to builtin defaults)
|
|
253
|
+
let LANGUAGE_MAP = {};
|
|
254
|
+
function rebuildLanguageMap() {
|
|
255
|
+
LANGUAGE_MAP = {};
|
|
256
|
+
const registry = _providerRegistry;
|
|
257
|
+
if (!registry)
|
|
258
|
+
return;
|
|
259
|
+
for (const [ext, resolved] of registry) {
|
|
260
|
+
if (!LANGUAGE_MAP[ext])
|
|
261
|
+
LANGUAGE_MAP[ext] = resolved.language;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Checks whether intervals contain only non-supported file types.
|
|
266
|
+
* Returns true only when intervals is non-empty AND every file has an unsupported extension.
|
|
267
|
+
* ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity.
|
|
268
|
+
*/
|
|
269
|
+
export function isUnsupportedIntervals(intervals) {
|
|
270
|
+
if (intervals.size === 0) {
|
|
271
|
+
return false; // empty intervals -> not unsupported (could be no changes)
|
|
272
|
+
}
|
|
273
|
+
const supported = supportedExtensions();
|
|
274
|
+
for (const [filePath] of intervals) {
|
|
275
|
+
const ext = filePath.slice(filePath.lastIndexOf('.'));
|
|
276
|
+
if (supported.has(ext))
|
|
277
|
+
return false;
|
|
278
|
+
}
|
|
279
|
+
return true; // all files are non-supported and intervals non-empty
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Builds the coverage lineage inputs object (deterministic, no timing).
|
|
283
|
+
* Handles absolute path → relative conversion, absent coverage hash sentinel,
|
|
284
|
+
* and coverage quality vocabulary (DIRECT / UNAVAILABLE).
|
|
285
|
+
*/
|
|
286
|
+
export function buildCoverageLineageInputs(coverageFile, cwd, coverageResult, errorReason) {
|
|
287
|
+
return {
|
|
288
|
+
// Input identity: relative coverage path only (security: no absolute paths in diagnostics)
|
|
289
|
+
...(coverageFile !== undefined && coverageFile !== '' ? {
|
|
290
|
+
coverageFile: path.isAbsolute(coverageFile) ? path.relative(cwd, coverageFile) : coverageFile
|
|
291
|
+
} : {}),
|
|
292
|
+
available: coverageResult.available,
|
|
293
|
+
error: coverageResult.error,
|
|
294
|
+
...(errorReason !== undefined ? { reason: errorReason } : {}),
|
|
295
|
+
// Input identity: sha256 of artifact bytes when read succeeded; sentinel otherwise
|
|
296
|
+
coverageHash: coverageResult.contentSha256
|
|
297
|
+
?? (coverageResult.error ? `malformed:${errorReason ?? 'malformed'}` : 'absent'),
|
|
298
|
+
// Canonical vocabulary (ADR-0001): measured from artifact => DIRECT, else UNAVAILABLE
|
|
299
|
+
quality: coverageResult.error || !coverageResult.available ? 'UNAVAILABLE' : 'DIRECT'
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
// ---- Extracted helper: extension detection ----
|
|
303
|
+
// ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity;
|
|
304
|
+
// priority order derived from config (default: .py > .tsx > .jsx > .js).
|
|
305
|
+
export function detectExtension(intervals) {
|
|
306
|
+
const priority = extensionPriority();
|
|
307
|
+
const supported = supportedExtensions();
|
|
308
|
+
// Collect which extensions are present
|
|
309
|
+
const present = new Set();
|
|
310
|
+
for (const [filePath] of intervals) {
|
|
311
|
+
let ext = filePath.slice(filePath.lastIndexOf('.'));
|
|
312
|
+
// ponytail: normalize .mjs/.cjs → .js for detection
|
|
313
|
+
if (ext === '.mjs' || ext === '.cjs')
|
|
314
|
+
ext = '.js';
|
|
315
|
+
if (supported.has(ext))
|
|
316
|
+
present.add(ext);
|
|
317
|
+
}
|
|
318
|
+
// Return first extension in priority order that's present
|
|
319
|
+
for (const ext of priority) {
|
|
320
|
+
if (present.has(ext))
|
|
321
|
+
return ext;
|
|
322
|
+
}
|
|
323
|
+
// Fallback: default to '.ts' when no supported extension found
|
|
324
|
+
return '.ts';
|
|
325
|
+
}
|
|
326
|
+
// ---- Extracted helper: gate + completeness from rule results ----
|
|
327
|
+
export function computeGateAndCompleteness(ruleResults) {
|
|
328
|
+
const hasWarn = ruleResults.some((r) => r.result === 'WARN');
|
|
329
|
+
const hasNotEvaluated = ruleResults.some((r) => r.result === 'NOT_EVALUATED');
|
|
330
|
+
return {
|
|
331
|
+
gate: hasWarn ? 'WARN' : 'PASS',
|
|
332
|
+
completeness: hasNotEvaluated ? 'INCOMPLETE' : 'COMPLETE',
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
function packageRoots(cwd, filePath) {
|
|
336
|
+
const root = path.resolve(cwd);
|
|
337
|
+
const roots = [];
|
|
338
|
+
let dir = path.dirname(path.resolve(cwd, filePath));
|
|
339
|
+
for (;;) {
|
|
340
|
+
const relative = path.relative(root, dir);
|
|
341
|
+
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative))
|
|
342
|
+
break;
|
|
343
|
+
roots.push(dir);
|
|
344
|
+
if (dir === root)
|
|
345
|
+
return roots;
|
|
346
|
+
dir = path.dirname(dir);
|
|
347
|
+
}
|
|
348
|
+
return [...roots, root];
|
|
349
|
+
}
|
|
350
|
+
// ponytail: nearest-wins. roots are ordered file-dir → cwd, so the FIRST
|
|
351
|
+
// package.json that declares next or react decides. A declared dependency in the
|
|
352
|
+
// analyzed tree is stronger evidence than anything resolvable outside it.
|
|
353
|
+
function nearestFrameworkDep(roots) {
|
|
354
|
+
for (const root of roots) {
|
|
355
|
+
let pkg;
|
|
356
|
+
try {
|
|
357
|
+
pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
continue; /* no package.json or parse error */
|
|
361
|
+
}
|
|
362
|
+
if (!pkg)
|
|
363
|
+
continue;
|
|
364
|
+
const declares = (d) => !!(pkg.dependencies?.[d] || pkg.devDependencies?.[d] || pkg.peerDependencies?.[d]);
|
|
365
|
+
if (declares('next'))
|
|
366
|
+
return 'next';
|
|
367
|
+
if (declares('react'))
|
|
368
|
+
return 'react';
|
|
369
|
+
}
|
|
370
|
+
return undefined;
|
|
371
|
+
}
|
|
372
|
+
function detectNextFramework(cwd, filePath) {
|
|
373
|
+
const roots = packageRoots(cwd, filePath);
|
|
374
|
+
// 1. Nearest declared dependency inside the analyzed package chain wins.
|
|
375
|
+
const declared = nearestFrameworkDep(roots);
|
|
376
|
+
if (declared)
|
|
377
|
+
return declared;
|
|
378
|
+
// 2. Installed presence — only when NO package.json in the chain declares
|
|
379
|
+
// next/react, AND the resolved copy lives INSIDE the analyzed tree.
|
|
380
|
+
// `paths` only sets where the walk STARTS; Node still ascends from each
|
|
381
|
+
// root to the filesystem root, so without this gate a machine-global
|
|
382
|
+
// node_modules above the repo labels every function 'next'. An escaped
|
|
383
|
+
// hit is ignored: the ladder continues to config/markers/walk.
|
|
384
|
+
// ponytail: realpath both sides so `..`/symlink prefixes can't sneak past.
|
|
385
|
+
try {
|
|
386
|
+
const hit = requireFromEvidence.resolve('next/package.json', { paths: roots });
|
|
387
|
+
const real = fs.realpathSync(hit);
|
|
388
|
+
if ([cwd, ...roots].some((r) => real.startsWith(fs.realpathSync(r) + path.sep)))
|
|
389
|
+
return 'next';
|
|
390
|
+
}
|
|
391
|
+
catch { /* not installed, or resolved outside the analyzed tree */ }
|
|
392
|
+
// 3. next.config.* at each package root
|
|
393
|
+
const configNames = ['next.config.js', 'next.config.mjs', 'next.config.ts'];
|
|
394
|
+
for (const root of roots) {
|
|
395
|
+
for (const name of configNames) {
|
|
396
|
+
if (fs.existsSync(path.join(root, name)))
|
|
397
|
+
return 'next';
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
// 4. App Router markers
|
|
401
|
+
const appMarkers = ['app/page.tsx', 'app/layout.tsx'];
|
|
402
|
+
for (const root of roots) {
|
|
403
|
+
for (const marker of appMarkers) {
|
|
404
|
+
if (fs.existsSync(path.join(root, marker)))
|
|
405
|
+
return 'next';
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
// 5. Bounded scan for app/**/route.ts
|
|
409
|
+
const appDir = path.resolve(cwd, 'app');
|
|
410
|
+
if (fs.existsSync(appDir)) {
|
|
411
|
+
const routeFiles = walkDirBounded(appDir, 0)
|
|
412
|
+
.filter((f) => f.endsWith('route.ts') || f.endsWith('route.tsx'));
|
|
413
|
+
if (routeFiles.length > 0)
|
|
414
|
+
return 'next';
|
|
415
|
+
}
|
|
416
|
+
// 6. Pages Router markers
|
|
417
|
+
const pagesDir = path.resolve(cwd, 'pages');
|
|
418
|
+
if (fs.existsSync(pagesDir)) {
|
|
419
|
+
const pageFiles = walkDirBounded(pagesDir, 0)
|
|
420
|
+
.filter((f) => f.endsWith('.tsx') || f.endsWith('.ts'));
|
|
421
|
+
if (pageFiles.length > 0)
|
|
422
|
+
return 'next';
|
|
423
|
+
}
|
|
424
|
+
// 7. React fallback
|
|
425
|
+
// The old packageHasDependency(roots,'react') probe is gone: step 1 already
|
|
426
|
+
// returned if any package.json in the chain declares react, so it was dead.
|
|
427
|
+
if (filePath.endsWith('.jsx'))
|
|
428
|
+
return 'react';
|
|
429
|
+
return undefined;
|
|
430
|
+
}
|
|
431
|
+
// ponytail: extracted walkDir into standalone fn to avoid nested function inside detectNextFramework
|
|
432
|
+
function walkDirBounded(dir, depth) {
|
|
433
|
+
if (depth > 3)
|
|
434
|
+
return [];
|
|
435
|
+
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
436
|
+
let files = [];
|
|
437
|
+
for (const entry of entries) {
|
|
438
|
+
const fullPath = path.join(dir, entry.name);
|
|
439
|
+
if (entry.isDirectory()) {
|
|
440
|
+
files = files.concat(walkDirBounded(fullPath, depth + 1));
|
|
441
|
+
}
|
|
442
|
+
else {
|
|
443
|
+
files.push(fullPath);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
return files;
|
|
447
|
+
}
|
|
448
|
+
export function enrichWithLanguageAndFramework(changedFunctions, cwd) {
|
|
449
|
+
return changedFunctions.map((fn) => {
|
|
450
|
+
const lang = getLanguageForFile(fn.file);
|
|
451
|
+
const fw = detectNextFramework(cwd, fn.file);
|
|
452
|
+
return {
|
|
453
|
+
...fn,
|
|
454
|
+
...(lang !== undefined ? { language: lang } : {}),
|
|
455
|
+
...(fw ? { framework: fw } : {}),
|
|
456
|
+
};
|
|
457
|
+
});
|
|
458
|
+
}
|
|
459
|
+
// ---- Extracted helper: coverage read with provider dispatch ----
|
|
460
|
+
// ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity;
|
|
461
|
+
// the original inline try/catch had 3 branches (error → failed, absent, catch → malformed).
|
|
462
|
+
export async function readCoverageWithProvider(detectedExtension, cwd, coverageFile, trace, autoGenerated) {
|
|
463
|
+
const t0 = Date.now();
|
|
464
|
+
let result;
|
|
465
|
+
let capability = 'available';
|
|
466
|
+
let errorReason;
|
|
467
|
+
try {
|
|
468
|
+
const provider = providers.get(detectedExtension);
|
|
469
|
+
if (provider) {
|
|
470
|
+
result = await provider.readCoverage(cwd, coverageFile, trace, autoGenerated);
|
|
471
|
+
}
|
|
472
|
+
else {
|
|
473
|
+
result = await readCoverage(cwd, coverageFile, trace, autoGenerated);
|
|
474
|
+
}
|
|
475
|
+
if (result.error) {
|
|
476
|
+
capability = 'failed';
|
|
477
|
+
errorReason = result.reason;
|
|
478
|
+
}
|
|
479
|
+
if (!result.available && !result.error) {
|
|
480
|
+
capability = 'absent';
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
catch {
|
|
484
|
+
capability = 'failed';
|
|
485
|
+
errorReason = 'malformed';
|
|
486
|
+
result = { available: false, coverageMap: null, error: true, reason: 'malformed' };
|
|
487
|
+
}
|
|
488
|
+
return { result, capability, errorReason, elapsed: Date.now() - t0 };
|
|
489
|
+
}
|
|
490
|
+
// ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity.
|
|
491
|
+
// Handles the empty-intervals early return (vacuous-PASS ban §5).
|
|
492
|
+
// Reads coverage so coverageErrorReason survives — INV-02/INV-03 MISSING≠MALFORMED.
|
|
493
|
+
async function emptyIntervalsReturn(base, threshold, detectedExtension, cwd, coverageFile, trace, autoGenerated, gitCapability, lineage) {
|
|
494
|
+
const t0CovEarly = Date.now();
|
|
495
|
+
const covEarly = await readCoverageWithProvider(detectedExtension, cwd, coverageFile, trace, autoGenerated);
|
|
496
|
+
if (trace)
|
|
497
|
+
trace.recordStage('coverage', Date.now() - t0CovEarly, covEarly.result.error ? 'error' : covEarly.result.available ? 'ok' : 'skipped');
|
|
498
|
+
lineage.push({
|
|
499
|
+
stage: 'coverage',
|
|
500
|
+
...coverageProvenance,
|
|
501
|
+
inputs: buildCoverageLineageInputs(coverageFile, cwd, covEarly.result, covEarly.errorReason),
|
|
502
|
+
});
|
|
503
|
+
// Empty intervals → UNSUPPORTED always. coverageErrorReason recorded
|
|
504
|
+
// for diagnostics but does NOT change analysisStatus (vacuous-PASS ban).
|
|
505
|
+
return withDiagnostics({
|
|
506
|
+
schemaVersion: '0.5',
|
|
507
|
+
analysis: { base, target: 'current' },
|
|
508
|
+
capabilities: {
|
|
509
|
+
git: gitCapability,
|
|
510
|
+
complexity: 'unavailable',
|
|
511
|
+
coverageArtifact: covEarly.capability === 'failed' ? 'failed' : 'unavailable'
|
|
512
|
+
},
|
|
513
|
+
changedFunctions: [],
|
|
514
|
+
ruleResults: [],
|
|
515
|
+
policy: { crapThreshold: threshold },
|
|
516
|
+
analysisStatus: 'UNSUPPORTED',
|
|
517
|
+
gate: 'NOT_EVALUATED',
|
|
518
|
+
completeness: 'INCOMPLETE',
|
|
519
|
+
...(covEarly.errorReason !== undefined ? { coverageErrorReason: covEarly.errorReason } : {})
|
|
520
|
+
}, lineage, buildQuality({ complexityCapability: 'unavailable', coverageUsable: false }));
|
|
521
|
+
}
|
|
522
|
+
// ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity.
|
|
523
|
+
// §5 vacuous-PASS ban: coverage absent + needs coverage → NOT_EVALUATED gate.
|
|
524
|
+
// preserve ZERO!=NULL MISSING!=MALFORMED: absent ≠ failed, not conflated.
|
|
525
|
+
function applyAbsentCoverageGate(currentGate, coverageCapability, changedFunctionsCount) {
|
|
526
|
+
if (coverageCapability === 'absent' && changedFunctionsCount > 0) {
|
|
527
|
+
return 'NOT_EVALUATED';
|
|
528
|
+
}
|
|
529
|
+
return currentGate;
|
|
530
|
+
}
|
|
531
|
+
// ---- Extracted helper: map attributed complexity → MethodEvidence array ----
|
|
532
|
+
// ponytail: extracted from buildEvidenceOutput; pure transformation, no side effects.
|
|
533
|
+
export function mapToMethodEvidence(attributedComplexity) {
|
|
534
|
+
return attributedComplexity.map((ac) => ({
|
|
535
|
+
file: ac.info.file,
|
|
536
|
+
method: ac.info.method,
|
|
537
|
+
lineStart: ac.info.lineStart,
|
|
538
|
+
lineEnd: ac.info.lineEnd,
|
|
539
|
+
cc: ac.info.cc,
|
|
540
|
+
crap: calculateCrap(ac.info.cc, ac.coveragePercent),
|
|
541
|
+
coverage: ac.coveragePercent,
|
|
542
|
+
coverageKind: ac.coverageKind ?? 'N/A',
|
|
543
|
+
analyzerStatus: (ac.coveragePercent !== null && ac.coveragePercent !== undefined ? 'passed' : 'skipped'),
|
|
544
|
+
source: { tool: '@barney-media/crap-typescript-core', version: '0.5.0' },
|
|
545
|
+
}));
|
|
546
|
+
}
|
|
547
|
+
export function correlate(methodEvidence, intervals) {
|
|
548
|
+
const changedFunctions = [];
|
|
549
|
+
for (const evidence of methodEvidence) {
|
|
550
|
+
const fileIntervals = intervals.get(evidence.file);
|
|
551
|
+
if (!fileIntervals) {
|
|
552
|
+
// No changes in this file, skip
|
|
553
|
+
continue;
|
|
554
|
+
}
|
|
555
|
+
// Check for overlap with any interval in this file
|
|
556
|
+
let isChanged = false;
|
|
557
|
+
for (const interval of fileIntervals) {
|
|
558
|
+
// Integer overlap logic: methodStart <= intervalEnd AND intervalStart <= methodEnd
|
|
559
|
+
if (evidence.lineStart <= interval.end && interval.start <= evidence.lineEnd) {
|
|
560
|
+
isChanged = true;
|
|
561
|
+
break;
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
if (isChanged) {
|
|
565
|
+
changedFunctions.push({
|
|
566
|
+
file: evidence.file,
|
|
567
|
+
method: evidence.method,
|
|
568
|
+
lineStart: evidence.lineStart,
|
|
569
|
+
lineEnd: evidence.lineEnd,
|
|
570
|
+
cc: evidence.cc,
|
|
571
|
+
crap: evidence.crap,
|
|
572
|
+
coverage: evidence.coverage,
|
|
573
|
+
coverageKind: evidence.coverageKind,
|
|
574
|
+
analyzerStatus: evidence.analyzerStatus,
|
|
575
|
+
source: evidence.source
|
|
576
|
+
? { tool: evidence.source.tool, version: evidence.source.version }
|
|
577
|
+
: { tool: '@barney-media/crap-typescript', version: '0.5.0' },
|
|
578
|
+
});
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
return changedFunctions;
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* Legacy buildOutput for WP3 tests (schema 0.1, sync). Kept for backward compatibility.
|
|
585
|
+
*/
|
|
586
|
+
export function buildOutput(base, changed, threshold = 30, capabilities = { git: 'available' }) {
|
|
587
|
+
const ruleResults = evaluateHighCrap(changed, threshold);
|
|
588
|
+
const gate = ruleResults.some((r) => r.result === 'WARN') ? 'WARN' : 'PASS';
|
|
589
|
+
const completeness = ruleResults.some((r) => r.result === 'NOT_EVALUATED') ? 'INCOMPLETE' : 'COMPLETE';
|
|
590
|
+
const caps = {
|
|
591
|
+
git: capabilities.git ?? 'available',
|
|
592
|
+
crapTypescript: capabilities.crapTypescript ?? 'available',
|
|
593
|
+
};
|
|
594
|
+
// For backward compat, only return old capability keys unless new ones explicitly passed
|
|
595
|
+
if (capabilities.complexity)
|
|
596
|
+
caps.complexity = capabilities.complexity;
|
|
597
|
+
if (capabilities.coverageArtifact)
|
|
598
|
+
caps.coverageArtifact = capabilities.coverageArtifact;
|
|
599
|
+
return {
|
|
600
|
+
schemaVersion: '0.1',
|
|
601
|
+
analysis: { base, target: 'current' },
|
|
602
|
+
capabilities: caps,
|
|
603
|
+
changedFunctions: changed,
|
|
604
|
+
policy: { crapThreshold: threshold },
|
|
605
|
+
ruleResults,
|
|
606
|
+
gate,
|
|
607
|
+
completeness,
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Handles coverage-failure resolution. Mutates state in place; returns early-return
|
|
612
|
+
* output when analysis should stop, or null to continue.
|
|
613
|
+
* ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity.
|
|
614
|
+
*/
|
|
615
|
+
function resolveCoverageFailure(coverageCapability, coverageErrorReason, autoGenerated, base, gitCapability, complexityCapability, threshold, lineage, complexityCapabilityForQuality) {
|
|
616
|
+
let analysisStatus = 'SUCCESS';
|
|
617
|
+
let gate = null;
|
|
618
|
+
let completeness = 'COMPLETE';
|
|
619
|
+
if (coverageCapability === 'failed') {
|
|
620
|
+
if (autoGenerated) {
|
|
621
|
+
return { earlyReturn: null, coverageCapability: 'absent', coverageErrorReason: undefined, analysisStatus, gate, completeness };
|
|
622
|
+
}
|
|
623
|
+
else {
|
|
624
|
+
analysisStatus = 'FAILED';
|
|
625
|
+
completeness = 'INCOMPLETE';
|
|
626
|
+
return {
|
|
627
|
+
earlyReturn: withDiagnostics(buildFailedOutput(base, gitCapability, complexityCapability, 'failed', threshold, coverageErrorReason), lineage, buildQuality({ complexityCapability: complexityCapabilityForQuality, coverageUsable: false })),
|
|
628
|
+
coverageCapability: 'failed', coverageErrorReason, analysisStatus, gate, completeness
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
return { earlyReturn: null, coverageCapability, coverageErrorReason, analysisStatus, gate, completeness };
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Wraps attribution attachment with timing and error handling.
|
|
636
|
+
* Returns either the attributed complexity or an early-return output on failure.
|
|
637
|
+
* ponytail: extracted from buildEvidenceOutput to reduce cyclomatic complexity.
|
|
638
|
+
*/
|
|
639
|
+
async function attachCoverageWithTracking(complexityInfo, coverageResult, trace, lineage, base, gitCapability, complexityCapability, coverageCapability, threshold, coverageErrorReason) {
|
|
640
|
+
const t0 = Date.now();
|
|
641
|
+
try {
|
|
642
|
+
const attributedComplexity = await attachCoverage(complexityInfo, coverageResult);
|
|
643
|
+
if (trace)
|
|
644
|
+
trace.recordStage('attribution', Date.now() - t0, 'ok');
|
|
645
|
+
lineage.push({
|
|
646
|
+
stage: 'attribution',
|
|
647
|
+
...attributionProvenance,
|
|
648
|
+
inputs: {
|
|
649
|
+
methods: attributedComplexity.length,
|
|
650
|
+
quality: coverageResult.available && !coverageResult.error ? 'ATTRIBUTED' : 'UNAVAILABLE'
|
|
651
|
+
}
|
|
652
|
+
});
|
|
653
|
+
return { attributedComplexity };
|
|
654
|
+
}
|
|
655
|
+
catch {
|
|
656
|
+
if (trace)
|
|
657
|
+
trace.recordStage('attribution', Date.now() - t0, 'error');
|
|
658
|
+
return {
|
|
659
|
+
attributedComplexity: [],
|
|
660
|
+
earlyReturn: withDiagnostics(buildFailedOutput(base, gitCapability, complexityCapability, coverageCapability, threshold, coverageErrorReason), lineage, buildQuality({ complexityCapability, coverageUsable: !coverageResult.error && coverageResult.available === true }))
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Builds the final JSON output using composed evidence.
|
|
666
|
+
* @param base The base reference used for comparison
|
|
667
|
+
* @param intervals Map from file path to array of changed intervals (from git)
|
|
668
|
+
* @param cwd Current working directory
|
|
669
|
+
* @param threshold CRAP threshold for evaluating changed functions
|
|
670
|
+
* @returns Promise<OutputJson>
|
|
671
|
+
*/
|
|
672
|
+
export async function buildEvidenceOutput(base, intervals, cwd, threshold = 30, coverageFile, trace, autoGenerated) {
|
|
673
|
+
// We'll assume that the git repo is valid and the base is resolved (done by cli.ts)
|
|
674
|
+
// We'll set the git capability to 'available' (if we got here, git is working)
|
|
675
|
+
const gitCapability = 'available';
|
|
676
|
+
// Diagnostics lineage collection (deterministic; inputs record identity, never timing)
|
|
677
|
+
const lineage = [];
|
|
678
|
+
lineage.push({
|
|
679
|
+
stage: 'git',
|
|
680
|
+
...gitProvenance,
|
|
681
|
+
inputs: {
|
|
682
|
+
base,
|
|
683
|
+
diff: 'git diff --unified=0 <resolvedBase>',
|
|
684
|
+
fileCount: intervals.size,
|
|
685
|
+
// Input identity hash over the parsed diff intervals (node:crypto, no new deps)
|
|
686
|
+
intervalsSha256: sha256Hex(JSON.stringify(Array.from(intervals.entries())))
|
|
687
|
+
}
|
|
688
|
+
});
|
|
689
|
+
// Step 1: Collect complexity
|
|
690
|
+
const detectedExtension = detectExtension(intervals);
|
|
691
|
+
const changedFiles = new Set(intervals.keys());
|
|
692
|
+
const t0Complexity = Date.now();
|
|
693
|
+
let complexityInfo;
|
|
694
|
+
let complexityCapability = 'available';
|
|
695
|
+
try {
|
|
696
|
+
if (_providerRegistry === null) {
|
|
697
|
+
initProviderConfig();
|
|
698
|
+
}
|
|
699
|
+
const provider = getProvider(detectedExtension);
|
|
700
|
+
if (provider) {
|
|
701
|
+
complexityInfo = await provider.collectComplexity(cwd, trace, changedFiles);
|
|
702
|
+
}
|
|
703
|
+
else {
|
|
704
|
+
complexityInfo = await collectComplexity(cwd, trace, changedFiles);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
catch {
|
|
708
|
+
complexityCapability = 'failed';
|
|
709
|
+
// We'll still continue to try to get coverage? But if complexity fails, we set analysisStatus to UNSUPPORTED.
|
|
710
|
+
// We'll set complexityInfo to empty and continue.
|
|
711
|
+
complexityInfo = [];
|
|
712
|
+
}
|
|
713
|
+
if (trace)
|
|
714
|
+
trace.recordStage('complexity', Date.now() - t0Complexity, complexityCapability === 'failed' ? 'error' : 'ok');
|
|
715
|
+
lineage.push({
|
|
716
|
+
stage: 'complexity',
|
|
717
|
+
...complexityProvenance,
|
|
718
|
+
inputs: {
|
|
719
|
+
extension: detectedExtension,
|
|
720
|
+
functions: complexityInfo.length,
|
|
721
|
+
// Canonical vocabulary (ADR-0001): native analyzer present => NATIVE, failed => UNAVAILABLE
|
|
722
|
+
quality: complexityCapability === 'failed' ? 'UNAVAILABLE' : 'NATIVE'
|
|
723
|
+
}
|
|
724
|
+
});
|
|
725
|
+
// Vacuous-PASS ban (§5): no files in diff + no supported extensions →
|
|
726
|
+
// INCOMPLETE/NOT_EVALUATED, never PASS. ponytail: intervals.size===0 is
|
|
727
|
+
// the degenerate case where isUnsupportedIntervals returns false (by
|
|
728
|
+
// design), but the output must still be NOT_EVALUATED because there is
|
|
729
|
+
// nothing to analyze.
|
|
730
|
+
if (intervals.size === 0) {
|
|
731
|
+
return emptyIntervalsReturn(base, threshold, detectedExtension, cwd, coverageFile, trace, autoGenerated, gitCapability, lineage);
|
|
732
|
+
}
|
|
733
|
+
// Helper to check if intervals contain only non-supported files
|
|
734
|
+
// If intervals indicate unsupported source (non-code files only), return UNSUPPORTED
|
|
735
|
+
if (isUnsupportedIntervals(intervals)) {
|
|
736
|
+
return withDiagnostics({
|
|
737
|
+
schemaVersion: '0.5',
|
|
738
|
+
analysis: {
|
|
739
|
+
base: base,
|
|
740
|
+
target: 'current'
|
|
741
|
+
},
|
|
742
|
+
capabilities: {
|
|
743
|
+
git: gitCapability,
|
|
744
|
+
complexity: complexityCapability,
|
|
745
|
+
coverageArtifact: 'available'
|
|
746
|
+
},
|
|
747
|
+
changedFunctions: [],
|
|
748
|
+
ruleResults: [],
|
|
749
|
+
policy: {
|
|
750
|
+
crapThreshold: threshold
|
|
751
|
+
},
|
|
752
|
+
analysisStatus: 'UNSUPPORTED',
|
|
753
|
+
gate: null,
|
|
754
|
+
completeness: 'INCOMPLETE'
|
|
755
|
+
}, lineage, buildQuality({ complexityCapability, coverageUsable: false }));
|
|
756
|
+
}
|
|
757
|
+
// Step 2: Read coverage
|
|
758
|
+
const t0Coverage = Date.now();
|
|
759
|
+
const { result: coverageResult, capability: _covCapability, errorReason: _covErrorReason } = await readCoverageWithProvider(detectedExtension, cwd, coverageFile, trace, autoGenerated);
|
|
760
|
+
let coverageCapability = _covCapability;
|
|
761
|
+
let coverageErrorReason = _covErrorReason;
|
|
762
|
+
if (trace)
|
|
763
|
+
trace.recordStage('coverage', Date.now() - t0Coverage, coverageResult.error ? 'error' : coverageResult.available ? 'ok' : 'skipped');
|
|
764
|
+
lineage.push({
|
|
765
|
+
stage: 'coverage',
|
|
766
|
+
...coverageProvenance,
|
|
767
|
+
inputs: buildCoverageLineageInputs(coverageFile, cwd, coverageResult, coverageErrorReason),
|
|
768
|
+
});
|
|
769
|
+
// Determine analysisStatus, gate, and completeness based on provider failures
|
|
770
|
+
// If complexity provider failed -> unsupported source
|
|
771
|
+
if (complexityCapability === 'failed') {
|
|
772
|
+
const earlyReturn = withDiagnostics({
|
|
773
|
+
schemaVersion: '0.5',
|
|
774
|
+
analysis: {
|
|
775
|
+
base: base,
|
|
776
|
+
target: 'current'
|
|
777
|
+
},
|
|
778
|
+
capabilities: {
|
|
779
|
+
git: gitCapability,
|
|
780
|
+
complexity: complexityCapability,
|
|
781
|
+
coverageArtifact: coverageCapability
|
|
782
|
+
},
|
|
783
|
+
changedFunctions: [],
|
|
784
|
+
policy: {
|
|
785
|
+
crapThreshold: threshold
|
|
786
|
+
},
|
|
787
|
+
ruleResults: [],
|
|
788
|
+
analysisStatus: 'UNSUPPORTED',
|
|
789
|
+
gate: null,
|
|
790
|
+
completeness: 'NOT_APPLICABLE'
|
|
791
|
+
}, lineage, buildQuality({ complexityCapability, coverageUsable: false }));
|
|
792
|
+
return earlyReturn;
|
|
793
|
+
}
|
|
794
|
+
// If coverage provider failed (malformed)
|
|
795
|
+
const covRes = resolveCoverageFailure(coverageCapability, coverageErrorReason, autoGenerated, base, gitCapability, complexityCapability, threshold, lineage, complexityCapability);
|
|
796
|
+
if (covRes.earlyReturn)
|
|
797
|
+
return covRes.earlyReturn;
|
|
798
|
+
coverageCapability = covRes.coverageCapability;
|
|
799
|
+
coverageErrorReason = covRes.coverageErrorReason;
|
|
800
|
+
const analysisStatus = covRes.analysisStatus;
|
|
801
|
+
// Step 3: Attach coverage to complexity info
|
|
802
|
+
const attrResult = await attachCoverageWithTracking(complexityInfo, coverageResult, trace, lineage, base, gitCapability, complexityCapability, coverageCapability, threshold, coverageErrorReason);
|
|
803
|
+
if (attrResult.earlyReturn)
|
|
804
|
+
return attrResult.earlyReturn;
|
|
805
|
+
const attributedComplexity = attrResult.attributedComplexity;
|
|
806
|
+
// Step 4+5: Map attributed complexity → MethodEvidence (merged Steps 4+5 via mapToMethodEvidence)
|
|
807
|
+
const t0CrapCalc = Date.now();
|
|
808
|
+
const methodEvidence = mapToMethodEvidence(attributedComplexity);
|
|
809
|
+
lineage.push({ stage: 'crapCalc', ...crapCalcProvenance, inputs: { functions: methodEvidence.length } });
|
|
810
|
+
if (trace)
|
|
811
|
+
trace.recordStage('crapCalc', Date.now() - t0CrapCalc, 'ok');
|
|
812
|
+
// Step 6: Correlate with git intervals
|
|
813
|
+
const changedFunctions = correlate(methodEvidence, intervals);
|
|
814
|
+
// Step 7: Evaluate rule results (using the existing evaluateHighCrap from rules.js)
|
|
815
|
+
const t0Rules = Date.now();
|
|
816
|
+
const ruleResults = evaluateHighCrap(changedFunctions, threshold);
|
|
817
|
+
lineage.push({ stage: 'rules', ...rulesProvenance, inputs: { threshold, functions: changedFunctions.length } });
|
|
818
|
+
if (trace)
|
|
819
|
+
trace.recordStage('rules', Date.now() - t0Rules, 'ok');
|
|
820
|
+
// Step 8: Compute overall gate and completeness
|
|
821
|
+
let { gate: gateValue, completeness: completenessValue } = computeGateAndCompleteness(ruleResults);
|
|
822
|
+
// §5 vacuous-PASS ban: coverage absent + needs coverage → NOT_EVALUATED gate.
|
|
823
|
+
gateValue = applyAbsentCoverageGate(gateValue, coverageCapability, changedFunctions.length);
|
|
824
|
+
// Step 9: Determine analysisStatus
|
|
825
|
+
// If we have no relevant TS functions after successful analysis -> SUCCESS
|
|
826
|
+
// We'll check if we have any complexityInfo (from the provider) and if we have any changedFunctions?
|
|
827
|
+
// The spec says: If no relevant current TS functions after successful applicable analysis -> SUCCESS / PASS / COMPLETE
|
|
828
|
+
// We'll consider that if complexityInfo is empty (no TS functions found) then we are in this case.
|
|
829
|
+
// But note: we might have complexityInfo but no changedFunctions (if no changes in any function). That is still SUCCESS if we have functions.
|
|
830
|
+
// We'll set analysisStatus to SUCCESS if we have not already set it to FAILED.
|
|
831
|
+
if (analysisStatus === 'SUCCESS') {
|
|
832
|
+
// We'll keep it as SUCCESS unless we have a reason to set to UNSUPPORTED?
|
|
833
|
+
// The spec says: Unsupported source/change -> UNSUPPORTED / null / NOT_APPLICABLE
|
|
834
|
+
// We don't have a way to detect unsupported source yet. We'll assume it's supported.
|
|
835
|
+
// We'll leave analysisStatus as SUCCESS.
|
|
836
|
+
}
|
|
837
|
+
// Step 10: Enrich with language/framework and return
|
|
838
|
+
const t0Evidence = Date.now();
|
|
839
|
+
const changedFunctionsWithLanguage = enrichWithLanguageAndFramework(changedFunctions, cwd);
|
|
840
|
+
lineage.push({
|
|
841
|
+
stage: 'evidence',
|
|
842
|
+
...evidenceProvenance,
|
|
843
|
+
inputs: {
|
|
844
|
+
base,
|
|
845
|
+
threshold,
|
|
846
|
+
changedFunctions: changedFunctionsWithLanguage.length,
|
|
847
|
+
ruleResults: ruleResults.length,
|
|
848
|
+
// Engine identity: HEAD commit of the repo running the analysis (cache key input)
|
|
849
|
+
engine: engineIdentity()
|
|
850
|
+
}
|
|
851
|
+
});
|
|
852
|
+
// Tracing seam: stage spans recorded only into the in-memory trace run —
|
|
853
|
+
// never into the deterministic EvidenceOutput returned below.
|
|
854
|
+
if (trace)
|
|
855
|
+
trace.recordStage('evidence', Date.now() - t0Evidence, 'ok');
|
|
856
|
+
return withDiagnostics({
|
|
857
|
+
schemaVersion: '0.5',
|
|
858
|
+
analysis: {
|
|
859
|
+
base: base,
|
|
860
|
+
target: 'current'
|
|
861
|
+
},
|
|
862
|
+
capabilities: {
|
|
863
|
+
git: gitCapability,
|
|
864
|
+
complexity: complexityCapability,
|
|
865
|
+
coverageArtifact: coverageCapability
|
|
866
|
+
},
|
|
867
|
+
changedFunctions: changedFunctionsWithLanguage,
|
|
868
|
+
policy: {
|
|
869
|
+
crapThreshold: threshold
|
|
870
|
+
},
|
|
871
|
+
ruleResults: ruleResults,
|
|
872
|
+
analysisStatus: analysisStatus,
|
|
873
|
+
gate: gateValue,
|
|
874
|
+
completeness: completenessValue
|
|
875
|
+
}, lineage, buildQuality({
|
|
876
|
+
complexityCapability,
|
|
877
|
+
coverageUsable: coverageResult.available === true && coverageResult.error === false,
|
|
878
|
+
attributionComplete: true,
|
|
879
|
+
rulesComplete: true,
|
|
880
|
+
changedFunctions: changedFunctionsWithLanguage
|
|
881
|
+
}), buildFingerprints(changedFunctionsWithLanguage));
|
|
882
|
+
}
|
|
883
|
+
// Helper function to build output when there is a provider failure
|
|
884
|
+
function buildFailedOutput(base, gitCapability, complexityCapability, coverageCapability, threshold, coverageErrorReason) {
|
|
885
|
+
return {
|
|
886
|
+
schemaVersion: '0.5',
|
|
887
|
+
analysis: {
|
|
888
|
+
base: base,
|
|
889
|
+
target: 'current'
|
|
890
|
+
},
|
|
891
|
+
capabilities: {
|
|
892
|
+
git: gitCapability,
|
|
893
|
+
complexity: complexityCapability,
|
|
894
|
+
coverageArtifact: coverageCapability
|
|
895
|
+
},
|
|
896
|
+
changedFunctions: [],
|
|
897
|
+
policy: {
|
|
898
|
+
crapThreshold: threshold
|
|
899
|
+
},
|
|
900
|
+
ruleResults: [],
|
|
901
|
+
analysisStatus: 'FAILED',
|
|
902
|
+
gate: null,
|
|
903
|
+
completeness: 'INCOMPLETE',
|
|
904
|
+
...(coverageErrorReason !== undefined ? { coverageErrorReason } : {}),
|
|
905
|
+
};
|
|
906
|
+
}
|