reading-stone 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +11 -0
  3. package/README.md +274 -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 +54 -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,770 @@
1
+ // The pairing strategies and their first-match-wins evaluation loop (T016 +
2
+ // T025; FR-004/FR-005; research R4, R12; data-model.md Sections 5.3–5.4 and
3
+ // 6; Constitution Principles I, III, and V).
4
+ //
5
+ // Pairing connects a collected `TestFunction` (src/quality/collect.ts) to
6
+ // the `ExtractionRecord` targets it exercises. The `TargetIndex` is the
7
+ // pairing-support view over one pipeline run's prepared analysis — built
8
+ // once, consulted by every strategy — and the three strategies evaluate per
9
+ // test in fixed priority order (data-model Section 6):
10
+ //
11
+ // 1. `naming` (exact 90 / case-insensitive 70) — purely lexical: a test
12
+ // whose title or nearest enclosing describe title equals a target name
13
+ // pairs by convention (research R4's conventional-title tier, the
14
+ // highest-availability signal). No compiler queries, no I/O — the
15
+ // strategy runs identically in both `ProgramContext` modes.
16
+ // 2. `calls` (80) — the test's callback subtree contains a call resolving
17
+ // to the target. Checker mode resolves each callee through
18
+ // `checker.getSymbolAtLocation` (the verified surface
19
+ // src/signals/evidence.ts rides) with aliases followed through the
20
+ // shared `resolveSymbolAliases`, then matches the symbol's declaration
21
+ // against `byNode` — method and property callees included, the symbol
22
+ // identifies the declaring function. Parse-only matches the callee's
23
+ // terminal identifier text against target names (research R4's
24
+ // documented false-positive surface — degradation reduces precision,
25
+ // never availability).
26
+ // 3. `imports` (75) — the test FILE statically imports the target through
27
+ // a named import specifier AND references the binding outside the
28
+ // import clause (a lexical identifier scan in BOTH modes — the pinned
29
+ // precision concession: a per-identifier checker query would cost one
30
+ // round-trip per identifier per file, disproportionate to the
31
+ // 75-confidence evidence class). Checker mode resolves each specifier
32
+ // symbol with re-exports followed (edge case 7's barrel rule);
33
+ // parse-only resolves the module specifier against the test file's
34
+ // directory over the discovered in-root file set — the walk's six
35
+ // extensions and `index` forms, barrels uncrossed, package specifiers
36
+ // and root escapes resolving to nothing (the FR-004 containment guard:
37
+ // a pure key computation over the discovered set, never a filesystem
38
+ // probe — Constitution V). Every test in the file not already paired by
39
+ // a higher-priority strategy pairs with each referenced target.
40
+ //
41
+ // First-match-wins per test (FR-004/US2-7): evaluation stops at the first
42
+ // strategy with any match and only that strategy's pairs are emitted — a
43
+ // test paired by naming never evaluates calls or imports.
44
+ //
45
+ // Determinism (Constitution I): every emitted list is ordered by the
46
+ // analyze record order — `(file, line, name)` through
47
+ // `compareFileLineName` — so repeated runs over the same tree pair
48
+ // byte-identically. Checker traffic is pinned (research R4): one
49
+ // `getSymbolAtLocation` query per call expression inside test callbacks
50
+ // and per import specifier per test file, with the file-scoped import
51
+ // evidence memoized per `pairTests` call — never recomputed per test or
52
+ // per assertion.
53
+ //
54
+ // Every walk this module owns (the callback-subtree call scan, the
55
+ // whole-file reference scan) is depth-bounded by the shared
56
+ // `MAPPING_WALK_DEPTH_BUDGET` (F2; plan.md Scale/Scope): pathological
57
+ // input degrades to a per-test or per-file skip with exactly one
58
+ // diagnostic written to the injected stderr — never a request crash
59
+ // (Constitution V).
60
+ import { join, posix } from "node:path";
61
+ import { isCallExpression, isIdentifier, isImportDeclaration, isNamedImports, isPropertyAccessExpression, isStringLiteral, SyntaxKind, } from "typescript/unstable/ast";
62
+ import { WALKED_EXTENSIONS } from "../discovery.js";
63
+ import { compareFileLineName, MAPPING_WALK_DEPTH_BUDGET } from "../internal.js";
64
+ import { derivePackage } from "../models.js";
65
+ import { resolveSymbolAliases } from "../program.js";
66
+ /**
67
+ * Builds the pairing-support `TargetIndex` over one pipeline run's
68
+ * prepared analysis (data-model.md Section 5.4).
69
+ *
70
+ * The records are sorted by the analyze record order —
71
+ * `compareFileLineName` over `(relPath, line, name)` — so `records` and
72
+ * every `byName` list are deterministic and match `analyze`'s reported
73
+ * order even when a caller (hand-built test fixtures included) passes an
74
+ * unsorted list. The sort is idempotent over `prepareAnalysis` output,
75
+ * which is already in that order.
76
+ *
77
+ * @param records The in-scope source records (the identical `analyze`
78
+ * set, FR-006's target parity).
79
+ * @param effects The `detectEffects` output per record.
80
+ * @param context The live `ProgramContext` of the same run; lent
81
+ * read-only, never disposed here.
82
+ * @returns The index every pairing strategy consults.
83
+ */
84
+ export function buildTargetIndex(records, effects, context) {
85
+ const ordered = [...records].sort((a, b) => compareFileLineName({ file: a.relPath, line: a.line, name: a.name }, { file: b.relPath, line: b.line, name: b.name }));
86
+ const byName = new Map();
87
+ const byNode = new Map();
88
+ for (const record of ordered) {
89
+ const list = byName.get(record.name);
90
+ if (list === undefined) {
91
+ byName.set(record.name, [record]);
92
+ }
93
+ else {
94
+ list.push(record);
95
+ }
96
+ // First-wins on a node-key collision: real extraction never produces
97
+ // two records for one function-like node, so a collision only arises
98
+ // in hand-built inputs — and the record order is the canonical one,
99
+ // so the first record in that order owns the key (a later `set` would
100
+ // silently flip the answer to whichever record sorted last).
101
+ if (!byNode.has(record.node)) {
102
+ byNode.set(record.node, record);
103
+ }
104
+ }
105
+ return { records: ordered, byName, byNode, effects, context };
106
+ }
107
+ /** The naming strategy's exact-tier confidence (case-sensitive title match). */
108
+ const NAMING_EXACT_CONFIDENCE = 90;
109
+ /** The naming strategy's case-insensitive-only tier confidence. */
110
+ const NAMING_FOLD_CONFIDENCE = 70;
111
+ /** The calls strategy's confidence (a callback-subtree call resolving to the target). */
112
+ const CALLS_CONFIDENCE = 80;
113
+ /** The imports strategy's confidence (a referenced named import of the target). */
114
+ const IMPORTS_CONFIDENCE = 75;
115
+ /**
116
+ * The strategy walks' depth sentinel (F2): raised when the callback-subtree
117
+ * call scan or the whole-file reference scan passes the shared
118
+ * `MAPPING_WALK_DEPTH_BUDGET`, caught at the owning strategy boundary —
119
+ * never escapes this module (the extract.ts `AstDepthExceeded` discipline).
120
+ * A `RangeError` from lazy node materialization is caught at the same site
121
+ * and treated identically.
122
+ */
123
+ class MappingWalkDepthExceeded extends Error {
124
+ constructor() {
125
+ super("ast depth exceeds budget");
126
+ }
127
+ }
128
+ /**
129
+ * Builds the case-folded name view over the index's records — one scan,
130
+ * record order preserved by construction (the input is
131
+ * `compareFileLineName`-sorted), so the fold tier's output needs no
132
+ * re-sort.
133
+ */
134
+ function buildFoldedNameIndex(index) {
135
+ const folded = new Map();
136
+ for (const record of index.records) {
137
+ const key = record.name.toLowerCase();
138
+ const list = folded.get(key);
139
+ if (list === undefined) {
140
+ folded.set(key, [record]);
141
+ }
142
+ else {
143
+ list.push(record);
144
+ }
145
+ }
146
+ return folded;
147
+ }
148
+ /**
149
+ * Collects a match set back into the analyze record order: filters the
150
+ * index's `(file, line, name)`-sorted records by membership, so every
151
+ * strategy's output follows FR-005's deterministic order regardless of
152
+ * how the matches were gathered (title and describe contributions
153
+ * merge, same-named targets stream in record order).
154
+ *
155
+ * @param index The target index whose `records` supply the order.
156
+ * @param matches The matched records, in any order.
157
+ * @returns The matched records in `(file, line, name)` order.
158
+ */
159
+ function inRecordOrder(index, matches) {
160
+ return index.records.filter((record) => matches.has(record));
161
+ }
162
+ /**
163
+ * The naming strategy (FR-004/FR-005's naming tier; research R4;
164
+ * data-model.md Section 6): a test whose title OR nearest enclosing
165
+ * describe title equals a target name pairs — the match rule is a
166
+ * disjunction, both candidate names contributing their matches at the
167
+ * same tier.
168
+ *
169
+ * Tiering is per test (research R4): the exact tier (case-sensitive
170
+ * equality) shadows the case-insensitive tier — a test matching one
171
+ * target exactly and another case-insensitively emits only the exact
172
+ * pairs at `90`. With no exact match, the case-insensitive tier
173
+ * (`toLowerCase` both sides, no locale fold) pairs at `70`. A test
174
+ * matched by neither tier produces no pairs — never confidence-0 rows.
175
+ *
176
+ * Only the NEAREST enclosing describe title is consulted (data-model
177
+ * Section 5.1): outer levels qualify the title, never pair it. An empty
178
+ * title or describe segment matches nothing — extraction names are
179
+ * never empty, so the lookup is structurally miss-free.
180
+ *
181
+ * @param test The collected test function.
182
+ * @param index The pairing-support target index.
183
+ * @param folded The case-folded name view shared across the call's tests.
184
+ * @returns The naming pairs, in analyze record order — `[]` when the
185
+ * strategy matches nothing (evaluation falls through to the next
186
+ * strategy).
187
+ */
188
+ function namingPairs(test, index, folded) {
189
+ // The two candidate names (data-model Section 5.1): the title, and
190
+ // the nearest enclosing describe title when one exists.
191
+ const candidates = new Set([test.title]);
192
+ if (test.describeTitles.length > 0) {
193
+ candidates.add(test.describeTitles[test.describeTitles.length - 1] ?? "");
194
+ }
195
+ const exact = new Set();
196
+ for (const name of candidates) {
197
+ for (const record of index.byName.get(name) ?? []) {
198
+ exact.add(record);
199
+ }
200
+ }
201
+ if (exact.size > 0) {
202
+ return inRecordOrder(index, exact).map((target) => ({
203
+ test,
204
+ target,
205
+ strategy: "naming",
206
+ confidence: NAMING_EXACT_CONFIDENCE,
207
+ }));
208
+ }
209
+ const fold = new Set();
210
+ for (const name of candidates) {
211
+ for (const record of folded.get(name.toLowerCase()) ?? []) {
212
+ fold.add(record);
213
+ }
214
+ }
215
+ if (fold.size > 0) {
216
+ return inRecordOrder(index, fold).map((target) => ({
217
+ test,
218
+ target,
219
+ strategy: "naming",
220
+ confidence: NAMING_FOLD_CONFIDENCE,
221
+ }));
222
+ }
223
+ return [];
224
+ }
225
+ /**
226
+ * The per-test pair-key first-wins dedup (FR-005 amended; iteration-2
227
+ * review fix F1, extended iteration-3 to the derived wire key): within
228
+ * ONE test function's emitted pairs, the wire pair key
229
+ * `(test_function, test_file, target_package, target_function)` is
230
+ * unique. The test side is constant within one test's pairs, and the
231
+ * row's `target_package` is derived from the target's file — a pure
232
+ * function of `relPath` — so the key reduces here to the derived wire
233
+ * identity `(derivePackage(relPath), name)`. `derivePackage` is NOT
234
+ * injective over files (same-stem different extensions
235
+ * `util.js`/`util.cjs`; a dot in a stem vs a nested directory
236
+ * `a.b.ts`/`a/b.ts`; a file vs its directory index
237
+ * `pkg.ts`/`pkg/index.ts`), so two distinct records that share one file
238
+ * and one declared name (same-named methods of different classes) OR
239
+ * that sit in different files whose paths derive the same package while
240
+ * sharing the declared name, are wire-indistinguishable targets — and
241
+ * only the FIRST in the strategy's record-ordered emission survives —
242
+ * the `byNode` first-wins discipline. The collapse is a documented
243
+ * conservative imprecision: later wire-indistinguishable records emit
244
+ * no pairs and no rows.
245
+ *
246
+ * The dedup domain is deliberately the test function, never the bare
247
+ * wire tuple: same-titled sibling tests inside one describe (spec edge
248
+ * case 2) share `test_function` but are distinct test functions, each
249
+ * keeping its own pairs (their rows disambiguate downstream through
250
+ * `assertion_location`). Strategy-agnostic by construction — whatever
251
+ * the winning strategy emitted gets deduped — so the US2 calls/imports
252
+ * tiers inherit the rule without re-plumbing.
253
+ *
254
+ * @param testPairs One test's emitted pairs, in record order.
255
+ * @returns The deduplicated pairs — order and first-wins preserved.
256
+ */
257
+ function dedupeByPairKey(testPairs) {
258
+ const seen = new Set();
259
+ const kept = [];
260
+ for (const pair of testPairs) {
261
+ // The derived wire identity, not (relPath, name): colliding-package
262
+ // files (pkg.ts vs pkg/index.ts) derive one target_package, so the
263
+ // key must collapse them exactly like the same-file case — the
264
+ // iteration-3 F1 amendment (data-model.md Section 6).
265
+ const key = `${derivePackage(pair.target.relPath)}\0${pair.target.name}`;
266
+ if (seen.has(key)) {
267
+ continue;
268
+ }
269
+ seen.add(key);
270
+ kept.push(pair);
271
+ }
272
+ return kept;
273
+ }
274
+ /**
275
+ * Resolves one test file's parsed source in either bootstrap mode — the
276
+ * collect.ts `resolveTestSources` route for a single path: parse-only
277
+ * sources are keyed by root-relative path already; program-mode source
278
+ * names are the compiler's absolute file names, spelled exactly as the
279
+ * extender config's `files` root set spelled them — `join(realRoot,
280
+ * relPath)` — so the same join resolves them back.
281
+ *
282
+ * @param relPath The test file's root-relative POSIX path.
283
+ * @param context The bootstrapped `ProgramContext` of the same run.
284
+ * @param rootPath Realpath-resolved absolute analysis root — the
285
+ * program-mode source-name base.
286
+ * @returns The file's parsed source, or undefined when absent from the
287
+ * bootstrap (a pre-read skip whose diagnostic readBounded already wrote).
288
+ */
289
+ function testSourceFile(relPath, context, rootPath) {
290
+ if (context.mode === "parse-only") {
291
+ return context.sources.get(relPath);
292
+ }
293
+ return context.program.getSourceFile(join(rootPath, relPath));
294
+ }
295
+ /**
296
+ * The calls strategy (FR-004/FR-005's calls tier; research R4; data-model
297
+ * Section 6): the test's callback subtree is scanned for `CallExpression`s
298
+ * — nested function expressions inside the callback included, exactly the
299
+ * assertion walk's scan domain — and each distinct target reached pairs at
300
+ * `80`, in analyze record order.
301
+ *
302
+ * Checker mode resolves each callee through `getSymbolAtLocation` and
303
+ * matches the resolved symbol's declaration against `byNode` (one query
304
+ * per call expression — the pinned traffic bound); parse-only matches the
305
+ * callee's terminal identifier text against target names (documented
306
+ * false-positive surface). A test whose callback argument is a bare
307
+ * identifier reference (no subtree) has no call evidence — the truthful
308
+ * empty result, never a scan of the referenced function's body.
309
+ *
310
+ * The walk is depth-bounded (F2): a pathological callback discards only
311
+ * THIS test's call pairs — the assertion walk's per-test skip unit — with
312
+ * exactly one diagnostic to `stderr`.
313
+ *
314
+ * @param test The collected test function.
315
+ * @param index The pairing-support target index.
316
+ * @param stderr The diagnostic sink for depth-budget skips.
317
+ * @returns The calls pairs, in analyze record order — `[]` when the
318
+ * strategy matches nothing (evaluation falls through to imports).
319
+ */
320
+ function callsPairs(test, index, stderr) {
321
+ const callback = test.callback;
322
+ if (callback === null) {
323
+ return [];
324
+ }
325
+ const matches = new Set();
326
+ try {
327
+ walkForCalls(callback, index, matches, 0);
328
+ }
329
+ catch (error) {
330
+ // Only the depth sentinel and a materialization RangeError are
331
+ // diagnosed skips; anything else escapes (a crash is never a silent
332
+ // skip — the collectAssertions rethrow discipline).
333
+ if (!(error instanceof MappingWalkDepthExceeded || error instanceof RangeError)) {
334
+ throw error;
335
+ }
336
+ stderr.write(`reading-stone: skipping call pairing in ${test.relPath}:${test.line}: ast depth exceeds budget\n`);
337
+ return [];
338
+ }
339
+ if (matches.size === 0) {
340
+ return [];
341
+ }
342
+ return inRecordOrder(index, matches).map((target) => ({
343
+ test,
344
+ target,
345
+ strategy: "calls",
346
+ confidence: CALLS_CONFIDENCE,
347
+ }));
348
+ }
349
+ /**
350
+ * The calls walk: a post-order descent over the test's callback subtree
351
+ * (children before the node — the assertion walk's discipline), collecting
352
+ * every `CallExpression`'s target match. Depth-bounded by the shared
353
+ * `MAPPING_WALK_DEPTH_BUDGET`; the sentinel raised past the budget is
354
+ * caught by `callsPairs`' per-test skip.
355
+ *
356
+ * @param node The subtree root (the test's callback).
357
+ * @param index The pairing-support target index.
358
+ * @param matches The matched records, gathered as a set.
359
+ * @param depth The current nesting depth (0 at the callback root).
360
+ */
361
+ function walkForCalls(node, index, matches, depth) {
362
+ if (depth > MAPPING_WALK_DEPTH_BUDGET) {
363
+ throw new MappingWalkDepthExceeded();
364
+ }
365
+ node.forEachChild((child) => {
366
+ walkForCalls(child, index, matches, depth + 1);
367
+ });
368
+ if (!isCallExpression(node)) {
369
+ return;
370
+ }
371
+ collectCallTarget(node, index, matches);
372
+ }
373
+ /**
374
+ * Resolves one call expression's callee to target records, per mode
375
+ * (research R4): checker mode through the symbol route, parse-only through
376
+ * terminal-identifier name matching.
377
+ *
378
+ * The query node both modes read is the callee's terminal identifier — the
379
+ * callee identifier itself for a plain call (`add(...)`), the invoked
380
+ * property's name for a method or property callee (`calc.add(...)`):
381
+ * checker mode queries the checker AT that identifier (the symbol
382
+ * identifies the declaring function — method and property callees
383
+ * included, the verified route with aliases followed), while parse-only
384
+ * reads its text against `byName`. Every other callee form (an element
385
+ * access, a call-rooted chain) contributes nothing in either mode.
386
+ *
387
+ * @param call The collected call expression.
388
+ * @param index The pairing-support target index.
389
+ * @param matches The matched records, gathered as a set.
390
+ */
391
+ function collectCallTarget(call, index, matches) {
392
+ const callee = call.expression;
393
+ const terminal = isIdentifier(callee)
394
+ ? callee
395
+ : isPropertyAccessExpression(callee)
396
+ ? callee.name
397
+ : null;
398
+ if (terminal === null) {
399
+ return;
400
+ }
401
+ if (index.context.mode === "program") {
402
+ const { checker } = index.context;
403
+ const symbol = checker.getSymbolAtLocation(terminal);
404
+ const resolved = resolveSymbolAliases(checker, symbol);
405
+ if (resolved === null) {
406
+ return;
407
+ }
408
+ for (const declaration of resolved.declarations) {
409
+ const declarationNode = declaration.resolve();
410
+ const record = declarationNode === undefined ? undefined : index.byNode.get(declarationNode);
411
+ if (record !== undefined) {
412
+ matches.add(record);
413
+ }
414
+ }
415
+ return;
416
+ }
417
+ for (const record of index.byName.get(terminal.text) ?? []) {
418
+ matches.add(record);
419
+ }
420
+ }
421
+ /**
422
+ * The imports tier's file-scoped evidence (FR-004/FR-005's imports tier;
423
+ * research R4; data-model Section 6): the target records this test file
424
+ * statically imports through named specifiers AND references outside the
425
+ * import clause, in analyze record order — `[]` when none.
426
+ *
427
+ * The order of operations is deliberate: the reference scan runs FIRST
428
+ * (the cheap, mode-independent lexical pass), so an unused import is dead
429
+ * evidence (US2-5) that never reaches the checker queries or the
430
+ * parse-only record matching — the unreferenced specifier costs nothing.
431
+ * The reference scan is depth-bounded (F2): a pathological file discards
432
+ * its whole import evidence with exactly one diagnostic (per-file skip —
433
+ * its tests fall through to unpaired, never a crash).
434
+ *
435
+ * @param tier The imports tier's per-run state.
436
+ * @param relPath The test file's root-relative POSIX path.
437
+ * @returns The referenced imported targets, in analyze record order.
438
+ */
439
+ function importedTargetsFor(tier, relPath) {
440
+ const sourceFile = testSourceFile(relPath, tier.index.context, tier.rootPath);
441
+ if (sourceFile === undefined) {
442
+ return [];
443
+ }
444
+ const bindings = namedImportBindings(sourceFile);
445
+ if (bindings.length === 0) {
446
+ return [];
447
+ }
448
+ let referencedNames;
449
+ try {
450
+ referencedNames = collectReferencedNames(sourceFile);
451
+ }
452
+ catch (error) {
453
+ if (!(error instanceof MappingWalkDepthExceeded || error instanceof RangeError)) {
454
+ throw error;
455
+ }
456
+ tier.stderr.write(`reading-stone: skipping import pairing in ${relPath}: ast depth exceeds budget\n`);
457
+ return [];
458
+ }
459
+ const matches = new Set();
460
+ for (const binding of bindings) {
461
+ if (!referencedNames.has(binding.localName)) {
462
+ // US2-5: an unused import is dead evidence — pairs nothing.
463
+ continue;
464
+ }
465
+ collectImportTargets(tier, relPath, binding, matches);
466
+ }
467
+ if (matches.size === 0) {
468
+ return [];
469
+ }
470
+ return inRecordOrder(tier.index, matches);
471
+ }
472
+ /**
473
+ * Collects the file's named-import bindings — a statement-level scan (no
474
+ * recursion, so no depth budget): import declarations are top-level only,
475
+ * and the named-specifier elements are read directly off each clause.
476
+ * Type-only imports are skipped (the whole-clause `import type` form and
477
+ * the inline `{ type X }` element form alike): the erased binding names a
478
+ * type, never a runtime target. Default and namespace imports carry no
479
+ * named specifier and contribute nothing (a default-imported or
480
+ * namespace-referenced function still pairs through the calls tier, whose
481
+ * callee resolution is import-form-agnostic).
482
+ *
483
+ * @param sourceFile The test file's parsed source.
484
+ * @returns The named-import bindings, in source order.
485
+ */
486
+ function namedImportBindings(sourceFile) {
487
+ const bindings = [];
488
+ for (const statement of sourceFile.statements) {
489
+ if (!isImportDeclaration(statement)) {
490
+ continue;
491
+ }
492
+ const clause = statement.importClause;
493
+ // The whole-clause `import type` form: TS 7's native AST spells the
494
+ // erased marker as the clause's `type` phase modifier, not a boolean.
495
+ if (clause === undefined || clause.phaseModifier === SyntaxKind.TypeKeyword) {
496
+ continue;
497
+ }
498
+ const moduleSpecifier = isStringLiteral(statement.moduleSpecifier)
499
+ ? statement.moduleSpecifier.text
500
+ : null;
501
+ if (moduleSpecifier === null) {
502
+ continue;
503
+ }
504
+ const named = clause.namedBindings;
505
+ if (named === undefined || !isNamedImports(named)) {
506
+ continue;
507
+ }
508
+ for (const specifier of named.elements) {
509
+ if (specifier.isTypeOnly) {
510
+ continue;
511
+ }
512
+ bindings.push({
513
+ specifier,
514
+ moduleSpecifier,
515
+ localName: specifier.name.text,
516
+ importedName: specifier.propertyName?.text ?? specifier.name.text,
517
+ });
518
+ }
519
+ }
520
+ return bindings;
521
+ }
522
+ /**
523
+ * The reference-presence scan (research R4's pinned precision concession):
524
+ * every identifier text appearing ANYWHERE in the file outside the import
525
+ * clauses — a single whole-file walk, both modes, never per-identifier
526
+ * checker queries. Deliberately coarse: a same-named property or a
527
+ * shadowed local counts as a reference (the documented conservative
528
+ * imprecision — availability over precision at the 75 tier).
529
+ *
530
+ * @param sourceFile The test file's parsed source.
531
+ * @returns The referenced identifier texts (import clauses excluded).
532
+ */
533
+ function collectReferencedNames(sourceFile) {
534
+ const names = new Set();
535
+ const walk = (node, depth) => {
536
+ if (depth > MAPPING_WALK_DEPTH_BUDGET) {
537
+ throw new MappingWalkDepthExceeded();
538
+ }
539
+ node.forEachChild((child) => {
540
+ walk(child, depth + 1);
541
+ });
542
+ if (isIdentifier(node)) {
543
+ names.add(node.text);
544
+ }
545
+ };
546
+ for (const statement of sourceFile.statements) {
547
+ if (isImportDeclaration(statement)) {
548
+ continue;
549
+ }
550
+ walk(statement, 0);
551
+ }
552
+ return names;
553
+ }
554
+ /**
555
+ * Resolves one referenced import binding to target records, per mode
556
+ * (research R4): checker mode through the specifier symbol with re-exports
557
+ * followed (edge case 7's barrel rule — the alias chain lands on the
558
+ * declaring function's node); parse-only through module-specifier path
559
+ * resolution over the discovered in-root file set, then imported-name
560
+ * matching against the records in the resolved file.
561
+ *
562
+ * @param tier The imports tier's per-run state.
563
+ * @param relPath The test file's root-relative POSIX path.
564
+ * @param binding The referenced import binding.
565
+ * @param matches The matched records, gathered as a set.
566
+ */
567
+ function collectImportTargets(tier, relPath, binding, matches) {
568
+ if (tier.index.context.mode === "program") {
569
+ const { checker } = tier.index.context;
570
+ const symbol = checker.getSymbolAtLocation(binding.specifier.name);
571
+ const resolved = resolveSymbolAliases(checker, symbol);
572
+ if (resolved === null) {
573
+ return;
574
+ }
575
+ for (const declaration of resolved.declarations) {
576
+ const declarationNode = declaration.resolve();
577
+ const record = declarationNode === undefined
578
+ ? undefined
579
+ : tier.index.byNode.get(declarationNode);
580
+ if (record !== undefined) {
581
+ matches.add(record);
582
+ }
583
+ }
584
+ return;
585
+ }
586
+ const resolvedPath = resolveSpecifierPath(tier, relPath, binding.moduleSpecifier);
587
+ if (resolvedPath === null) {
588
+ return;
589
+ }
590
+ const fileRecords = recordsByFileView(tier).get(resolvedPath);
591
+ for (const record of fileRecords?.get(binding.importedName) ?? []) {
592
+ matches.add(record);
593
+ }
594
+ }
595
+ /**
596
+ * The parse-only records-by-file view: root-relative path → declared name →
597
+ * the records carrying it, in record order (the input is
598
+ * `compareFileLineName`-sorted, so the lists need no re-sort). Built once
599
+ * per `pairTests` call, lazily — the checker-mode run never builds it.
600
+ *
601
+ * @param tier The imports tier's per-run state.
602
+ * @returns The `(relPath, name)` record view.
603
+ */
604
+ function recordsByFileView(tier) {
605
+ if (tier.recordsByFile === null) {
606
+ const view = new Map();
607
+ for (const record of tier.index.records) {
608
+ let names = view.get(record.relPath);
609
+ if (names === undefined) {
610
+ names = new Map();
611
+ view.set(record.relPath, names);
612
+ }
613
+ const list = names.get(record.name);
614
+ if (list === undefined) {
615
+ names.set(record.name, [record]);
616
+ }
617
+ else {
618
+ list.push(record);
619
+ }
620
+ }
621
+ tier.recordsByFile = view;
622
+ }
623
+ return tier.recordsByFile;
624
+ }
625
+ /**
626
+ * The parse-only module-specifier path resolution (research R4; data-model
627
+ * Section 6's containment pin): a pure key computation over the discovered
628
+ * in-root file set — never a filesystem probe (Constitution V).
629
+ *
630
+ * Only relative specifiers (`./`, `../`) resolve; package specifiers
631
+ * (`node:...`, bare package names) denote no in-root target and resolve to
632
+ * nothing. The specifier is joined against the test file's directory and
633
+ * normalized lexically (POSIX — the relPath discipline); a resolved path
634
+ * escaping the analysis root (leading `..`) or absolute resolves to
635
+ * nothing. The candidate enumeration, in order: the bare resolved path (a
636
+ * specifier naming a discovered file exactly), then the walk's six
637
+ * extensions, then the `index` forms — discovery's own
638
+ * `WALKED_EXTENSIONS` order, so resolution and discovery can never
639
+ * disagree about which extensions name an in-root module. The first
640
+ * candidate present in the discovered set wins; a `.js`-suffixed
641
+ * specifier naming a `.ts` file does not substitute (the documented
642
+ * boundary — extensionless specifiers resolve through the enumeration).
643
+ *
644
+ * @param tier The imports tier's per-run state (carries the parse-only
645
+ * sources map — the discovered in-root file set).
646
+ * @param testRelPath The test file's root-relative POSIX path.
647
+ * @param moduleSpecifier The module specifier text, unquoted.
648
+ * @returns The resolved root-relative POSIX path, or null when the
649
+ * specifier resolves to nothing.
650
+ */
651
+ function resolveSpecifierPath(tier, testRelPath, moduleSpecifier) {
652
+ if (!moduleSpecifier.startsWith("./") && !moduleSpecifier.startsWith("../")) {
653
+ return null;
654
+ }
655
+ // `join` normalizes the joined segments lexically, so ".." components
656
+ // resolve away ("tests" + "../src/math" → "src/math").
657
+ const resolved = posix.join(posix.dirname(testRelPath), moduleSpecifier);
658
+ // The containment guard: the literal ".." test errs toward rejecting (the
659
+ // relativeUnderBase precedent — even an in-base sibling such as
660
+ // "..hidden.ts" is refused rather than risk an escape).
661
+ if (resolved === "" || resolved.startsWith("..") || posix.isAbsolute(resolved)) {
662
+ return null;
663
+ }
664
+ // The discovered in-root file set: the parse-only sources map. The
665
+ // resolver runs only from collectImportTargets' parse-only branch, but
666
+ // that narrowing does not cross the call boundary — the guard here makes
667
+ // the access total instead of trusted.
668
+ const context = tier.index.context;
669
+ if (context.mode !== "parse-only") {
670
+ return null;
671
+ }
672
+ const knownFiles = context.sources;
673
+ if (knownFiles.has(resolved)) {
674
+ return resolved;
675
+ }
676
+ for (const extension of WALKED_EXTENSIONS) {
677
+ const candidate = `${resolved}${extension}`;
678
+ if (knownFiles.has(candidate)) {
679
+ return candidate;
680
+ }
681
+ }
682
+ for (const extension of WALKED_EXTENSIONS) {
683
+ const candidate = `${resolved}/index${extension}`;
684
+ if (knownFiles.has(candidate)) {
685
+ return candidate;
686
+ }
687
+ }
688
+ return null;
689
+ }
690
+ /**
691
+ * Pairs the collected test functions with their target records
692
+ * (FR-004/FR-005): per test, the strategies evaluate in fixed priority
693
+ * order — naming → calls → imports — first-match-wins: evaluation stops
694
+ * at the first strategy with any match, and only that strategy's pairs
695
+ * are emitted (a test paired by naming never evaluates calls or imports;
696
+ * a test paired by calls never evaluates imports). Each test's winning
697
+ * emission flows through the per-test pair-key first-wins dedup
698
+ * (`dedupeByPairKey`, FR-005's amended soundness pin).
699
+ *
700
+ * The imports tier is file-scoped: its evidence (the referenced imported
701
+ * targets) is memoized per test file inside this call, computed only when
702
+ * a test actually reaches the third tier — never recomputed per test, and
703
+ * never at all for a file whose every test pairs by naming or calls
704
+ * (research R4's pinned traffic bound: one `getSymbolAtLocation` query
705
+ * per import specifier per test file).
706
+ *
707
+ * Each test pairs independently — one test's matches never affect
708
+ * another's — and unpaired tests produce no pairs, never confidence-0
709
+ * rows. Every walk the tiers own is depth-bounded by the shared
710
+ * `MAPPING_WALK_DEPTH_BUDGET` (F2), with per-test and per-file skips
711
+ * diagnosed to `stderr`.
712
+ *
713
+ * @param tests The collected test functions (the collector's sorted output).
714
+ * @param index The pairing-support target index for the same run.
715
+ * @param rootPath Realpath-resolved absolute analysis root — the
716
+ * program-mode source-name base for the file-scoped import walk (the
717
+ * collect.ts threading precedent: passed explicitly, never re-derived;
718
+ * never consulted in parse-only mode).
719
+ * @param stderr The diagnostic sink for depth-budget skips (the server's
720
+ * stderr; never stdout — protocol fidelity).
721
+ * @returns The pairs: per test in input order, each test's matches in
722
+ * analyze record order `(file, line, name)`, wire-indistinguishable
723
+ * targets (same-file and colliding-package same-named records alike)
724
+ * collapsed to the first record.
725
+ */
726
+ export function pairTests(tests, index, rootPath, stderr = process.stderr) {
727
+ const pairs = [];
728
+ // The folded name view is shared across every test in the call — one
729
+ // scan of the records, not one per test (the strategy reads it; it
730
+ // owns no other per-call state).
731
+ const folded = buildFoldedNameIndex(index);
732
+ // The imports tier's per-run state: file-scoped evidence memoized per
733
+ // test file, the parse-only record view built lazily on first need.
734
+ const importsTier = {
735
+ index,
736
+ rootPath,
737
+ stderr,
738
+ evidenceByFile: new Map(),
739
+ recordsByFile: null,
740
+ };
741
+ for (const test of tests) {
742
+ // Priority 1 — naming (purely lexical, mode-independent).
743
+ const named = dedupeByPairKey(namingPairs(test, index, folded));
744
+ if (named.length > 0) {
745
+ pairs.push(...named);
746
+ continue;
747
+ }
748
+ // Priority 2 — calls (the test's own callback subtree).
749
+ const called = dedupeByPairKey(callsPairs(test, index, stderr));
750
+ if (called.length > 0) {
751
+ pairs.push(...called);
752
+ continue;
753
+ }
754
+ // Priority 3 — imports (file-scoped evidence, memoized per file).
755
+ if (!importsTier.evidenceByFile.has(test.relPath)) {
756
+ importsTier.evidenceByFile.set(test.relPath, importedTargetsFor(importsTier, test.relPath));
757
+ }
758
+ const imported = dedupeByPairKey((importsTier.evidenceByFile.get(test.relPath) ?? []).map((target) => ({
759
+ test,
760
+ target,
761
+ strategy: "imports",
762
+ confidence: IMPORTS_CONFIDENCE,
763
+ })));
764
+ if (imported.length > 0) {
765
+ pairs.push(...imported);
766
+ }
767
+ }
768
+ return pairs;
769
+ }
770
+ //# sourceMappingURL=pairing.js.map