reading-stone 0.0.0-stage → 0.2.1

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 (72) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +11 -0
  3. package/README.md +301 -2
  4. package/dist/analysis.d.ts +341 -0
  5. package/dist/analysis.js +392 -0
  6. package/dist/cognitive.d.ts +163 -0
  7. package/dist/cognitive.js +380 -0
  8. package/dist/complexity.d.ts +102 -0
  9. package/dist/complexity.js +163 -0
  10. package/dist/coverage.d.ts +78 -0
  11. package/dist/coverage.js +635 -0
  12. package/dist/detector.d.ts +41 -0
  13. package/dist/detector.js +2134 -0
  14. package/dist/discovery.d.ts +330 -0
  15. package/dist/discovery.js +930 -0
  16. package/dist/doc-coverage.d.ts +155 -0
  17. package/dist/doc-coverage.js +543 -0
  18. package/dist/extract.d.ts +209 -0
  19. package/dist/extract.js +498 -0
  20. package/dist/index.d.ts +64 -0
  21. package/dist/index.js +63 -0
  22. package/dist/internal.d.ts +75 -0
  23. package/dist/internal.js +63 -0
  24. package/dist/main.d.ts +8 -0
  25. package/dist/main.js +39 -0
  26. package/dist/models.d.ts +185 -0
  27. package/dist/models.js +170 -0
  28. package/dist/program.d.ts +207 -0
  29. package/dist/program.js +662 -0
  30. package/dist/protocol.d.ts +88 -0
  31. package/dist/protocol.js +74 -0
  32. package/dist/quality/assertions.d.ts +81 -0
  33. package/dist/quality/assertions.js +425 -0
  34. package/dist/quality/collect.d.ts +66 -0
  35. package/dist/quality/collect.js +412 -0
  36. package/dist/quality/inference.d.ts +86 -0
  37. package/dist/quality/inference.js +603 -0
  38. package/dist/quality/matchers.d.ts +129 -0
  39. package/dist/quality/matchers.js +220 -0
  40. package/dist/quality/pairing.d.ts +133 -0
  41. package/dist/quality/pairing.js +770 -0
  42. package/dist/quality/pipeline.d.ts +59 -0
  43. package/dist/quality/pipeline.js +202 -0
  44. package/dist/quality/types.d.ts +127 -0
  45. package/dist/quality/types.js +92 -0
  46. package/dist/safeio.d.ts +107 -0
  47. package/dist/safeio.js +314 -0
  48. package/dist/server.d.ts +19 -0
  49. package/dist/server.js +451 -0
  50. package/dist/signals/adapter.d.ts +103 -0
  51. package/dist/signals/adapter.js +323 -0
  52. package/dist/signals/caller-index.d.ts +117 -0
  53. package/dist/signals/caller-index.js +147 -0
  54. package/dist/signals/caller.d.ts +76 -0
  55. package/dist/signals/caller.js +108 -0
  56. package/dist/signals/evidence.d.ts +233 -0
  57. package/dist/signals/evidence.js +578 -0
  58. package/dist/signals/interface.d.ts +68 -0
  59. package/dist/signals/interface.js +87 -0
  60. package/dist/signals/jsdoc.d.ts +27 -0
  61. package/dist/signals/jsdoc.js +233 -0
  62. package/dist/signals/naming.d.ts +26 -0
  63. package/dist/signals/naming.js +160 -0
  64. package/dist/signals/routing.d.ts +163 -0
  65. package/dist/signals/routing.js +416 -0
  66. package/dist/signals/types.d.ts +146 -0
  67. package/dist/signals/types.js +99 -0
  68. package/dist/signals/visibility.d.ts +23 -0
  69. package/dist/signals/visibility.js +82 -0
  70. package/dist/taxonomy.d.ts +89 -0
  71. package/dist/taxonomy.js +217 -0
  72. package/package.json +61 -4
