checkchange 0.4.2 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,422 @@
1
+ /**
2
+ * Pure-TypeScript `.cs` method + approximate cyclomatic-complexity extractor.
3
+ *
4
+ * This is the FALLBACK path for C# analysis: no SDK, no `dotnet`, no Roslyn, no
5
+ * subprocess of any kind. The only host dependency is `node:fs/promises`
6
+ * `readFile`. It exists so that cycle 1 still produces COMPLETE coverage
7
+ * evaluation on a machine without the .NET SDK (the rich path is Task 3).
8
+ *
9
+ * Shape parity: `MethodDescriptor` and `isValidFileName` are copied
10
+ * field-for-field / byte-for-byte from pythonDescriptorProvider.ts:4-24 so that
11
+ * attribution (src/attribution.ts:143 keys descriptors by
12
+ * `${containerName ? containerName + '.' : ''}${functionName}:${startLine}`)
13
+ * and `coverageForMethods` cannot tell the two providers apart. Do NOT
14
+ * "improve" the guard here without changing the python one in the same commit.
15
+ *
16
+ * CC is an APPROXIMATION, by keyword counting over comment/string-stripped
17
+ * source: base 1, plus one per `if` / `else if` / `foreach` / `for` / `while` /
18
+ * `case` / `catch` / `&&` / `||` / `??` / `?:`. The per-token table and its
19
+ * known blind spots are pinned in test/csharp-fallback-parity.test.ts. A real
20
+ * AST would count `else if` once (this does too, via the `if` token) and would
21
+ * additionally count `when` filters, `switch` expressions and `yield`, which
22
+ * this does not. Divergence against the rich path is DELIBERATE and documented,
23
+ * not accidental.
24
+ *
25
+ * Documented limitations (all pinned or waived in the test file):
26
+ * - Block-bodied members AND expression-bodied METHODS (`int F() => x;`) are
27
+ * reported. Expression-bodied ones carry complexity 1 (the `=>` expression is
28
+ * never branch-parsed) and a span ending at the statement `;`, not at `{`.
29
+ * Expression-bodied PROPERTIES (`int P => 1;`), lambda field initialisers,
30
+ * abstract/interface declarations and fields are NOT methods here. Accepted
31
+ * blind spot: an expression-bodied member whose expression reaches a `{`
32
+ * before its `;` (collection initialiser, switch expression, block lambda) is
33
+ * not reported — the `{` severs the head before the terminator (pinned by the
34
+ * only-props test in test/csharp-fallback-parity.test.ts).
35
+ * - Generic methods (`M<T>(...)`) ARE recognised: `stripTypeParameters` (:281)
36
+ * removes `<...>` groups from the head prefix before the name regex (:313),
37
+ * so `public T Accumulate<T>(` is named `Accumulate` and gets a real span.
38
+ * Before this, EVERY generic head ended in `>`, the name regex rejected it,
39
+ * and the method was silently dropped — losing coverage attribution entirely.
40
+ * REMAINING limitation, by design: an UNBALANCED `<`/`>` in the head
41
+ * (malformed source) hands the head back unchanged, so such a head is decided
42
+ * exactly as it was before — including the pre-existing misname of a head like
43
+ * `public T Broken<T(`, which ends in the identifier `T` and has always been
44
+ * reported as `T`. Both are pinned as parity locks, not endorsed. A nested
45
+ * argument list (`Func<Func<int>>`) is NOT a blind spot: the strip counts
46
+ * depth, so nested groups go whole.
47
+ * - A recognised method body is skipped wholesale, so local functions inside it
48
+ * are never reported.
49
+ * - Code inside interpolated-string holes (`$"{x if}"`) is blanked with the
50
+ * rest of the string.
51
+ * - Constructors ARE reported, as functionName === the type name (so
52
+ * displayName is `Foo.Foo`). Rich-path naming may differ; that difference is
53
+ * in the pinned delta table.
54
+ * - Malformed source degrades to whatever was recognised before the imbalance; a
55
+ * file with no recognisable method yields `[]`. Degradation is NON-THROWING
56
+ * but not faithful, and the deviation is worse than "stopped early": an
57
+ * unterminated block-comment opener pairs with the next block-comment closer
58
+ * ANYWHERE later in the file — even one sitting inside a string literal on a
59
+ * later line — so real code after it is retroactively blanked and reported
60
+ * spans shift. An unbalanced `[` in an attribute list is dropped whole (never
61
+ * a method). Only an unreadable path (missing file, bad encoding) THROWS — that
62
+ * is a caller bug, not unparseable content.
63
+ */
64
+ import { readFile } from 'node:fs/promises';
65
+ import { basename } from 'node:path';
66
+ function isValidFileName(file) {
67
+ const baseName = basename(file);
68
+ const regex = /^[a-zA-Z0-9._/-]+$/;
69
+ return regex.test(baseName) && !baseName.includes('..') && !baseName.includes('\n') && !baseName.includes(';') && !baseName.includes('|');
70
+ }
71
+ // ponytail: keyword denylist, not a C# grammar. A head starting with one of
72
+ // these is a statement/expression, never a member declaration.
73
+ const STATEMENT_KEYWORDS = new Set([
74
+ 'add', 'and', 'as', 'async', 'await', 'base', 'break', 'case', 'catch', 'checked', 'class', 'const', 'continue',
75
+ 'default', 'delegate', 'do', 'else', 'enum', 'event', 'explicit', 'fixed', 'finally', 'for', 'foreach', 'from',
76
+ 'get', 'goto', 'group', 'if', 'implicit', 'in', 'init', 'interface', 'into', 'is', 'join', 'let', 'lock', 'namespace',
77
+ 'new', 'not', 'on', 'operator', 'or', 'orderby', 'out', 'params', 'record', 'ref', 'remove', 'return', 'select', 'set',
78
+ 'sizeof', 'stackalloc', 'struct', 'switch', 'this', 'throw', 'try', 'typeof', 'unchecked', 'unsafe', 'using',
79
+ 'value', 'var', 'when', 'where', 'while', 'with', 'yield',
80
+ ]);
81
+ const CONTAINER_RE = /\b(?:class|struct|interface|record|enum)\s+([A-Za-z_]\w*)/;
82
+ // One pass, ordered alternation. Word-boundary keywords first (so `foreach` is
83
+ // not also counted as `for`), then the boolean operators, then `??`, then the
84
+ // ternary.
85
+ //
86
+ // The ternary alternative requires a `:` before the next `;`/`{`/`}` so a
87
+ // nullable-type annotation (`int? x`) with no colon in the statement is not
88
+ // counted, and `(?![?.])` excludes null-conditional access (`a?.b`). The
89
+ // lookbehind `(?<![)\]\w])` additionally excludes annotations directly after an
90
+ // identifier, `)`, `]` or `>` — e.g. `List<int?> x` — where the colon of a LATER
91
+ // ternary in the same statement would otherwise be reached. The cost of that
92
+ // guard is a documented false negative for a space-less ternary whose condition
93
+ // ends in an identifier, `)` or `]`: `x==1?a:b`. False negatives are preferred
94
+ // here because a false positive inflates CC against the 30/15 thresholds.
95
+ //
96
+ // `#if` preprocessor lines ARE counted as `if`: they are compile-time
97
+ // decisions. This is a deliberate divergence from a Roslyn AST walk, which
98
+ // ignores preprocessor conditionals.
99
+ const DECISION_RE = /\b(?:if|foreach|for|while|case|catch)\b|&&|\|\||\?\?|(?<![)\]\w])\?(?![?.])[^;{}]*?:/g;
100
+ /** Replace comment and string/char-literal content with spaces, preserving every offset. */
101
+ function blankNonCode(src) {
102
+ const out = [];
103
+ let i = 0;
104
+ while (i < src.length) {
105
+ if (src.startsWith('//', i)) {
106
+ const nl = src.indexOf('\n', i);
107
+ const end = nl === -1 ? src.length : nl;
108
+ out.push(blanks(src.slice(i, end)));
109
+ i = end;
110
+ }
111
+ else if (src.startsWith('/*', i)) {
112
+ const close = src.indexOf('*/', i + 2);
113
+ const end = close === -1 ? src.length : close + 2;
114
+ out.push(blanks(src.slice(i, end)));
115
+ i = end;
116
+ }
117
+ else {
118
+ const ch = src[i] ?? '';
119
+ if (ch === '"' || ch === "'") {
120
+ // Verbatim prefix is `@`, `$@` or `@$` — all three are verbatim (raw
121
+ // `@` is an identifier sigil, `$` interpolation is compatible with
122
+ // verbatim, so `"` after `$` is NOT verbatim).
123
+ const verbatim = ch === '"' && /@\$?|\$@$/.test(src.slice(Math.max(0, i - 2), i));
124
+ let j = i + 1;
125
+ while (j < src.length) {
126
+ const cur = src[j];
127
+ if (!verbatim && cur === '\\') {
128
+ j += 2;
129
+ continue;
130
+ }
131
+ if (cur === ch) {
132
+ if (verbatim && src[j + 1] === '"') {
133
+ j += 2;
134
+ continue;
135
+ }
136
+ j++;
137
+ break;
138
+ }
139
+ if (ch === "'" && cur === '\n')
140
+ break; // unterminated char literal
141
+ j++;
142
+ }
143
+ out.push(blanks(src.slice(i, j)));
144
+ i = j;
145
+ }
146
+ else {
147
+ out.push(ch);
148
+ i++;
149
+ }
150
+ }
151
+ }
152
+ return out.join('');
153
+ }
154
+ function blanks(text) {
155
+ return text.replace(/[^\n]/g, ' ');
156
+ }
157
+ function lineStartsOf(src) {
158
+ const starts = [0];
159
+ for (let i = 0; i < src.length; i++) {
160
+ if (src[i] === '\n')
161
+ starts.push(i + 1);
162
+ }
163
+ return starts;
164
+ }
165
+ function lineIndexAt(starts, offset) {
166
+ let lo = 0;
167
+ let hi = starts.length - 1;
168
+ while (lo < hi) {
169
+ const mid = (lo + hi + 1) >> 1;
170
+ if ((starts[mid] ?? 0) <= offset)
171
+ lo = mid;
172
+ else
173
+ hi = mid - 1;
174
+ }
175
+ return lo;
176
+ }
177
+ function matchBrace(src, open) {
178
+ let depth = 0;
179
+ for (let i = open; i < src.length; i++) {
180
+ const ch = src[i];
181
+ if (ch === '{')
182
+ depth++;
183
+ else if (ch === '}') {
184
+ depth--;
185
+ if (depth === 0)
186
+ return i;
187
+ }
188
+ }
189
+ return src.length - 1;
190
+ }
191
+ /** Index of the `)` closing the `(` at `open`, or -1 when unbalanced. */
192
+ function matchParen(src, open) {
193
+ let depth = 0;
194
+ for (let i = open; i < src.length; i++) {
195
+ const ch = src[i];
196
+ if (ch === '(')
197
+ depth++;
198
+ else if (ch === ')') {
199
+ depth--;
200
+ if (depth === 0)
201
+ return i;
202
+ }
203
+ }
204
+ return -1;
205
+ }
206
+ /**
207
+ * Remove leading attribute lists (`[Obsolete]`, `[Authorize(Roles = "x")]`) from
208
+ * a member head. Without this, a parameterised attribute's own `(` is the FIRST
209
+ * `(` in the head, so the member is reported under the attribute's name and the
210
+ * real method vanishes — which silently drops coverage attribution.
211
+ *
212
+ * Safe because `blankNonCode` runs first: every `[`/`]`/`(` inside a string or
213
+ * comment literal is already a space, so bracket counting cannot be fooled.
214
+ * An unbalanced `[` (malformed source) drops the rest of the head.
215
+ */
216
+ function stripAttributes(head) {
217
+ let rest = head;
218
+ for (;;) {
219
+ const start = rest.search(/\S/);
220
+ if (start === -1 || rest[start] !== '[')
221
+ return rest;
222
+ let depth = 0;
223
+ let i = start;
224
+ for (; i < rest.length; i++) {
225
+ if (rest[i] === '[')
226
+ depth++;
227
+ else if (rest[i] === ']') {
228
+ depth--;
229
+ if (depth === 0)
230
+ break;
231
+ }
232
+ }
233
+ if (i >= rest.length)
234
+ return '';
235
+ rest = rest.slice(0, start) + ' ' + rest.slice(i + 1);
236
+ }
237
+ }
238
+ /**
239
+ * Remove `<...>` groups from the part of a member head that precedes the `(`,
240
+ * so a generic method's name is an identifier again: `public T Accumulate<T>`
241
+ * becomes `public T Accumulate` and the name regex downstream matches it.
242
+ *
243
+ * Without this, EVERY generic method head ends in `>`, the name regex rejects
244
+ * it, and the whole method is SILENTLY DROPPED — no descriptor, no span, no
245
+ * coverage attribution, so a CRAPPY generic method cannot be reported at all.
246
+ * That is the gap this closes.
247
+ *
248
+ * Depth-counted, deliberately NOT `<.*?>`: a nested argument list
249
+ * (`Func<Func<int>>`) closes at the second `>`, and a non-greedy match would
250
+ * stop at the first and leave the method head half-stripped. Not a C# grammar —
251
+ * generic TYPE declarations and constraints never reach here (a constraint
252
+ * follows the parameter list, i.e. after the `(` this slice stops at).
253
+ *
254
+ * Safe because `blankNonCode` runs first: every `<`/`>` inside a string or
255
+ * comment is already a space, so bracket counting cannot be fooled.
256
+ * An unbalanced bracket (malformed source) hands the head back UNCHANGED, so the
257
+ * name regex decides as it did before this function existed — degradation, never
258
+ * a new phantom member.
259
+ */
260
+ function stripTypeParameters(before) {
261
+ if (!before.includes('<'))
262
+ return before;
263
+ let out = '';
264
+ let depth = 0;
265
+ for (const ch of before) {
266
+ if (ch === '<')
267
+ depth++;
268
+ else if (ch === '>') {
269
+ depth--;
270
+ if (depth < 0)
271
+ return before; // stray closer: strip nothing
272
+ }
273
+ else if (depth === 0)
274
+ out += ch;
275
+ }
276
+ return depth === 0 ? out : before; // unclosed `<`: strip nothing
277
+ }
278
+ function signatureOf(head) {
279
+ const stripped = stripAttributes(head);
280
+ const open = stripped.indexOf('(');
281
+ if (open < 0)
282
+ return null;
283
+ // `=>` in the head is a method ONLY at body position: the first `(`'s
284
+ // balanced `)` must be immediately followed by `=>` (expression-bodied
285
+ // method — the member loop feeds such heads here at the statement `;`).
286
+ // Any other `=>` is a lambda (`Select(i => i)`, `Wrap((x) => x)`) and stays
287
+ // disqualified, exactly as the old blanket `stripped.includes('=>')` gate did.
288
+ if (stripped.includes('=>')) {
289
+ const close = matchParen(stripped, open);
290
+ if (close < 0 || !/^\s*=>/.test(stripped.slice(close + 1)))
291
+ return null;
292
+ }
293
+ // Strip type-parameter lists BEFORE the name regex, which needs an identifier
294
+ // at the end of the head. `head` itself is left untouched, so `isMethodHead`'s
295
+ // first-token STATEMENT_KEYWORDS read is unaffected, and the `=` / constructor
296
+ // gates below keep seeing the same `returnPart` decision.
297
+ const before = stripTypeParameters(stripped.slice(0, open).trimEnd());
298
+ const nameMatch = /([A-Za-z_]\w*)\s*$/.exec(before);
299
+ if (!nameMatch?.[1])
300
+ return null;
301
+ const name = nameMatch[1];
302
+ return { name, returnPart: before.slice(0, before.length - name.length).trim(), head: stripped };
303
+ }
304
+ function isMethodHead(head, containerName) {
305
+ const sig = signatureOf(head);
306
+ if (!sig)
307
+ return null;
308
+ // Read the first token from the attribute-stripped head, not the raw one.
309
+ const first = /[A-Za-z_]\w*/.exec(sig.head)?.[0];
310
+ if (first === undefined || STATEMENT_KEYWORDS.has(first))
311
+ return null;
312
+ // ponytail: a target-typed `new()` / collection-initializer field
313
+ // (`static readonly Dictionary<string,int> Map = new() { ... }`) has a `(` in
314
+ // its head but is a field, not a method — an `=` before the name is the tell.
315
+ if (sig.returnPart.includes('='))
316
+ return null;
317
+ // No return type means a constructor (or a lambda — already excluded above).
318
+ if (!sig.returnPart)
319
+ return sig.name === containerName ? sig : null;
320
+ return sig;
321
+ }
322
+ export async function parseCsharpFileMethods(filePath) {
323
+ if (!isValidFileName(filePath)) {
324
+ throw new Error(`Invalid file name: ${filePath}`);
325
+ }
326
+ const source = blankNonCode(await readFile(filePath, 'utf8'));
327
+ const lineStarts = lineStartsOf(source);
328
+ const descriptors = [];
329
+ const stack = [];
330
+ let headStart = 0;
331
+ let i = 0;
332
+ /** Push a descriptor for the member spanning source[headStart..end] (end = `}` or `;`, inclusive). */
333
+ const pushMember = (sig, container, start0, end, complexity) => {
334
+ let start = start0;
335
+ while (start < end && ' \t\r\n'.includes(source[start] ?? 'x'))
336
+ start++;
337
+ const startLineIdx = lineIndexAt(lineStarts, start);
338
+ const endLineIdx = lineIndexAt(lineStarts, end);
339
+ descriptors.push({
340
+ functionName: sig.name,
341
+ containerName: container,
342
+ displayName: container ? `${container}.${sig.name}` : sig.name,
343
+ startLine: startLineIdx + 1,
344
+ endLine: endLineIdx + 1,
345
+ complexity,
346
+ bodySpan: {
347
+ startLine: startLineIdx + 1,
348
+ // A body that fits on ONE line anchors at column 0, not at the
349
+ // declaration's column. Cobertura/LCOV emit statements as whole LINES
350
+ // with startColumn 0 (coberturaProvider.ts:122, lcovProvider.ts:64), and
351
+ // the attribution join compares columns whenever the statement and the
352
+ // span share a start line (coverageAttribution.js:121,124 ->
353
+ // comparePosition returns leftColumn - rightColumn for equal lines). At
354
+ // the declaration column, `comparePosition(L, 12, L, 0) <= 0` was false
355
+ // on both containment paths, so the statement was owned by nobody and
356
+ // coverage came back null -> changed-function-high-crap NOT_EVALUATED ->
357
+ // completeness INCOMPLETE. Multi-line bodies start on a DIFFERENT line
358
+ // from any statement inside them, so their startColumn is never read for
359
+ // containment and stays exactly as measured.
360
+ startColumn: startLineIdx === endLineIdx ? 0 : start - (lineStarts[startLineIdx] ?? 0),
361
+ endLine: endLineIdx + 1,
362
+ endColumn: end - (lineStarts[endLineIdx] ?? 0) + 1,
363
+ },
364
+ expectsStatementCoverage: true,
365
+ expectsBranchCoverage: true,
366
+ });
367
+ };
368
+ while (i < source.length) {
369
+ const ch = source[i];
370
+ if (ch === ';') {
371
+ // Expression-bodied members terminate at `;` and never reach the `{`
372
+ // trigger below — evaluate the accumulated head HERE (both gates: this
373
+ // `;` trigger + signatureOf's structural `=>` check). Attribute lists are
374
+ // stripped first so a lambda inside an attribute (`[My(() => 1)]`) does
375
+ // not look like an expression body. complexity is 1: the `=>` expression
376
+ // is never branch-parsed.
377
+ const head = source.slice(headStart, i);
378
+ if (stripAttributes(head).includes('=>')) {
379
+ const container = stack.length ? (stack[stack.length - 1]?.container ?? null) : null;
380
+ const sig = isMethodHead(head, container);
381
+ if (sig)
382
+ pushMember(sig, container, headStart, i, 1);
383
+ }
384
+ headStart = i + 1;
385
+ i++;
386
+ continue;
387
+ }
388
+ if (ch === '}') {
389
+ stack.pop();
390
+ headStart = i + 1;
391
+ i++;
392
+ continue;
393
+ }
394
+ if (ch !== '{') {
395
+ i++;
396
+ continue;
397
+ }
398
+ const head = source.slice(headStart, i);
399
+ const container = stack.length ? (stack[stack.length - 1]?.container ?? null) : null;
400
+ // An attr-stripped `=>` in the head means an expression-bodied member whose
401
+ // EXPRESSION reaches this `{` (initialiser, switch arm, block lambda) —
402
+ // never a block-bodied method. Evaluating it here would anchor the span
403
+ // mid-expression and branch-count the body; the statement `;` path above
404
+ // owns `=>` heads. Matches the old signatureOf `=>` gate byte-for-byte.
405
+ const sig = stripAttributes(head).includes('=>') ? null : isMethodHead(head, container);
406
+ if (sig) {
407
+ const close = matchBrace(source, i);
408
+ const body = source.slice(i + 1, close);
409
+ pushMember(sig, container, headStart, close, 1 + (body.match(DECISION_RE)?.length ?? 0));
410
+ // Jump past the whole body: nested blocks and local functions are not
411
+ // scanned, and `endLine` is the method's own closing brace.
412
+ i = close + 1;
413
+ headStart = i;
414
+ continue;
415
+ }
416
+ const containerMatch = CONTAINER_RE.exec(head);
417
+ stack.push({ container: containerMatch?.[1] ?? container });
418
+ headStart = i + 1;
419
+ i++;
420
+ }
421
+ return descriptors;
422
+ }
@@ -1,6 +1,13 @@
1
1
  import { spawnSync } from 'node:child_process';
