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,323 @@
1
+ import { derivePackage } from "../models.js";
2
+ import { TIER_MAP } from "../taxonomy.js";
3
+ import { callerSignal } from "./caller.js";
4
+ import { interfaceSignal } from "./interface.js";
5
+ import { docstringSignal } from "./jsdoc.js";
6
+ import { namingSignal } from "./naming.js";
7
+ import { visibilitySignal } from "./visibility.js";
8
+ /**
9
+ * The classification fan-out core (FR-008 through FR-011; research R8, R9,
10
+ * R10; data-model.md Sections 4, 5.4) — the shared engine both consumers of
11
+ * classification ride: the `analyze` method's handler (T025) and the
12
+ * `classify_signals` entry (T029).
13
+ *
14
+ * Three responsibilities, one seam:
15
+ *
16
+ * - **Fan-out (FR-008)**: the five pure extractors (interface, visibility,
17
+ * caller, naming, docstring) run exactly once per (function record,
18
+ * canonical effect type) PAIR — never per effect instance. Same-type
19
+ * instances share one pair run, so they share identical signals and an
20
+ * identical classification; distinct types on one record run
21
+ * independently. Extractor results are never deduplicated across
22
+ * sources. A record absent from the effects map is benign no-pairs (the
23
+ * `?? []` default `detectEffects` itself uses internally), while a record
24
+ * without an evidence snapshot fails loud (`buildRecordEvidence` keys
25
+ * every record, so a miss is an upstream bug).
26
+ * - **Contradiction (FR-011)**: a pair whose extractor signals mix at least
27
+ * one positive and at least one negative weight carries exactly ONE
28
+ * synthesized `contradiction` row — weight −20, the pair's identity
29
+ * fields, a fixed-template reasoning — applied exactly once however many
30
+ * signals of either polarity fired. The row is the wire realization of
31
+ * the formula's separate −20 term: a consumer summing ALL emitted signals
32
+ * for the pair (contradiction included) reproduces the reported
33
+ * confidence.
34
+ * - **Formula (FR-009/FR-010)**: `clamp(0, 100, 50 + tierBoost +
35
+ * Σ(extractor weights) − (contradiction ? 20 : 0))` with the tier read
36
+ * from `TIER_MAP` — the taxonomy is the single tier authority, never a
37
+ * second tier table — and labels contractual ≥ 80, ambiguous [50, 80),
38
+ * incidental < 50.
39
+ *
40
+ * The adapter also owns FR-014's emitter-side ordering: every feed it
41
+ * returns is sorted by the four-key `(package, function, side_effect_type,
42
+ * source)` codepoint comparison. Pair keying keeps that key duplicate-free
43
+ * (at most one signal per source per pair), which is what lets the total
44
+ * order carry no tie-break rule and what keeps a Gaze consumer's
45
+ * pair-matching join unambiguous.
46
+ *
47
+ * Composition contract (research R10; research R12's seam): this module is
48
+ * the CORE only — `classifyBundle` and `classifyPairs` below, a pure
49
+ * function of (records, effects, evidence): no `ProgramContext`, no I/O,
50
+ * no checker (one value import per extractor plus `TIER_MAP` and
51
+ * `derivePackage` are its structural proof, and the exhaustively
52
+ * hand-built snapshots of tests/signals/adapter.test.ts are what that
53
+ * purity buys). The WIRING belongs to the two method entries that consume
54
+ * the core — `analyze` (T025) and `classifySignals` (T029), both in
55
+ * src/analysis.ts beside the `prepareAnalysis` pipeline they close over —
56
+ * in one order, while the program-mode context is still live:
57
+ *
58
+ * 1. `detectEffects(records, context)` — the detector's per-record map.
59
+ * 2. `buildRecordEvidence(context, records, inScopePaths, rootPath)` — the
60
+ * evidence snapshots, caller index included, taken before any context
61
+ * disposal.
62
+ * 3. `classifyPairs(records, effects, evidence)` — this module's core.
63
+ * 4. `assembleFunctionRecords` + `serializeFunctionRecord` (`analyze`) /
64
+ * feed serialization (`classifySignals`) — each entry's own assembly,
65
+ * both in src/analysis.ts.
66
+ *
67
+ * Both entries living in src/analysis.ts keeps the module dependency
68
+ * strictly one-directional (convention pack AP-005: circular dependencies
69
+ * MUST NOT exist between modules): analysis imports the core from this
70
+ * module, and nothing here imports analysis back — the imports above are
71
+ * the extractors', `TIER_MAP`, and `derivePackage` only, so the
72
+ * classify_signals flow is acyclic end to end.
73
+ *
74
+ * Immutability (convention pack AP-004): classified effects are REBUILT as
75
+ * new values (`{ ...effect, classification }`), every field preserved —
76
+ * the detector's instances are never mutated, and both input maps are
77
+ * consumed read-only. The seam is also what makes the whole engine
78
+ * exhaustively testable with hand-built snapshots (research R13;
79
+ * tests/signals/adapter.test.ts, T016) — no tree, no tsconfig, no checker.
80
+ */
81
+ /**
82
+ * The tier boosts (data-model.md Section 4; SC-003) — P0 → +25, P1 → +10,
83
+ * P2/P3/P4 → +0. Keyed by the full `Tier` union so the compiler rejects a
84
+ * missing or misspelled entry (compile-time exhaustiveness, the same check
85
+ * `TIER_MAP` gets). The TIER a boost applies to is always read from
86
+ * `TIER_MAP`; this table holds only the arithmetic, and
87
+ * tests/signals/adapter.test.ts carries its own pinned copy as the
88
+ * independent second copy the arithmetic is diffed against.
89
+ */
90
+ const TIER_BOOST = {
91
+ P0: 25,
92
+ P1: 10,
93
+ P2: 0,
94
+ P3: 0,
95
+ P4: 0,
96
+ };
97
+ /**
98
+ * The mixed-polarity penalty (FR-011; data-model.md Section 4): the weight
99
+ * of the single synthesized `contradiction` row and the formula's one-time
100
+ * term — applied exactly once per contradicting pair, never per signal.
101
+ */
102
+ const CONTRADICTION_WEIGHT = -20;
103
+ /**
104
+ * The contradiction row's fixed-template reasoning (spec assumption 8;
105
+ * Constitution Principle I): deterministic per analyzer version, pinned
106
+ * verbatim by tests/signals/adapter.test.ts.
107
+ */
108
+ const CONTRADICTION_REASONING = "mixed-polarity evidence: positive and negative signals";
109
+ /**
110
+ * FR-014's total order over signals: the four-key `(package, function,
111
+ * side_effect_type, source)` codepoint comparison — plain string
112
+ * comparison per field, which for these ASCII fields IS codepoint
113
+ * comparison (never `localeCompare`, whose collation is locale-dependent
114
+ * and would break determinism). Pair keying keeps the key duplicate-free
115
+ * (at most one signal per source per pair), so the comparator needs no
116
+ * tie-break rule; the equal case exists only for hand-built duplicates the
117
+ * wire never sees.
118
+ *
119
+ * @param a The left signal.
120
+ * @param b The right signal.
121
+ * @returns Negative when `a` sorts first, positive when `b` does, zero on
122
+ * exact four-key equality.
123
+ */
124
+ function compareSignals(a, b) {
125
+ if (a.package !== b.package) {
126
+ return a.package < b.package ? -1 : 1;
127
+ }
128
+ if (a.function !== b.function) {
129
+ return a.function < b.function ? -1 : 1;
130
+ }
131
+ if (a.side_effect_type !== b.side_effect_type) {
132
+ return a.side_effect_type < b.side_effect_type ? -1 : 1;
133
+ }
134
+ if (a.source !== b.source) {
135
+ return a.source < b.source ? -1 : 1;
136
+ }
137
+ return 0;
138
+ }
139
+ /**
140
+ * FR-010's label bands (data-model.md Section 4): contractual ≥ 80,
141
+ * ambiguous [50, 80), incidental < 50 — inclusive at 80, exclusive at 50.
142
+ *
143
+ * @param confidence The clamped confidence percentage.
144
+ * @returns The label the formula assigns to that confidence.
145
+ */
146
+ function labelForConfidence(confidence) {
147
+ if (confidence >= 80) {
148
+ return "contractual";
149
+ }
150
+ return confidence >= 50 ? "ambiguous" : "incidental";
151
+ }
152
+ /**
153
+ * Classifies one (function record, canonical effect type) pair (FR-011;
154
+ * data-model.md Sections 4, 5.4) — the per-pair core `classifyPairs` fans
155
+ * out to, and the seam tests/signals/adapter.test.ts pins directly with
156
+ * hand-built signals (deliberately out-of-set weights included, for the
157
+ * clamp rows real extractor arithmetic cannot reach).
158
+ *
159
+ * The contradiction rule is a property of the PAIR, not a per-signal
160
+ * penalty: when the extractor signals mix at least one positive and at
161
+ * least one negative weight, exactly ONE synthesized row joins the bundle
162
+ * — source `contradiction`, weight −20, the first signal's identity
163
+ * fields, the pair's canonical type, the fixed-template reasoning — and
164
+ * the formula applies the −20 exactly once however many signals of either
165
+ * polarity fired. All-positive and all-negative evidence is agreement,
166
+ * never a contradiction; a weight of 0 is polarity-neutral.
167
+ *
168
+ * The formula (FR-009/FR-010): `clamp(0, 100, 50 + tierBoost +
169
+ * Σ(extractor weights) − (contradiction ? 20 : 0))` — the tier from
170
+ * `TIER_MAP` (the taxonomy is the single tier authority), the sum over the
171
+ * EXTRACTOR signals only (the synthesized row's −20 is the separate
172
+ * one-time term, which is what keeps the emitted feed sum-invariant). The
173
+ * clamp applies to the confidence only — emitted rows keep their real
174
+ * weights, so the evidence a consumer reads is never distorted by the
175
+ * bound.
176
+ *
177
+ * @param extractorSignals The pair's already-extracted signals — the five
178
+ * extractors' defined results, any order; never mutated.
179
+ * @param effectType The pair's canonical effect type — the `TIER_MAP` key
180
+ * and the synthesized row's `side_effect_type`; structural for the empty
181
+ * bundle, where no signal exists to read it from.
182
+ * @returns The pair's `SignalBundle`: its wire rows in four-key order
183
+ * (contradiction row included when it fires) and its `Classification`.
184
+ * @throws Error never in real flow — the identity guard below is
185
+ * structurally unreachable (mixed polarity implies a non-empty bundle) and
186
+ * exists to keep that claim loud rather than asserted.
187
+ */
188
+ export function classifyBundle(extractorSignals, effectType) {
189
+ // The polarity scan decides the synthesis (FR-011): mixed polarity — at
190
+ // least one positive AND at least one negative weight — is the one and
191
+ // only trigger. A 0 weight (never emitted by real extractors) is
192
+ // polarity-neutral: it cannot fire the synthesis.
193
+ let hasPositive = false;
194
+ let hasNegative = false;
195
+ for (const signal of extractorSignals) {
196
+ if (signal.weight > 0) {
197
+ hasPositive = true;
198
+ }
199
+ else if (signal.weight < 0) {
200
+ hasNegative = true;
201
+ }
202
+ }
203
+ // The bundle copies the input array (never mutates it); the signal
204
+ // objects themselves are shared immutable values, the house pattern.
205
+ const signals = [...extractorSignals];
206
+ // The one-time −20 term; 0 when no synthesis fired. Kept separate from
207
+ // the extractor sum so the emitted rows and the arithmetic stay in step
208
+ // — the sum-invariant a consumer checks by summing ALL rows.
209
+ let contradictionTerm = 0;
210
+ if (hasPositive && hasNegative) {
211
+ // Mixed polarity implies a non-empty bundle, so the first signal
212
+ // always exists; the guard keeps the structural claim loud rather
213
+ // than asserted (the noUncheckedIndexedAccess posture).
214
+ const identity = extractorSignals[0];
215
+ if (identity === undefined) {
216
+ throw new Error("mixed-polarity evidence implies a non-empty signal bundle — an empty bundle cannot fire the contradiction");
217
+ }
218
+ signals.push({
219
+ function: identity.function,
220
+ package: identity.package,
221
+ side_effect_type: effectType,
222
+ source: "contradiction",
223
+ weight: CONTRADICTION_WEIGHT,
224
+ reasoning: CONTRADICTION_REASONING,
225
+ });
226
+ contradictionTerm = CONTRADICTION_WEIGHT;
227
+ }
228
+ signals.sort(compareSignals);
229
+ const weightSum = extractorSignals.reduce((total, signal) => total + signal.weight, 0);
230
+ // FR-009: the clamped score, then FR-010: the label bands.
231
+ const raw = 50 + TIER_BOOST[TIER_MAP[effectType]] + weightSum + contradictionTerm;
232
+ const confidence = Math.max(0, Math.min(100, raw));
233
+ return {
234
+ signals,
235
+ classification: { label: labelForConfidence(confidence), confidence },
236
+ };
237
+ }
238
+ /**
239
+ * Runs the classification fan-out over one prepared analysis's records
240
+ * (FR-008; research R8) — the shared engine both consumers call after
241
+ * `detectEffects` and `buildRecordEvidence`, per the composition contract
242
+ * in this module's header.
243
+ *
244
+ * Pair keying: the extractors run once per (record, DISTINCT canonical
245
+ * effect type) pair — the fan-out counts types, never effect instances —
246
+ * so same-type instances share one bundle's signals and one classification,
247
+ * and distinct types on one record run independently (the routing gate
248
+ * decides per pair; neither pair's evidence leaks to the other). Extractor
249
+ * results are never deduplicated across sources: a naming and a
250
+ * documentation match on one pair yield two signals, never one merged row.
251
+ *
252
+ * Evidence totality is the hard dependency: a record in `records` without
253
+ * an evidence snapshot is an upstream bug and fails loud (the
254
+ * `callerSignal` posture — never a silent skip, which would be a
255
+ * Constitution Principle II silent false negative). A record ABSENT from
256
+ * the effects map is benign no-pairs and still keys the output map (output
257
+ * totality mirrors `detectEffects`' own over `records`).
258
+ *
259
+ * @param records The extraction records, any order; the output map keys
260
+ * every record.
261
+ * @param effects `detectEffects`' per-record effect map, consumed
262
+ * read-only.
263
+ * @param evidence `buildRecordEvidence`'s per-record snapshot map, keyed by
264
+ * the same record references.
265
+ * @returns The `ClassifiedEffects`: the four-key-ordered signal feed and
266
+ * every record's effects rebuilt as new immutable values with
267
+ * `classification` set (AP-004 — the detector's instances are never
268
+ * mutated, every field preserved, input order preserved).
269
+ * @throws Error when a record in `records` has no evidence snapshot, or
270
+ * when an effect's type carries no pair classification (structurally
271
+ * impossible — the pair loop keys every detected type).
272
+ */
273
+ export function classifyPairs(records, effects, evidence) {
274
+ const feed = [];
275
+ const classified = new Map();
276
+ for (const record of records) {
277
+ const snapshot = evidence.get(record);
278
+ if (snapshot === undefined) {
279
+ throw new Error(`record "${record.name}" (${record.relPath}) has no evidence snapshot — buildRecordEvidence keys every record, so this is an upstream bug`);
280
+ }
281
+ // The keyed-empty and absent spellings collapse here: a record the
282
+ // detector left clean arrives as [], a record missing from the map as
283
+ // undefined — both are no-pairs, never an error.
284
+ const recordEffects = effects.get(record) ?? [];
285
+ // Distinct canonical types in first-occurrence order (Set insertion
286
+ // order) — the pair unit FR-008 names. Instance count is invisible to
287
+ // the fan-out by construction.
288
+ const pairTypes = new Set(recordEffects.map((effect) => effect.type));
289
+ const pairClassifications = new Map();
290
+ for (const effectType of pairTypes) {
291
+ // FR-001's source order: interface, visibility, caller_count,
292
+ // naming_convention, docstring. The feed is sorted before return, so
293
+ // this order never reaches the output — it exists only to give the
294
+ // pre-sort array one fixed shape.
295
+ const extractorSignals = [
296
+ interfaceSignal(snapshot, effectType),
297
+ visibilitySignal(snapshot, effectType),
298
+ callerSignal(snapshot.callerModuleCount, record.name, derivePackage(record.relPath), effectType),
299
+ namingSignal(snapshot, effectType),
300
+ docstringSignal(snapshot, effectType),
301
+ ].filter((signal) => signal !== undefined);
302
+ const bundle = classifyBundle(extractorSignals, effectType);
303
+ feed.push(...bundle.signals);
304
+ pairClassifications.set(effectType, bundle.classification);
305
+ }
306
+ // AP-004: rebuild, never mutate — new values, every field preserved,
307
+ // input order preserved, the pair's classification attached to every
308
+ // same-type instance identically.
309
+ classified.set(record, recordEffects.map((effect) => {
310
+ const classification = pairClassifications.get(effect.type);
311
+ if (classification === undefined) {
312
+ throw new Error(`effect type "${effect.type}" on record "${record.name}" has no pair classification — the pair loop keys every detected type, so this is an upstream bug`);
313
+ }
314
+ return { ...effect, classification };
315
+ }));
316
+ }
317
+ // FR-014: the emitter owns the total order. Pair keying keeps the
318
+ // four-key duplicate-free (one signal per source per pair), so this is a
319
+ // strict total order with no tie-break rule.
320
+ feed.sort(compareSignals);
321
+ return { signals: feed, effects: classified };
322
+ }
323
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1,117 @@
1
+ import type { ExtractionRecord } from "../extract.js";
2
+ import type { ProgramContext } from "../program.js";
3
+ /**
4
+ * The checker-resolved caller index (FR-016; research R7; data-model.md
5
+ * Section 5.2) — the import-graph answer to US3's question, "how many
6
+ * distinct in-scope modules call this function?", derived through the
7
+ * compiler's own cross-module reference machinery rather than heuristic
8
+ * name matching (Constitution Principle III: `getSignatureUsage` is the
9
+ * verified `typescript/unstable/sync` surface, returning per usage the
10
+ * reference-name handle paired with its call-expression handle when the
11
+ * reference is invoked).
12
+ *
13
+ * Contract, per research R7 and data-model.md Section 5.2:
14
+ *
15
+ * 1. **One query per record.** Each extracted record costs exactly one
16
+ * `checker.getSignatureUsage` call — never one per call site — so the
17
+ * index's checker traffic stays proportional to project size, the same
18
+ * order as the detector's existing per-callee queries. The query node is
19
+ * the record's own declaration when it bears the declared name (function,
20
+ * method, accessor, and constructor declarations), and the NAME-GIVING
21
+ * PARENT declaration for the three assigned expression forms — a
22
+ * variable, class-property, or object-literal-property initializer —
23
+ * mirroring extract.ts's `recordNameForExpression` parent shapes: the
24
+ * symbol those records are called through is the binding, not the
25
+ * anonymous expression.
26
+ * 2. **Qualifying call sites.** A usage counts only when it carries a call
27
+ * expression. The call handle is resolved to its node and the node's
28
+ * source-file `fileName` (original case) is mapped to a root-relative
29
+ * path through the shared `relativeUnderBase` — deliberately NOT the
30
+ * handle's own `path` string, which the server canonicalizes (case-folded
31
+ * on case-insensitive platforms) and which therefore cannot be compared
32
+ * against analyzer-side spellings without duplicating the server's
33
+ * canonicalization rules.
34
+ * 3. **File-set parity (US3-7).** A call site is kept only when its
35
+ * root-relative path is in the caller's `inScopePaths` — the identical
36
+ * discovered, pattern-filtered, exclusion-filtered file set `analyze`
37
+ * reports over (T006's widening). Calls positioned in pattern-excluded
38
+ * modules that are still inside the compiler's program (the hermetic host
39
+ * serves in-root files on demand) and calls in test-classified files
40
+ * (excluded at discovery, never in the program) are both dropped here.
41
+ * 4. **Self-recursion exclusion (US3-6).** Calls positioned inside the
42
+ * record's own body span do not count — the rule is positional, so a
43
+ * recursive self-call is not an inbound caller, while a same-module call
44
+ * from a DIFFERENT function (including one nested inside the record's
45
+ * span but a record of its own) resolves through its own declaration and
46
+ * is judged by its own position.
47
+ * 5. **Distinct modules.** The count is the number of DISTINCT in-scope
48
+ * modules with at least one qualifying call site: the defining module
49
+ * counts when other functions in it call the record (US3-1), multiple
50
+ * sites within one module count that module once (US3-5), and
51
+ * module-level call sites count exactly like calls inside function
52
+ * bodies (US3's letter is call sites, not call sites in records).
53
+ * 6. **Documented resolve-no-caller boundaries** (data-model.md Section
54
+ * 5.2, pinned by tests/signals/caller-index.test.ts): anonymous
55
+ * default-export expressions (the `export default` form's parent is the
56
+ * ExportAssignment, which names nothing — the query runs against the
57
+ * expression itself and finds no symbol), accessors (property reads are
58
+ * name-only usages; no call expression is ever paired), and constructors
59
+ * (new expressions are not call expressions in the usage API's pairing).
60
+ *
61
+ * Mode boundary (research R7's documented degradation): in parse-only mode
62
+ * there is no checker, so the index is EMPTY — no entries at all, never an
63
+ * all-zero one — and no `caller_count` signal is emitted. Degradation
64
+ * reduces precision, never availability.
65
+ *
66
+ * Strictly static (Constitution Principle V): the index never executes,
67
+ * imports, or requires analyzed code. Every stage — reference resolution,
68
+ * handle resolution, span comparison — reads the compiler's parsed views
69
+ * only; `tests/signals/caller-index.test.ts`'s canary tree pins this by
70
+ * planting a throwing module inside the compiler's resolved import graph.
71
+ *
72
+ * Lifetime: the checker round-trips to the live native compiler server, so
73
+ * `buildCallerIndex` must run while the program-mode context is alive —
74
+ * `buildRecordEvidence` runs it for the method entries that own the
75
+ * context's disposal (src/analysis.ts, T025/T029) before they dispose,
76
+ * exactly as the detector's checker queries do.
77
+ */
78
+ /**
79
+ * The per-record caller index (data-model.md Section 5.2): every extracted
80
+ * record mapped to its distinct in-scope calling-module count. Internal —
81
+ * not protocol-visible; `RecordEvidence.callerModuleCount` (T019) is the
82
+ * value's consumer-facing spelling.
83
+ *
84
+ * Keying is by record REFERENCE: records are immutable value records
85
+ * (convention pack AP-004) flowing from one `prepareAnalysis` call, and the
86
+ * callers that pass them here hold the same array `prepareAnalysis`
87
+ * returned, so identity is stable and
88
+ * structural lookups (`index.get(record)`) cannot collide across same-named
89
+ * records. In program mode the map is TOTAL — one entry per record, 0 for
90
+ * uncalled records (US3-4); in parse-only mode it is empty.
91
+ */
92
+ export type CallerIndex = ReadonlyMap<ExtractionRecord, number>;
93
+ /**
94
+ * Builds the caller index over one prepared analysis (FR-016; research R7).
95
+ *
96
+ * In program mode, one `checker.getSignatureUsage` query per extracted
97
+ * record (see the module header for the query-node selection and the
98
+ * qualifying-call-site rules); in parse-only mode the result is the empty
99
+ * index — research R7's documented degradation boundary. An empty record
100
+ * list yields the empty index in either mode (there is nothing to count),
101
+ * even against a live program-mode context.
102
+ *
103
+ * @param context The bootstrapped analysis context — must still be live in
104
+ * program mode (checker calls round-trip to the native compiler server).
105
+ * @param records The extracted function-likes, as `prepareAnalysis`
106
+ * returned them — the same instances the caller will look up by.
107
+ * @param inScopePaths The pattern-filtered, test-excluded source list from
108
+ * `PreparedAnalysis.inScopePaths` (T006) — the identical file set `analyze`
109
+ * reports over, so US3-7's parity is structural.
110
+ * @param rootPath The realpath-resolved analysis root from
111
+ * `PreparedAnalysis.rootPath` — the base call-site file names are
112
+ * relativized against, threaded from the pipeline rather than re-derived
113
+ * from record file names.
114
+ * @returns The per-record distinct-module count map — one entry per record
115
+ * in program mode, empty in parse-only mode.
116
+ */
117
+ export declare function buildCallerIndex(context: ProgramContext, records: readonly ExtractionRecord[], inScopePaths: readonly string[], rootPath: string): CallerIndex;
@@ -0,0 +1,147 @@
1
+ import { sep } from "node:path";
2
+ import { isPropertyAssignment, isPropertyDeclaration, isVariableDeclaration, } from "typescript/unstable/ast";
3
+ import { relativeUnderBase } from "../internal.js";
4
+ /**
5
+ * Builds the caller index over one prepared analysis (FR-016; research R7).
6
+ *
7
+ * In program mode, one `checker.getSignatureUsage` query per extracted
8
+ * record (see the module header for the query-node selection and the
9
+ * qualifying-call-site rules); in parse-only mode the result is the empty
10
+ * index — research R7's documented degradation boundary. An empty record
11
+ * list yields the empty index in either mode (there is nothing to count),
12
+ * even against a live program-mode context.
13
+ *
14
+ * @param context The bootstrapped analysis context — must still be live in
15
+ * program mode (checker calls round-trip to the native compiler server).
16
+ * @param records The extracted function-likes, as `prepareAnalysis`
17
+ * returned them — the same instances the caller will look up by.
18
+ * @param inScopePaths The pattern-filtered, test-excluded source list from
19
+ * `PreparedAnalysis.inScopePaths` (T006) — the identical file set `analyze`
20
+ * reports over, so US3-7's parity is structural.
21
+ * @param rootPath The realpath-resolved analysis root from
22
+ * `PreparedAnalysis.rootPath` — the base call-site file names are
23
+ * relativized against, threaded from the pipeline rather than re-derived
24
+ * from record file names.
25
+ * @returns The per-record distinct-module count map — one entry per record
26
+ * in program mode, empty in parse-only mode.
27
+ */
28
+ export function buildCallerIndex(context, records, inScopePaths, rootPath) {
29
+ // Parse-only is the documented no-checker boundary: an empty index, so no
30
+ // `caller_count` signal can be emitted downstream.
31
+ if (context.mode !== "program") {
32
+ return new Map();
33
+ }
34
+ const inScopeSet = new Set(inScopePaths);
35
+ const index = new Map();
36
+ for (const record of records) {
37
+ index.set(record, distinctCallerModuleCount(context.checker, record, rootPath, inScopeSet));
38
+ }
39
+ return index;
40
+ }
41
+ /**
42
+ * Counts one record's distinct in-scope calling modules — the per-record
43
+ * body of the index build, kept separate from `buildCallerIndex` so the
44
+ * mode and totality bookkeeping stays flat.
45
+ *
46
+ * @param checker The live program-mode type checker.
47
+ * @param record The function-like to count callers of.
48
+ * @param rootPath The realpath-resolved analysis root from
49
+ * `PreparedAnalysis.rootPath`, threaded through `buildRecordEvidence` —
50
+ * the base call-site file names are relativized against.
51
+ * @param inScopeSet The in-scope root-relative paths, as a membership set.
52
+ * @returns The number of distinct in-scope modules with at least one
53
+ * qualifying call site (module-level sites included, self-recursion
54
+ * excluded, each module counted once).
55
+ */
56
+ function distinctCallerModuleCount(checker, record, rootPath, inScopeSet) {
57
+ const usages = checker.getSignatureUsage(queryDeclarationFor(record));
58
+ const modules = new Set();
59
+ for (const usage of usages) {
60
+ // Only invoked references count: a usage without a call expression is a
61
+ // read (an alias assignment, a property access on an accessor) — live
62
+ // usage of the binding, but not a call site.
63
+ if (usage.call === undefined) {
64
+ continue;
65
+ }
66
+ const callNode = usage.call.resolve();
67
+ if (callNode === undefined) {
68
+ // A handle the producing project cannot resolve does not identify a
69
+ // call site the index can position — dropped, never counted.
70
+ continue;
71
+ }
72
+ const callRelPath = relativeUnderBase(rootPath, toPosixSeparators(callNode.getSourceFile().fileName));
73
+ // US3-7's parity filter: only call sites in the identical in-scope file
74
+ // set `analyze` reports over. Out-of-root files (default libraries) and
75
+ // pattern-excluded in-root modules resolve to null or a non-member
76
+ // relPath here and are dropped.
77
+ if (callRelPath === null || !inScopeSet.has(callRelPath)) {
78
+ continue;
79
+ }
80
+ // US3-6: a call positioned inside the record's own body span is the
81
+ // record calling itself (self-recursion), not an inbound caller. The
82
+ // same-file gate keeps the span comparison inside one file's position
83
+ // space; a different function in the same module falls outside the
84
+ // record's span and counts (US3-1 — the defining module is a caller
85
+ // like any other).
86
+ if (callRelPath === record.relPath && isPositionInside(callNode, record.node)) {
87
+ continue;
88
+ }
89
+ modules.add(callRelPath);
90
+ }
91
+ return modules.size;
92
+ }
93
+ /**
94
+ * Selects the declaration node the checker queries for one record: the
95
+ * record's own node when it bears the declared name, and the name-giving
96
+ * parent declaration for the three assigned expression forms (research R7).
97
+ *
98
+ * The parent shapes mirror extract.ts's `recordNameForExpression` exactly —
99
+ * a variable declaration, object-literal property assignment, or class
100
+ * property declaration whose initializer IS the record's node — because the
101
+ * symbol callers invoke is the binding those parents declare, not the
102
+ * anonymous arrow or function expression itself (querying the expression
103
+ * directly finds no usages: it has no name for the reference machinery to
104
+ * resolve). Every other form, including the `export default` expression
105
+ * (whose parent is the ExportAssignment — the documented resolve-no-caller
106
+ * boundary), is queried as the record node itself.
107
+ *
108
+ * @param record The function-like to select the query declaration for.
109
+ * @returns The node to hand to `checker.getSignatureUsage`.
110
+ */
111
+ function queryDeclarationFor(record) {
112
+ const node = record.node;
113
+ const parent = node.parent;
114
+ if ((isVariableDeclaration(parent) && parent.initializer === node) ||
115
+ (isPropertyAssignment(parent) && parent.initializer === node) ||
116
+ (isPropertyDeclaration(parent) && parent.initializer === node)) {
117
+ return parent;
118
+ }
119
+ return node;
120
+ }
121
+ /**
122
+ * Positional containment (US3-6): whether `inner`'s span lies inside
123
+ * `outer`'s — both nodes from the same source file (callers gate on the
124
+ * file first, since positions are file-local). `getStart`/`getEnd` use the
125
+ * same leading-trivia convention on both nodes, so the comparison is
126
+ * self-consistent for full-span containment of the call expression.
127
+ *
128
+ * @param inner The candidate containing node (the call expression).
129
+ * @param outer The enclosing node (the record's declaration).
130
+ * @returns Whether `inner` is positioned inside `outer`'s span.
131
+ */
132
+ function isPositionInside(inner, outer) {
133
+ return inner.getStart() >= outer.getStart() && inner.getEnd() <= outer.getEnd();
134
+ }
135
+ /**
136
+ * Normalizes a path's separators to `/` (a no-op on POSIX, where the
137
+ * analysis pipeline and CI run): keeps the `relativeUnderBase` input in
138
+ * one spelling discipline regardless of the platform the server spells
139
+ * file names for.
140
+ *
141
+ * @param path The path to normalize.
142
+ * @returns The same path with platform separators as `/`.
143
+ */
144
+ function toPosixSeparators(path) {
145
+ return path.split(sep).join("/");
146
+ }
147
+ //# sourceMappingURL=caller-index.js.map
@@ -0,0 +1,76 @@
1
+ import type { SideEffectType } from "../taxonomy.js";
2
+ import type { Signal } from "./types.js";
3
+ /**
4
+ * The distinct-module bucket extractor (FR-004; research R7; data-model.md
5
+ * Section 7) — the pure half of US3's caller signal, and one of the five
6
+ * extractors the adapter fans out per (function record, canonical effect
7
+ * type) pair (FR-008).
8
+ *
9
+ * `buildCallerIndex` (src/signals/caller-index.ts) answers "how many
10
+ * distinct in-scope modules call this function?" through the checker's own
11
+ * cross-module reference machinery; this rule maps that count to FR-004's
12
+ * pinned buckets:
13
+ *
14
+ * | distinct calling modules | `caller_count` weight |
15
+ * |--------------------------|-----------------------|
16
+ * | 0 | — (no signal emitted) |
17
+ * | exactly 1 | +5 |
18
+ * | 2–3 | +10 |
19
+ * | 4 or more | +15 |
20
+ *
21
+ * The table is pinned arithmetic, not tuning — the same posture as the
22
+ * confidence formula (FR-009): a bucket boundary or weight that drifts from
23
+ * data-model.md Section 7 is a bug.
24
+ *
25
+ * Evidence seam (research R12): the rule is a pure function of the count and
26
+ * the pair's identity fields — no compiler interaction, no I/O, no
27
+ * `ProgramContext` (the imports above are type-only, which is the structural
28
+ * proof). The checker machinery that produces the count lives entirely in
29
+ * caller-index.ts; the adapter passes `RecordEvidence.callerModuleCount`
30
+ * once the evidence snapshot lands (T019). The seam is what makes the rule
31
+ * exhaustively table-testable with hand-built counts
32
+ * (tests/signals/caller.test.ts, T008) — no compiler fixtures for the
33
+ * weights, exactly like the sibling pure rules (interface, visibility,
34
+ * naming, jsdoc).
35
+ *
36
+ * Zero-caller neutrality (FR-004; US3-4; spec assumption 3): a count of 0
37
+ * emits NO signal. Weight 0 carries no evidence — a 0-weight row would add
38
+ * wire noise without shifting the confidence arithmetic — and the reference
39
+ * analyzer's extractor likewise returns nothing for zero-caller counts. The
40
+ * same value carries parse-only degradation (research R7): without a
41
+ * checker the index is empty, so no `caller_count` signal exists at all —
42
+ * degradation reduces precision, never availability.
43
+ *
44
+ * Determinism (Constitution Principle I; research R1/R15): the emitted
45
+ * `reasoning` is a fixed template naming the count — a pure function of the
46
+ * matched rule and its token, stable per analyzer version and pinned by the
47
+ * test suite exactly like effect `description` strings.
48
+ */
49
+ /**
50
+ * Maps one (function record, canonical effect type) pair's distinct in-scope
51
+ * calling-module count to FR-004's `caller_count` bucket.
52
+ *
53
+ * The identity fields pass through verbatim — `functionName` is the record's
54
+ * unqualified name, `packageName` its `derivePackage` value — and the rule is
55
+ * effect-type-blind: unlike naming and documentation evidence (FR-005/
56
+ * FR-006), real usage agrees with every effect type equally, so no routing
57
+ * gate applies and `effectType` rides along as identity only.
58
+ *
59
+ * @param callerModuleCount The number of distinct in-scope modules whose
60
+ * call sites resolve to the record — `buildCallerIndex`'s per-record value
61
+ * (0 in parse-only mode), which the adapter passes as
62
+ * `RecordEvidence.callerModuleCount` once the evidence snapshot lands.
63
+ * @param functionName The record's unqualified name — the signal's
64
+ * `function` identity field.
65
+ * @param packageName The record's dotted module path — the signal's
66
+ * `package` identity field.
67
+ * @param effectType The pair's canonical effect type — the signal's
68
+ * `side_effect_type` identity field.
69
+ * @returns The `caller_count` signal for the count's bucket — weight +5 for
70
+ * exactly 1 distinct module, +10 for 2–3, +15 for 4 or more — or
71
+ * `undefined` for 0 callers: neutral evidence, never a 0-weight row.
72
+ * @throws Error when `callerModuleCount` is not a non-negative integer — a
73
+ * value the caller index cannot produce; an upstream bug fails loud rather
74
+ * than silently dropping the signal.
75
+ */
76
+ export declare function callerSignal(callerModuleCount: number, functionName: string, packageName: string, effectType: SideEffectType): Signal | undefined;