@@ -0,0 +1,392 @@
1
+ import { assembleFunctionRecords, detectEffects } from "./detector.js";
2
+ import { classifyFiles, resolveRoot, screenCandidates, walkTree } from "./discovery.js";
3
+ import { extractFunctions } from "./extract.js";
4
+ import { serializeFunctionRecord } from "./models.js";
5
+ import { buildProgramContext, } from "./program.js";
6
+ import { MAX_FILE_BYTES, readBounded } from "./safeio.js";
7
+ import { classifyPairs } from "./signals/adapter.js";
8
+ import { buildRecordEvidence } from "./signals/evidence.js";
9
+ import { serializeSignal } from "./signals/types.js";
10
+ /**
11
+ * Normalizes one pattern element into a directory prefix: strip one
12
+ * leading `./`, then one trailing `/...` — exactly one of each, in that
13
+ * order (research R11). `"././src"` keeps its second `./`, and no glob or
14
+ * regex interpretation exists (rejected in research R11).
15
+ *
16
+ * The result may be a documented match-nothing prefix: the empty string
17
+ * (from `""` or `"./"`), `"."`, or a non-singleton `"..."` — such an
18
+ * element matches no path, so a set of only such elements matches
19
+ * nothing rather than everything.
20
+ */
21
+ function normalizePattern(element) {
22
+ let prefix = element;
23
+ if (prefix.startsWith("./")) {
24
+ prefix = prefix.slice(2);
25
+ }
26
+ if (prefix.endsWith("/...")) {
27
+ prefix = prefix.slice(0, -4);
28
+ }
29
+ return prefix;
30
+ }
31
+ /**
32
+ * Normalizes the raw `patterns` parameter into a `PatternSet` (FR-001).
33
+ *
34
+ * The catch-alls — `patterns` absent, `null`, the empty array, or the
35
+ * exact singleton forms `["./..."]` and `["..."]` — normalize to `null`,
36
+ * the whole tree. Every other element becomes a directory prefix through
37
+ * `normalizePattern`, deduplicated preserving first occurrence.
38
+ *
39
+ * Match-nothing elements are kept, never dropped: `[""]`, `["."]`, and
40
+ * `["./"]` normalize to prefixes that match no path, so a pattern set
41
+ * matching nothing yields empty analysis results downstream, never an
42
+ * error. Only the exact singleton forms are catch-alls — a lone `"..."`
43
+ * element inside a larger array survives as a match-nothing prefix.
44
+ *
45
+ * The input domain is the server-validated one (T019 rejects non-array
46
+ * or non-string-element `patterns` with `-32602` before analysis runs):
47
+ * `undefined`, `null`, or an array of strings. Validation itself is the
48
+ * dispatch layer's concern, not this function's.
49
+ *
50
+ * @param patterns The raw `patterns` parameter value.
51
+ */
52
+ export function normalizePatterns(patterns) {
53
+ if (patterns === null || patterns === undefined) {
54
+ return null;
55
+ }
56
+ const elements = patterns;
57
+ if (elements.length === 0) {
58
+ return null;
59
+ }
60
+ const prefixes = new Set();
61
+ for (const element of elements) {
62
+ prefixes.add(normalizePattern(element));
63
+ }
64
+ // The catch-all check is on the raw element count: only the exact
65
+ // singleton forms are catch-alls, so `["...", "..."]` is not one (its
66
+ // lone distinct prefix still matches nothing — research R11).
67
+ if (elements.length === 1 && prefixes.has("...")) {
68
+ return null;
69
+ }
70
+ return [...prefixes];
71
+ }
72
+ /**
73
+ * Reports whether a root-relative POSIX-separator path is in scope under a
74
+ * normalized pattern set (FR-001).
75
+ *
76
+ * `null` means the whole tree. Otherwise a pattern matches when the path
77
+ * equals a prefix — the prefix may itself be a file path — or begins with
78
+ * `prefix + "/"`, a segment boundary: the prefix `src` does not match
79
+ * `srcx/lib.ts`, and the file pattern `src/lib.ts` does not scope its
80
+ * siblings. Patterns union — any matching prefix puts the path in scope.
81
+ *
82
+ * @param relPath Root-relative POSIX-separator path to test.
83
+ * @param patternSet A normalized pattern set from `normalizePatterns`.
84
+ */
85
+ export function pathInScope(relPath, patternSet) {
86
+ if (patternSet === null) {
87
+ return true;
88
+ }
89
+ return patternSet.some((prefix) => relPath === prefix || relPath.startsWith(`${prefix}/`));
90
+ }
91
+ /**
92
+ * Prepares the shared analysis over a project tree (FR-002; research R12):
93
+ * resolve, walk, screen, classify, exclude, filter, bootstrap, extract —
94
+ * the one pipeline the analyze and complexity handlers both consume, so
95
+ * FR-022's same-extraction-set/scope/ordering guarantee is structural.
96
+ *
97
+ * Composition, in order:
98
+ *
99
+ * 1. `resolveRoot` validates and realpath-resolves the root (FR-010) —
100
+ * the same validation `discover` runs; an invalid root throws
101
+ * `InvalidRootPathError` here, for the server to map to `-32602`
102
+ * (no layering inversion).
103
+ * 2. `walkTree` → `screenCandidates` → `classifyFiles`: the same
104
+ * walk/screen/classify chain `discover()` composes, minus framework
105
+ * detection — deterministic walk order, the safety-skip → `.d.ts` →
106
+ * generated-marker exclusion chain, then the test/source partition.
107
+ * 3. Test files are additionally excluded from analysis (FR-002): only
108
+ * the classification's source arm proceeds. Generated files never
109
+ * reach this point (`screenCandidates` already dropped them), so test
110
+ * files and generated files are never analyzed. The exclusion precedes
111
+ * the pattern filter and is absolute: a pattern naming a test file
112
+ * still yields no records (FR-001 narrows within the analyzable set).
113
+ * 4. The FR-001 pattern filter — `normalizePatterns` then `pathInScope`
114
+ * over classifyFiles' sorted list — keeps the in-scope subset; a set
115
+ * matching nothing yields an empty analysis, never an error.
116
+ * 5. Each in-scope file is pre-read through the async `readBounded` at
117
+ * the full 16 MiB budget (a JSON-free whole-file read),
118
+ * `buildProgramContext` bootstraps the program or parse-only context
119
+ * over exactly those files (FR-003/FR-004; a `null` read excludes its
120
+ * file after `readBounded`'s own one-diagnostic skip), and
121
+ * `extractFunctions` walks the context's sources into the sorted
122
+ * record list (FR-007/FR-008), and the records are narrowed to the
123
+ * in-scope set — the program arm's transitive imports are excluded
124
+ * (FR-001/FR-022; the parse-only arm is structurally in scope).
125
+ *
126
+ * Diagnostics flow to the injected stderr; stdout is never touched (it is
127
+ * reserved for JSON-RPC responses). The returned context's lifetime is
128
+ * the consumer's — the analysis handlers dispose a program-mode context
129
+ * when finished with it — and a mid-pipeline failure releases it here:
130
+ * when extraction throws, the program-mode context is disposed before
131
+ * the error propagates, so no native compiler server outlives the
132
+ * pipeline call either way.
133
+ *
134
+ * @param rootPath Absolute or relative project root; a relative path
135
+ * resolves against the analyzer process working directory, and a symlinked
136
+ * root is realpath-resolved exactly once at the boundary (FR-018).
137
+ * @param patterns The raw `patterns` parameter value. The server validates
138
+ * its shape (`-32602`, T019) before analysis runs; this surface only
139
+ * normalizes.
140
+ * @param stderr Injected diagnostic sink (Testability principle); defaults
141
+ * to `process.stderr`.
142
+ * @param options The widening options (spec 004 FR-006); omitted by the
143
+ * analyze/complexity/classify_signals callers, which observe no behavior
144
+ * change beyond the inert `testPaths: []` result field.
145
+ * @returns The bootstrapped `ProgramContext`, the extraction records, the
146
+ * in-scope file set (spec 003 FR-016's file-set parity), the
147
+ * realpath-resolved analysis root, and the test arm (`[]` unless
148
+ * `{ includeTestArm: true }` was passed).
149
+ * @throws InvalidRootPathError when the root does not exist, is not a
150
+ * directory, or cannot be accessed; the server handler maps it to the
151
+ * contract's `-32602` response.
152
+ */
153
+ export async function prepareAnalysis(rootPath, patterns, stderr = process.stderr, options) {
154
+ const realRoot = await resolveRoot(rootPath);
155
+ const candidates = await walkTree(realRoot);
156
+ const surviving = await screenCandidates(realRoot, candidates, stderr);
157
+ // FR-002: test files are additionally excluded from analysis. Only the
158
+ // classification's source arm proceeds — classifyFiles owns the
159
+ // test/source partition, so taking the one arm is the whole exclusion,
160
+ // with no second copy of the test signals to drift. Generated files
161
+ // were already screened out above; test files and generated files are
162
+ // never analyzed. Spec 004's widening (FR-006) captures the other arm
163
+ // for the opt-in caller: the test arm flows to the bootstrap and back
164
+ // as `testPaths`, pattern-UNfiltered — patterns narrow the target arm
165
+ // only.
166
+ const { sourceFiles, testFiles } = classifyFiles(surviving);
167
+ // FR-001 narrows within the analyzable set, after the structural
168
+ // exclusion: the same normalize-then-test pair every pattern-filtered
169
+ // method applies, over the sorted source list (deterministic order).
170
+ const patternSet = normalizePatterns(patterns);
171
+ const inScope = sourceFiles.filter((relPath) => pathInScope(relPath, patternSet));
172
+ const testArm = options?.includeTestArm === true ? testFiles : [];
173
+ // The bootstrap input is deterministic in both modes: the sorted
174
+ // source arm, then the sorted test arm. Program mode derives the
175
+ // extender config's `files` root set from this list (so the test arm
176
+ // enters the configured program); parse-only mode derives its
177
+ // root-relative sources map from it identically.
178
+ const preRead = await preReadSources(realRoot, [...inScope, ...testArm], stderr);
179
+ const context = buildProgramContext(realRoot, preRead, stderr);
180
+ let records;
181
+ try {
182
+ records = extractFunctions(realRoot, context, stderr);
183
+ }
184
+ catch (error) {
185
+ // A program-mode context owns a live native compiler server; a failed
186
+ // extraction must not leak it. Release before the throw propagates —
187
+ // the same lifetime contract the handlers' finally owns (a parse-only
188
+ // context has nothing to dispose).
189
+ if (context.mode === "program") {
190
+ context.dispose();
191
+ }
192
+ throw error;
193
+ }
194
+ // FR-001/FR-022's scope guarantee over the configured program: the program
195
+ // arm can contain pattern-excluded in-root files — transitive imports the
196
+ // hermetic host serves on demand (src/program.ts) — and, under spec 004's
197
+ // widening, the admitted test arm; extraction's walk is root-containment
198
+ // scoped (src/extract.ts), so the record set is narrowed here to the
199
+ // identical in-scope list the pattern filter produced. The narrowing
200
+ // filter below is UNCONDITIONAL — the FR-006 parity invariant in both
201
+ // modes: the parse-only arm needs it just as much, because the widened
202
+ // test arm is admitted there too and its files are equally subject to
203
+ // the pattern filter's in-scope narrowing (F4's review fix: the old
204
+ // "needs no narrowing" claim described the pre-widening parse-only
205
+ // view, not the landed one). Both modes' record sets ARE the in-scope
206
+ // set — what FR-022's same-extraction-set guarantee, spec 003 US3-7's
207
+ // identical-file-set guarantee, and spec 004 FR-006's target-parity
208
+ // guarantee (the widened call reports `analyze`'s records
209
+ // record-for-record) all rest on.
210
+ const inScopeSet = new Set(inScope);
211
+ records = records.filter((record) => inScopeSet.has(record.relPath));
212
+ return {
213
+ context,
214
+ records,
215
+ inScopePaths: inScope,
216
+ rootPath: realRoot,
217
+ testPaths: testArm,
218
+ };
219
+ }
220
+ /**
221
+ * The `analyze` method's handler (FR-020; the analyze contract): the
222
+ * serialized `FunctionRecord[]` payload — detection effects attributed per
223
+ * record, assembled in the `(file, line, name)` total order, and mapped
224
+ * through `serializeFunctionRecord` so every entry on the returned array
225
+ * is already wire-shaped (fixed key order, validated fields — the
226
+ * protocol layer's sorted-key serializer then only re-orders keys).
227
+ *
228
+ * Spec 003 inserts the classification core between detection and
229
+ * assembly (FR-012; research R10; the adapter's composition contract):
230
+ * the evidence snapshots are taken while the program-mode context is
231
+ * still live — every checker query and the caller index's
232
+ * `getSignatureUsage` traffic round-trips to the native compiler server —
233
+ * then `classifyPairs` runs the pair-keyed fan-out and rebuilds each
234
+ * record's effects as new immutable values carrying
235
+ * `classification: {label, confidence}`. Every same-type effect on a
236
+ * record shares the identical pair classification (FR-008/FR-011), every
237
+ * effect in every response carries one (FR-012, superseding spec 002
238
+ * FR-019's omission rule here at the wiring layer — the detector itself
239
+ * is untouched and still produces unclassified effects), and the
240
+ * classified instances are what assembly consumes, so
241
+ * `serializeEffect` → `serializeClassification`'s fail-loud validation
242
+ * (closed label set, integer 0–100) now exercises on every `analyze`
243
+ * response.
244
+ *
245
+ * The returned array — not a `{functions: [...]}` wrapper — is the
246
+ * documented result shape the server wraps into its JSON-RPC success
247
+ * response (T019); both this entry and the payload are deterministic
248
+ * pure functions of the analyzed tree (Constitution Principle I:
249
+ * byte-identical repeat responses, classification fields included).
250
+ *
251
+ * The program-mode context's lifetime is this handler's — unchanged by
252
+ * the classification insertion: the native compiler server behind it is
253
+ * closed in the `finally` whatever the detection and classification
254
+ * outcome, so no subprocess outlives one analysis. A parse-only context
255
+ * owns nothing to dispose.
256
+ *
257
+ * @param rootPath Absolute or relative project root; validated and
258
+ * realpath-resolved by `prepareAnalysis` (an invalid root throws
259
+ * `InvalidRootPathError`, the server maps to `-32602`).
260
+ * @param patterns The raw `patterns` parameter value; shape-validated by
261
+ * the server (`-32602`, T019) before analysis runs, normalized here.
262
+ * @param stderr Injected diagnostic sink (Testability principle); defaults
263
+ * to `process.stderr`. Stdout is never touched.
264
+ * @returns The serialized function records, `(file, line, name)`-sorted.
265
+ */
266
+ export async function analyze(rootPath, patterns, stderr = process.stderr) {
267
+ const prepared = await prepareAnalysis(rootPath, patterns, stderr);
268
+ try {
269
+ const effects = detectEffects(prepared.records, prepared.context);
270
+ // Spec 003's insertion point (FR-012; research R10): evidence while
271
+ // the program-mode context is live (the caller index's
272
+ // `getSignatureUsage` traffic rides it), then the pair-keyed fan-out
273
+ // rebuilding effects as classified immutable values — between
274
+ // detection and assembly, exactly where FR-012 places the change.
275
+ const evidence = buildRecordEvidence(prepared.context, prepared.records, prepared.inScopePaths, prepared.rootPath);
276
+ const classified = classifyPairs(prepared.records, effects, evidence);
277
+ const assembled = assembleFunctionRecords(prepared.records, classified.effects);
278
+ return assembled.map(serializeFunctionRecord);
279
+ }
280
+ finally {
281
+ if (prepared.context.mode === "program") {
282
+ prepared.context.dispose();
283
+ }
284
+ }
285
+ }
286
+ /**
287
+ * The `classify_signals` method's entry (FR-014; research R10, R11): the
288
+ * serialized `Signal[]` payload — the raw evidence behind `analyze`'s
289
+ * classifications, one row per rule that matched per (function record,
290
+ * canonical effect type) pair — in FR-014's `(package, function,
291
+ * side_effect_type, source)` total order, each row already wire-shaped
292
+ * through `serializeSignal` (validated fields, omit-unset-optionals
293
+ * `reasoning`). The returned array — not a `{"signals": [...]}` wrapper —
294
+ * is the payload the server handler wraps into its JSON-RPC success
295
+ * response, exactly as it wraps `analyze`'s array. The return type is
296
+ * `ClassifySignalsResult["signals"]` — the payload half of the wire result
297
+ * interface — so the entry-to-handler hand-off is compile-time pinned: the
298
+ * handler types its wrapper against the interface, and this return cannot
299
+ * drift from the wire contract.
300
+ *
301
+ * The stages are `analyze`'s, identically and in the identical order
302
+ * (FR-013's one-shared-pipeline guarantee is structural, never a second
303
+ * walk): `prepareAnalysis` — the one discovery/bootstrap/extraction
304
+ * pipeline, so the identical discovered, pattern-filtered,
305
+ * exclusion-filtered file set and record set — then `detectEffects`, then
306
+ * the T024 core with the program-mode context still live: the evidence
307
+ * snapshots (`buildRecordEvidence`, caller index included) taken while the
308
+ * checker can still answer, then `classifyPairs` — the pair-keyed fan-out
309
+ * whose four-key-ordered `signals` feed is this entry's payload. The two
310
+ * entries differ by the last stage only: assembly and
311
+ * `serializeFunctionRecord` in `analyze`, feed serialization here.
312
+ *
313
+ * The entry lives here beside `analyze` — not in src/signals/adapter.ts —
314
+ * so the module dependency stays strictly one-directional (convention
315
+ * pack AP-005): this module imports the pure core; nothing under
316
+ * src/signals/ imports this module back.
317
+ *
318
+ * The program-mode context's dispose lifetime is owned here exactly as
319
+ * `analyze` owns its own (the same `finally` discipline): the native
320
+ * compiler server behind the context is closed whatever the detection and
321
+ * classification outcome, so no subprocess outlives one request. A
322
+ * parse-only context owns nothing to dispose. `prepareAnalysis` itself
323
+ * releases the context when extraction throws, and an invalid root throws
324
+ * `InvalidRootPathError` before any context exists — it propagates
325
+ * untouched for the server to map to the shared `-32602` root message.
326
+ *
327
+ * Deterministic (Constitution Principle I): the feed is a pure function of
328
+ * the analyzed tree and analyzer version — fixed row order, fixed
329
+ * reasoning templates, no timestamps or environment-dependent data — so
330
+ * repeated requests over the same tree serialize byte-identically.
331
+ *
332
+ * @param rootPath Absolute or relative project root; validated and
333
+ * realpath-resolved by `prepareAnalysis` (an invalid root throws
334
+ * `InvalidRootPathError`, the server maps to `-32602`).
335
+ * @param patterns The raw `patterns` parameter value; shape-validated by
336
+ * the server (`-32602`) before analysis runs, normalized by
337
+ * `prepareAnalysis`. A set matching nothing yields `[]`, never an error.
338
+ * @param stderr Injected diagnostic sink (Testability principle); defaults
339
+ * to `process.stderr`. Stdout is never touched.
340
+ * @returns The serialized signals — `ClassifySignalsResult["signals"]`, the
341
+ * `readonly Signal[]` the server handler wraps under the result interface's
342
+ * single `signals` key — `(package, function, side_effect_type, source)`
343
+ * -sorted.
344
+ * @throws InvalidRootPathError when the root does not exist, is not a
345
+ * directory, or cannot be accessed; the server handler maps it to the
346
+ * contract's `-32602` response.
347
+ */
348
+ export async function classifySignals(rootPath, patterns, stderr = process.stderr) {
349
+ const prepared = await prepareAnalysis(rootPath, patterns, stderr);
350
+ try {
351
+ const effects = detectEffects(prepared.records, prepared.context);
352
+ // The core's composition order (the adapter header's composition
353
+ // contract): evidence while the program-mode context is live — the
354
+ // caller index's `getSignatureUsage` traffic and every checker query
355
+ // ride it — then the pair-keyed fan-out whose four-key-ordered feed is
356
+ // the payload.
357
+ const evidence = buildRecordEvidence(prepared.context, prepared.records, prepared.inScopePaths, prepared.rootPath);
358
+ const classified = classifyPairs(prepared.records, effects, evidence);
359
+ return classified.signals.map(serializeSignal);
360
+ }
361
+ finally {
362
+ if (prepared.context.mode === "program") {
363
+ prepared.context.dispose();
364
+ }
365
+ }
366
+ }
367
+ /**
368
+ * Pre-reads the in-scope files for the bootstrap (research R12): each file
369
+ * through the async `readBounded` at the full 16 MiB budget — a JSON-free
370
+ * whole-file read, the form `buildProgramContext`'s pre-read pairs expect.
371
+ * A skipped read resolves `null` after `readBounded`'s own one-diagnostic
372
+ * skip; the `null` text is passed through for the bootstrap to exclude the
373
+ * file silently (never a second diagnostic for one skip). Reads are
374
+ * sequential, so per-file skip diagnostics land in the sorted list's order
375
+ * (research R8's deterministic-diagnostic discipline).
376
+ *
377
+ * @param realRoot Realpath-resolved absolute analysis root; every read is
378
+ * contained within it (FR-018).
379
+ * @param inScope The pattern-filtered, test-excluded source files, in
380
+ * classifyFiles' sorted order.
381
+ * @param stderr Injected diagnostic sink; stdout is never touched.
382
+ * @returns One `(relPath, text)` pair per in-scope file, in order.
383
+ */
384
+ async function preReadSources(realRoot, inScope, stderr) {
385
+ const preRead = [];
386
+ for (const relPath of inScope) {
387
+ const text = await readBounded(realRoot, relPath, MAX_FILE_BYTES, stderr);
388
+ preRead.push([relPath, text]);
389
+ }
390
+ return preRead;
391
+ }
392
+ //# sourceMappingURL=analysis.js.map
@@ -0,0 +1,163 @@
1
+ import type { Writable } from "node:stream";
2
+ /**
3
+ * The cognitive complexity engine (spec 005, FR-005 through FR-009;
4
+ * research R1, R7-R10, R12; Constitution Principles I, III, and
5
+ * IV): the SonarSource cognitive complexity score for every function record
6
+ * the shared extraction table produces. `cognitiveComplexity` (T016) closes
7
+ * the shared `prepareAnalysis` pipeline over that score — the SAME
8
+ * extraction set, scope, and ordering `computeComplexity` reports, so US2-2's
9
+ * parity guarantee is structural (a function has a cognitive score if and
10
+ * only if it has a cyclomatic one; no second extraction path to drift) — with
11
+ * the program-mode context's lifetime owned by this handler and closed in a
12
+ * `finally` exactly as `computeComplexity` closes its own.
13
+ *
14
+ * The scoring rules (FR-006's structural, flow-break, and recursion
15
+ * clauses + FR-007 nesting regions + FR-008 sequences + FR-009
16
+ * per-record domain), as the walk applies them:
17
+ *
18
+ * 1. **Increments**: `if`, `for`, `for-of`, `for-in`, `while`, `do`,
19
+ * `switch`, `catch`, and a conditional (ternary) expression each add 1
20
+ * plus the current nesting level; `else` and `else if` add 1 flat; `try`
21
+ * and `finally` add nothing; case clauses never increment (the enclosing
22
+ * `switch` takes the single increment). An empty body scores 0 — there is
23
+ * no baseline increment, unlike cyclomatic complexity.
24
+ * 2. **Nesting regions**: the interior of the `if` consequent, the
25
+ * else-if consequent, the `else` body, loop bodies, `switch` case
26
+ * clauses, `catch` blocks, and ternary branches is one level deeper,
27
+ * applying to constructs lexically inside the region — never to the
28
+ * region's own statement (an `else` is flat though it sits inside the
29
+ * `if`'s region; a `case` clause is flat though it sits inside the
30
+ * `switch`'s).
31
+ * 3. **Per-record domain** (FR-009, the same boundary the detector and the
32
+ * cyclomatic engine walk): the walk starts at the record's body node —
33
+ * the record's own node is never treated as a boundary — stops at nested
34
+ * extracted function-likes (each owns its own row), and continues through
35
+ * anonymous function-likes with the nesting level reset to 0 at the
36
+ * boundary (the `xs.map((x) => ...)` folding shape).
37
+ * 4. **Flat rules** (T024's phase-6 extension; FR-006's flow-break and
38
+ * recursion clauses + FR-008; research R7-R10): a logical operator
39
+ * sequence — `&&`, `||`, `??` — adds 1 per maximal run of the same
40
+ * operator in the flattened chain, with parenthesized subexpressions
41
+ * transparent to the flattening and sequences counted anywhere the
42
+ * walk reaches them, control-structure conditions included; a `break`
43
+ * or `continue` referencing a label adds 1 (the plain forms add
44
+ * nothing); and direct recursion — a call to the enclosing record's
45
+ * own name, bare `f(...)` or `this.m(...)` inside method `m` — adds 1
46
+ * per call site, matched binding-blind against the record's name
47
+ * (research R10: no checker dependency, so mode parity holds). All
48
+ * three increments are FLAT — no nesting term, unlike the structural
49
+ * constructs of item 1.
50
+ *
51
+ * Scope (T024): the structural clauses and the flat rules above are the
52
+ * full rule set — FR-006's flow-break and recursion clauses and FR-008's
53
+ * sequences have landed with the phase-6 extension;
54
+ * tests/cognitive.test.ts pins the FR-010 golden table these rules
55
+ * compute.
56
+ *
57
+ * The documented divergences from Gaze's Go port (spec 005 Assumption 3 —
58
+ * reading-stone follows SonarSource, the norm the protocol field cites):
59
+ * control-structure conditions are walked (Gaze does not), ternaries are
60
+ * scored (Go has none), labeled breaks are counted (Gaze does not), and
61
+ * nesting resets at anonymous function boundaries (Gaze carries nesting
62
+ * through function literals). The SonarJS lint carve-outs are not adopted
63
+ * (Assumption 4).
64
+ *
65
+ * No second AST depth budget: extraction already discarded any file whose
66
+ * AST could exceed its budget (a record exists only for an in-budget file),
67
+ * and this walk revisits exactly those materialized subtrees — the argument
68
+ * `complexity.ts` records for its own walk (research R12).
69
+ *
70
+ * Constitution alignment:
71
+ *
72
+ * - Principle I (Protocol Fidelity): rows serialize to the
73
+ * cognitive_complexity wire shape — package, function, file, line,
74
+ * cognitive_complexity — in the canonical sorted-key order the protocol
75
+ * layer's own serializer produces, so its pass is a structural no-op; the
76
+ * identity key is `function` (the coverage method's row shape and the
77
+ * protocol document's schema, Assumption 6), never `name`.
78
+ * - Principle III (TypeScript-Native Analysis): the score is a metric over
79
+ * the compiler's AST — exactly as cyclomatic complexity already is — and
80
+ * the type checker is never consulted, so program and parse-only modes
81
+ * score identically (mode parity, the optional-program degrade path kept
82
+ * whole).
83
+ * - Principle IV (Testability): the walk core is a pure
84
+ * ExtractionRecord-to-number function; the entry takes the injected
85
+ * (rootPath, patterns, stderr) surface and owns the program-context
86
+ * lifetime, so each is testable against a fixture tree in isolation.
87
+ * - Principle V (Analysis Safety): static analysis only — the walk reads
88
+ * the compiler's AST and never executes analyzed source.
89
+ */
90
+ /**
91
+ * One cognitive complexity row (FR-005): the extraction identity plus the
92
+ * computed SonarSource score. Field names mirror the wire payload exactly —
93
+ * the identity key is `function` (the coverage method's row shape and the
94
+ * protocol document's schema, Assumption 6), not `name` (the cyclomatic
95
+ * complexity method's) — snake_case included (`cognitive_complexity`, the
96
+ * MappingRow and FunctionRecord.side_effects precedent), and the entity is
97
+ * an immutable value record (convention pack AP-004).
98
+ */
99
+ export interface CognitiveRow {
100
+ /** Dotted module path derived by `derivePackage` from `file`. */
101
+ readonly package: string;
102
+ /**
103
+ * The function's declared name, carried as the wire `function` key — the
104
+ * identity-key spelling FR-005 pins (Assumption 6), never `name`.
105
+ */
106
+ readonly function: string;
107
+ /** Root-relative POSIX path of the declaring file. */
108
+ readonly file: string;
109
+ /** 1-based line of the function declaration. */
110
+ readonly line: number;
111
+ /** The SonarSource cognitive complexity score (an integer ≥ 0). */
112
+ readonly cognitive_complexity: number;
113
+ }
114
+ /**
115
+ * The `cognitive_complexity` method's entry (FR-005, FR-009; the
116
+ * analyze-shaped surface T018 established): the serialized `CognitiveRow[]`
117
+ * payload — one row per extraction record, assembled in the `(file, line,
118
+ * name)` total order, and mapped through `serializeCognitiveRow` so every
119
+ * row on the returned array is already wire-shaped.
120
+ *
121
+ * The returned array — not a `{functions: [...]}` wrapper — follows the
122
+ * computeComplexity split: the T017 server handler wraps the array into the
123
+ * cognitive_complexity result shape, exactly as it wraps the complexity
124
+ * entries. Both this entry and its payload are deterministic pure functions
125
+ * of the analyzed tree (Constitution Principle I: byte-identical repeat
126
+ * responses).
127
+ *
128
+ * The program-mode context's lifetime is this handler's: the native
129
+ * compiler server behind it is closed in the `finally` whatever the scoring
130
+ * outcome, so no subprocess outlives one analysis. A parse-only context
131
+ * owns nothing to dispose.
132
+ *
133
+ * @param rootPath Absolute or relative project root; validated and
134
+ * realpath-resolved by `prepareAnalysis` (an invalid root throws
135
+ * `InvalidRootPathError`, the server maps to `-32602`).
136
+ * @param patterns The raw `patterns` parameter value; shape-validated by
137
+ * the server (`-32602`) before analysis runs, normalized here.
138
+ * @param stderr Injected diagnostic sink (Testability principle); defaults
139
+ * to `process.stderr`. Stdout is never touched.
140
+ * @returns The serialized cognitive rows, `(file, line, name)`-sorted.
141
+ */
142
+ export declare function cognitiveComplexity(rootPath: string, patterns: unknown, stderr?: Writable): Promise<readonly Record<string, unknown>[]>;
143
+ /**
144
+ * Serializes a `CognitiveRow` to its wire shape (FR-005): exactly the five
145
+ * fields, emitted in the canonical sorted-key order the protocol layer's
146
+ * sorted-key serializer produces — so the server's `serialize` pass
147
+ * re-orders these keys as a structural no-op and each row is wire-final in
148
+ * the form that serializer defines.
149
+ *
150
+ * A pure projection, deliberately without the fail-loud field validation
151
+ * `models.ts`'s record serializers apply (the serializeComplexityEntry
152
+ * argument): every `CognitiveRow` is constructed at this module's single
153
+ * site from fields whose validity is structural — `ExtractionRecord`'s
154
+ * string `name`/`relPath`, a 1-based `line`, and `cognitive_complexity` as
155
+ * the walk's non-negative sum. The wire shape itself — exactly these five
156
+ * keys, integer `cognitive_complexity` ≥ 0 — is pinned by
157
+ * `tests/cognitive.test.ts`'s wire-invariant assertions.
158
+ *
159
+ * @param row The cognitive row to serialize.
160
+ * @returns A JSON-ready object with `cognitive_complexity`, `file`,
161
+ * `function`, `line`, and `package`.
162
+ */
163
+ export declare function serializeCognitiveRow(row: CognitiveRow): Record<string, unknown>;