2
2
  import { basename, relative } from 'node:path';
3
3
  import { readCoverage } from '../coverage.js';
4
+ // ponytail: `as const` is deliberately NOT used — ComplexityInfo.provenance is a
5
+ // mutable optional field, and a readonly const would not assign cleanly.
6
+ const PYTHON_AST_PROVENANCE = {
7
+ tool: 'python stdlib ast',
8
+ version: 'unknown',
9
+ mode: 'NATIVE',
10
+ };
4
11
  export const pythonASTComplexityProvider = {
5
12
  extensions: ['.py'],
6
13
  collectComplexity: (cwd) => {
@@ -130,7 +137,17 @@ if __name__ == '__main__':
130
137
  method: info.method,
131
138
  lineStart: info.lineStart,
132
139
  lineEnd: info.lineEnd,
133
- cc: info.cc
140
+ cc: info.cc,
141
+ // GAP 8: these CC values come from the CPython `ast` module run in a
142
+ // `python3 -c` subprocess (pythonDescriptorProvider.ts:118), NOT from
143
+ // @barney-media/crap-typescript-core — which is what evidence reported
144
+ // before, a false provenance claim on every .py function. `version` is
145
+ // 'unknown' because the interpreter version is not probed: the script's
146
+ // stdout contract carries descriptors only, and widening it to carry a
147
+ // version is a bigger change than this. NATIVE, not FALLBACK — `ast` is
148
+ // a real AST parser for Python, so diagnostics.quality stays NATIVE for
149
+ // a .py run and the only delta is the honest tool name.
150
+ provenance: PYTHON_AST_PROVENANCE
134
151
  });
135
152
  }
136
153
  }
@@ -3,12 +3,63 @@ export declare const complexityProvenance: {
3
3
  readonly tool: "@barney-media/crap-typescript-core";
4
4
  readonly version: "0.5.0";
5
5
  };
6
+ /**
7
+ * Which analyzer measured one function, and whether it was a real analyzer for
8
+ * that language (`NATIVE`) or an approximation of one (`FALLBACK` — the ADR-0001
9
+ * term reserved at docs/decisions/terminology-reconciliation.md:68,:112).
10
+ *
11
+ * It rides ON the measurement instead of being re-derived at the consumer, so
12
+ * evidence.ts never learns a provider's tool name or its health from a literal
13
+ * (D5). A measurement that omits `provenance` entirely was produced by the
14
+ * default native analyzer above — that absence IS the TypeScript case.
15
+ */
16
+ export interface MeasurementProvenance {
17
+ tool: string;
18
+ version: string;
19
+ mode: 'NATIVE' | 'FALLBACK';
20
+ /**
21
+ * Provider-owned machine reason code for a FALLBACK measurement, e.g.
22
+ * `csharp-analysis-failed`. Optional and NOT part of `source`: evidence reports
23
+ * only `{ tool, version }` per function (the published Source shape), while this
24
+ * rides the complexity LINEAGE entry — one key per run, so a consumer can tell
25
+ * "approximated" from "approximated because the analyzer was missing".
26
+ */
27
+ degradation?: string;
28
+ }
6
29
  export interface ComplexityInfo {
7
30
  file: string;
8
31
  method: string;
9
32
  lineStart: number;
10
33
  lineEnd: number;
11
34
  cc: number;
35
+ /** Absent => measured by the default native analyzer (`complexityProvenance`). */
36
+ provenance?: MeasurementProvenance;
12
37
  }
38
+ /**
39
+ * The `{ tool, version }` evidence reports for one measurement. A FACTORY, not a
40
+ * second const, because the answer depends on the measurement; the default it
41
+ * returns is `complexityProvenance` itself, so the TypeScript path is unchanged.
42
+ */
43
+ export declare function measurementProvenance(info: ComplexityInfo | undefined): {
44
+ tool: string;
45
+ version: string;
46
+ };
47
+ /**
48
+ * ADR-0001 quality for a set of measurements: `FALLBACK` when ANY of them came
49
+ * from an approximation. One approximate file makes the whole stage non-native —
50
+ * reporting `NATIVE` over a mixed set is the false-provenance claim GAP 8 exists
51
+ * to remove. Absent provenance => `NATIVE`.
52
+ */
53
+ export declare function measurementQuality(infos: ReadonlyArray<{
54
+ provenance?: MeasurementProvenance;
55
+ }>): 'NATIVE' | 'FALLBACK';
56
+ /**
57
+ * The distinct provider reason codes behind a FALLBACK stage, in first-seen order.
58
+ * Empty for a native or failed stage, so callers can spread the key in only when
59
+ * it carries something — a `.ts` run's lineage entry stays byte-identical.
60
+ */
61
+ export declare function measurementDegradations(infos: ReadonlyArray<{
62
+ provenance?: MeasurementProvenance;
63
+ }>): string[];
13
64
  export declare function getGitTrackedCodeFiles(cwd: string): string[];
14
65
  export declare function collectComplexity(cwd: string, trace?: TraceRun, changedFiles?: ReadonlySet<string>): Promise<ComplexityInfo[]>;
@@ -2,7 +2,45 @@ import { findAllTypeScriptFilesUnderSourceRoots, parseFileMethods } from '@barne
2
2
  import { relative, resolve } from 'node:path';
3
3
  import { execSync } from 'node:child_process';
4
4
  // Provenance for the complexity lineage stage: native analyzer from the core package.
5
+ // RETAINED as a plain const, not folded into the factory below: cache.ts:366 reads
6
+ // `.version` off it and test/lineage.test.ts:43 asserts it in a wholesale list.
5
7
  export const complexityProvenance = { tool: '@barney-media/crap-typescript-core', version: '0.5.0' };
8
+ /**
9
+ * The `{ tool, version }` evidence reports for one measurement. A FACTORY, not a
10
+ * second const, because the answer depends on the measurement; the default it
11
+ * returns is `complexityProvenance` itself, so the TypeScript path is unchanged.
12
+ */
13
+ export function measurementProvenance(info) {
14
+ const p = info?.provenance ?? complexityProvenance;
15
+ // PROJECT, never pass the reference through. A full MeasurementProvenance also
16
+ // carries `mode` and `degradation`, which are STAGE-level facts; returning it as-is
17
+ // would widen the published per-function `source` shape from { tool, version } to
18
+ // five keys and stamp a provider reason code onto every single function.
19
+ return { tool: p.tool, version: p.version };
20
+ }
21
+ /**
22
+ * ADR-0001 quality for a set of measurements: `FALLBACK` when ANY of them came
23
+ * from an approximation. One approximate file makes the whole stage non-native —
24
+ * reporting `NATIVE` over a mixed set is the false-provenance claim GAP 8 exists
25
+ * to remove. Absent provenance => `NATIVE`.
26
+ */
27
+ export function measurementQuality(infos) {
28
+ return infos.some((info) => info.provenance?.mode === 'FALLBACK') ? 'FALLBACK' : 'NATIVE';
29
+ }
30
+ /**
31
+ * The distinct provider reason codes behind a FALLBACK stage, in first-seen order.
32
+ * Empty for a native or failed stage, so callers can spread the key in only when
33
+ * it carries something — a `.ts` run's lineage entry stays byte-identical.
34
+ */
35
+ export function measurementDegradations(infos) {
36
+ const codes = [];
37
+ for (const info of infos) {
38
+ const code = info.provenance?.degradation;
39
+ if (code !== undefined && !codes.includes(code))
40
+ codes.push(code);
41
+ }
42
+ return codes;
43
+ }
6
44
  export function getGitTrackedCodeFiles(cwd) {
7
45
  try {
8
46
  // Get list of tracked files, one per line
@@ -0,0 +1,28 @@
1
+ import type { coverageForMethods } from '@barney-media/crap-typescript-core';
2
+ type FileCoverage = NonNullable<Parameters<typeof coverageForMethods>[1]>;
3
+ /**
4
+ * Typed parse failure. `reason` carries the EXISTING CoverageResult.reason
5
+ * value ('malformed', src/coverage.ts:487) so a caller maps a Cobertura refusal
6
+ * onto the current taxonomy without inventing a reason string.
7
+ * The size/line guards throw this too, so a single `instanceof` catch covers
8
+ * every provider-side refusal.
9
+ */
10
+ export declare class CoberturaParseError extends Error {
11
+ readonly reason: "malformed";
12
+ constructor(message: string);
13
+ }
14
+ /**
15
+ * Parse Cobertura XML content and convert it to the same Map shape the core
16
+ * package's parseCoverageReport produces, so coverageForMethods can attribute
17
+ * methods.
18
+ * @param coberturaContent The Cobertura XML file content as string
19
+ * @param cwd Current working directory for path normalization
20
+ * @returns Map<filePath, { statements: Array<{ span: { startLine: number, startColumn: number, endLine: number, endColumn: number }, hits: number }>, branches: [], functions: [] }>
21
+ * Branches and functions are always empty: a `<line branch="true">` element
22
+ * does NOT fabricate a branches array (same precedent as LCOV BRDA being
23
+ * ignored at lcovProvider.ts:70-71). Merge Cobertura with LCOV via
24
+ * mergeCoverageMaps rather than by concatenating raw maps.
25
+ * @throws {CoberturaParseError} on an oversized / over-long / malformed document
26
+ */
27
+ export declare function parseCoberturaContent(coberturaContent: string, cwd: string): Map<string, FileCoverage>;
28
+ export {};