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,341 @@
1
+ import type { Writable } from "node:stream";
2
+ import { type ExtractionRecord } from "./extract.js";
3
+ import { type ProgramContext } from "./program.js";
4
+ import { type ClassifySignalsResult } from "./signals/types.js";
5
+ /**
6
+ * Pattern rules and the shared analysis pipeline (FR-001, FR-002; research
7
+ * R11, R12; data-model.md PatternSet and the ProgramContext →
8
+ * ExtractionRecord pipeline order).
9
+ *
10
+ * The pattern rules (T012) are pure — no filesystem, no walk — and shared
11
+ * by every pattern-filtered method: the analyze and complexity scope filter
12
+ * below, and coverage entry filtering (FR-024), so "the same path-prefix
13
+ * rules" is structural. `prepareAnalysis` (T014) composes the exported
14
+ * discovery, bootstrap, and extraction stages into the one pipeline both
15
+ * analysis handlers consume, so FR-022's same-extraction-set, scope, and
16
+ * ordering guarantee is structural — there is no second extraction path
17
+ * to drift. `analyze` (T018) closes that pipeline over the detector:
18
+ * detection, FR-020's response assembly, and serialization, with the
19
+ * program-mode context's lifetime owned by the handler (disposed in a
20
+ * `finally`) — and released by `prepareAnalysis` itself when extraction
21
+ * throws — so no native compiler server outlives one analysis. Spec 003
22
+ * (T025) inserts the classification core between detection and assembly
23
+ * (FR-012): the evidence snapshots are taken while that context is live,
24
+ * then the pair-keyed fan-out rebuilds every effect as a classified
25
+ * immutable value, so each one reaches the wire already carrying
26
+ * `classification: {label, confidence}`.
27
+ *
28
+ * `classifySignals` (T029, FR-014) is the second method entry here — the
29
+ * `classify_signals` handler's payload source, running the identical
30
+ * stages `analyze` runs over the same `prepareAnalysis` pipeline and
31
+ * owning the same dispose lifetime, differing only in the last stage
32
+ * (feed serialization instead of record assembly). Both entries consume
33
+ * the pure fan-out core from src/signals/adapter.ts strictly
34
+ * one-directionally (convention pack AP-005: circular dependencies MUST
35
+ * NOT exist between modules): this module imports the core, and nothing
36
+ * under src/signals/ imports this module back, so the classify_signals
37
+ * flow is acyclic end to end.
38
+ *
39
+ * Spec 004 (T005) adds the one widening every mapping stage consumes
40
+ * (FR-006): an optional `options` parameter whose `includeTestArm` flag
41
+ * admits the discovered test arm to the bootstrap — program mode's
42
+ * extender-config `files` root set and the parse-only sources map both
43
+ * derive from the same pre-read list — while the extraction records stay
44
+ * narrowed to the in-scope source set, so the target set remains the
45
+ * identical `analyze` file set. The flag is opt-in: the three method
46
+ * entries below pass nothing and observe only the inert
47
+ * `testPaths: []` result field.
48
+ */
49
+ /**
50
+ * Normalized pattern state (data-model.md PatternSet; internal — not
51
+ * protocol-visible).
52
+ *
53
+ * `null` is the whole-tree marker: `patterns` absent, `null`, empty, or
54
+ * exactly one of the catch-all forms `["./..."]` / `["..."]`. Any other
55
+ * value is the array of normalized directory prefixes.
56
+ */
57
+ export type PatternSet = null | readonly string[];
58
+ /**
59
+ * Normalizes the raw `patterns` parameter into a `PatternSet` (FR-001).
60
+ *
61
+ * The catch-alls — `patterns` absent, `null`, the empty array, or the
62
+ * exact singleton forms `["./..."]` and `["..."]` — normalize to `null`,
63
+ * the whole tree. Every other element becomes a directory prefix through
64
+ * `normalizePattern`, deduplicated preserving first occurrence.
65
+ *
66
+ * Match-nothing elements are kept, never dropped: `[""]`, `["."]`, and
67
+ * `["./"]` normalize to prefixes that match no path, so a pattern set
68
+ * matching nothing yields empty analysis results downstream, never an
69
+ * error. Only the exact singleton forms are catch-alls — a lone `"..."`
70
+ * element inside a larger array survives as a match-nothing prefix.
71
+ *
72
+ * The input domain is the server-validated one (T019 rejects non-array
73
+ * or non-string-element `patterns` with `-32602` before analysis runs):
74
+ * `undefined`, `null`, or an array of strings. Validation itself is the
75
+ * dispatch layer's concern, not this function's.
76
+ *
77
+ * @param patterns The raw `patterns` parameter value.
78
+ */
79
+ export declare function normalizePatterns(patterns: unknown): PatternSet;
80
+ /**
81
+ * Reports whether a root-relative POSIX-separator path is in scope under a
82
+ * normalized pattern set (FR-001).
83
+ *
84
+ * `null` means the whole tree. Otherwise a pattern matches when the path
85
+ * equals a prefix — the prefix may itself be a file path — or begins with
86
+ * `prefix + "/"`, a segment boundary: the prefix `src` does not match
87
+ * `srcx/lib.ts`, and the file pattern `src/lib.ts` does not scope its
88
+ * siblings. Patterns union — any matching prefix puts the path in scope.
89
+ *
90
+ * @param relPath Root-relative POSIX-separator path to test.
91
+ * @param patternSet A normalized pattern set from `normalizePatterns`.
92
+ */
93
+ export declare function pathInScope(relPath: string, patternSet: PatternSet): boolean;
94
+ /**
95
+ * The `prepareAnalysis` result (data-model.md's internal pipeline order:
96
+ * `ProgramContext` → `ExtractionRecord`) — the surfaces the analyze and
97
+ * complexity computations run over (FR-022: the identical extraction
98
+ * set, scope, and ordering both methods report), plus the in-scope file
99
+ * set spec 003's signal pipeline filters by.
100
+ */
101
+ export interface PreparedAnalysis {
102
+ /**
103
+ * The bootstrapped analysis context (FR-003/FR-004). A program-mode
104
+ * context owns a live native compiler server; the consumer that drops
105
+ * it disposes it — the analysis handlers own that lifetime, exactly as
106
+ * direct pipeline callers must. A parse-only context owns nothing to
107
+ * dispose.
108
+ */
109
+ readonly context: ProgramContext;
110
+ /**
111
+ * The extracted function-likes, sorted by `(relPath, line, name)`
112
+ * (FR-008) — the record set the detector (FR-009 attribution) and the
113
+ * complexity engine (FR-021) both consume.
114
+ */
115
+ readonly records: readonly ExtractionRecord[];
116
+ /**
117
+ * The in-scope file set (spec 003 FR-016's file-set parity; research
118
+ * R7): the pattern-filtered, test-excluded source list in
119
+ * classifyFiles' sorted order — the exact set `records` were extracted
120
+ * from. The caller index (spec 003 T009) filters call sites by this
121
+ * set, so the index is built over the identical discovered,
122
+ * pattern-filtered, exclusion-filtered file set as the analysis by
123
+ * construction — no second scope computation to drift. A purely
124
+ * additive widening: the analyze and complexity handlers ignore it,
125
+ * and their behavior is unchanged.
126
+ */
127
+ readonly inScopePaths: readonly string[];
128
+ /**
129
+ * The realpath-resolved absolute analysis root — `resolveRoot`'s output
130
+ * (FR-010's resolved form, never the raw request spelling). The base the
131
+ * caller index relativizes call-site file names against, threaded here so
132
+ * `buildCallerIndex` never re-derives it from record file names. A purely
133
+ * additive widening: consumers that do not need it ignore it, and their
134
+ * behavior is unchanged.
135
+ */
136
+ readonly rootPath: string;
137
+ /**
138
+ * The discovered, exclusion-screened test arm in classifyFiles' sorted
139
+ * order (spec 004 FR-006): `[]` unless the caller passed
140
+ * `{ includeTestArm: true }`. Pattern-UNfiltered by contract —
141
+ * `patterns` narrow the target arm only, so a pattern set naming test
142
+ * files still yields the full test arm here. Generated and skipped
143
+ * files are excluded by the screening both arms share. A purely
144
+ * additive widening: consumers that pass no flag observe only this
145
+ * inert empty field, and their behavior is unchanged.
146
+ */
147
+ readonly testPaths: readonly string[];
148
+ }
149
+ /**
150
+ * The `prepareAnalysis` widening options (spec 004 FR-006; research R2):
151
+ * the opt-in switch that admits the test arm to the bootstrap. The
152
+ * mapping pipeline (`test_mapping`, spec 004) is the consumer that sets
153
+ * it; every other caller passes nothing and observes no behavior change
154
+ * beyond the inert `testPaths: []` result field.
155
+ */
156
+ export interface PrepareAnalysisOptions {
157
+ /**
158
+ * When `true`, the discovered, exclusion-screened test arm is pre-read
159
+ * through the same bounded `readBounded` and appended to the bootstrap
160
+ * input (sorted source arm, then sorted test arm), so the program
161
+ * mode's extender-config `files` root set and the parse-only sources
162
+ * map both admit the test files — checker queries can resolve
163
+ * test-file imports and calls. The extraction records are STILL
164
+ * narrowed to the in-scope source set: the target set remains the
165
+ * identical `analyze` file set, record-for-record.
166
+ */
167
+ readonly includeTestArm: boolean;
168
+ }
169
+ /**
170
+ * Prepares the shared analysis over a project tree (FR-002; research R12):
171
+ * resolve, walk, screen, classify, exclude, filter, bootstrap, extract —
172
+ * the one pipeline the analyze and complexity handlers both consume, so
173
+ * FR-022's same-extraction-set/scope/ordering guarantee is structural.
174
+ *
175
+ * Composition, in order:
176
+ *
177
+ * 1. `resolveRoot` validates and realpath-resolves the root (FR-010) —
178
+ * the same validation `discover` runs; an invalid root throws
179
+ * `InvalidRootPathError` here, for the server to map to `-32602`
180
+ * (no layering inversion).
181
+ * 2. `walkTree` → `screenCandidates` → `classifyFiles`: the same
182
+ * walk/screen/classify chain `discover()` composes, minus framework
183
+ * detection — deterministic walk order, the safety-skip → `.d.ts` →
184
+ * generated-marker exclusion chain, then the test/source partition.
185
+ * 3. Test files are additionally excluded from analysis (FR-002): only
186
+ * the classification's source arm proceeds. Generated files never
187
+ * reach this point (`screenCandidates` already dropped them), so test
188
+ * files and generated files are never analyzed. The exclusion precedes
189
+ * the pattern filter and is absolute: a pattern naming a test file
190
+ * still yields no records (FR-001 narrows within the analyzable set).
191
+ * 4. The FR-001 pattern filter — `normalizePatterns` then `pathInScope`
192
+ * over classifyFiles' sorted list — keeps the in-scope subset; a set
193
+ * matching nothing yields an empty analysis, never an error.
194
+ * 5. Each in-scope file is pre-read through the async `readBounded` at
195
+ * the full 16 MiB budget (a JSON-free whole-file read),
196
+ * `buildProgramContext` bootstraps the program or parse-only context
197
+ * over exactly those files (FR-003/FR-004; a `null` read excludes its
198
+ * file after `readBounded`'s own one-diagnostic skip), and
199
+ * `extractFunctions` walks the context's sources into the sorted
200
+ * record list (FR-007/FR-008), and the records are narrowed to the
201
+ * in-scope set — the program arm's transitive imports are excluded
202
+ * (FR-001/FR-022; the parse-only arm is structurally in scope).
203
+ *
204
+ * Diagnostics flow to the injected stderr; stdout is never touched (it is
205
+ * reserved for JSON-RPC responses). The returned context's lifetime is
206
+ * the consumer's — the analysis handlers dispose a program-mode context
207
+ * when finished with it — and a mid-pipeline failure releases it here:
208
+ * when extraction throws, the program-mode context is disposed before
209
+ * the error propagates, so no native compiler server outlives the
210
+ * pipeline call either way.
211
+ *
212
+ * @param rootPath Absolute or relative project root; a relative path
213
+ * resolves against the analyzer process working directory, and a symlinked
214
+ * root is realpath-resolved exactly once at the boundary (FR-018).
215
+ * @param patterns The raw `patterns` parameter value. The server validates
216
+ * its shape (`-32602`, T019) before analysis runs; this surface only
217
+ * normalizes.
218
+ * @param stderr Injected diagnostic sink (Testability principle); defaults
219
+ * to `process.stderr`.
220
+ * @param options The widening options (spec 004 FR-006); omitted by the
221
+ * analyze/complexity/classify_signals callers, which observe no behavior
222
+ * change beyond the inert `testPaths: []` result field.
223
+ * @returns The bootstrapped `ProgramContext`, the extraction records, the
224
+ * in-scope file set (spec 003 FR-016's file-set parity), the
225
+ * realpath-resolved analysis root, and the test arm (`[]` unless
226
+ * `{ includeTestArm: true }` was passed).
227
+ * @throws InvalidRootPathError when the root does not exist, is not a
228
+ * directory, or cannot be accessed; the server handler maps it to the
229
+ * contract's `-32602` response.
230
+ */
231
+ export declare function prepareAnalysis(rootPath: string, patterns: unknown, stderr?: Writable, options?: PrepareAnalysisOptions): Promise<PreparedAnalysis>;
232
+ /**
233
+ * The `analyze` method's handler (FR-020; the analyze contract): the
234
+ * serialized `FunctionRecord[]` payload — detection effects attributed per
235
+ * record, assembled in the `(file, line, name)` total order, and mapped
236
+ * through `serializeFunctionRecord` so every entry on the returned array
237
+ * is already wire-shaped (fixed key order, validated fields — the
238
+ * protocol layer's sorted-key serializer then only re-orders keys).
239
+ *
240
+ * Spec 003 inserts the classification core between detection and
241
+ * assembly (FR-012; research R10; the adapter's composition contract):
242
+ * the evidence snapshots are taken while the program-mode context is
243
+ * still live — every checker query and the caller index's
244
+ * `getSignatureUsage` traffic round-trips to the native compiler server —
245
+ * then `classifyPairs` runs the pair-keyed fan-out and rebuilds each
246
+ * record's effects as new immutable values carrying
247
+ * `classification: {label, confidence}`. Every same-type effect on a
248
+ * record shares the identical pair classification (FR-008/FR-011), every
249
+ * effect in every response carries one (FR-012, superseding spec 002
250
+ * FR-019's omission rule here at the wiring layer — the detector itself
251
+ * is untouched and still produces unclassified effects), and the
252
+ * classified instances are what assembly consumes, so
253
+ * `serializeEffect` → `serializeClassification`'s fail-loud validation
254
+ * (closed label set, integer 0–100) now exercises on every `analyze`
255
+ * response.
256
+ *
257
+ * The returned array — not a `{functions: [...]}` wrapper — is the
258
+ * documented result shape the server wraps into its JSON-RPC success
259
+ * response (T019); both this entry and the payload are deterministic
260
+ * pure functions of the analyzed tree (Constitution Principle I:
261
+ * byte-identical repeat responses, classification fields included).
262
+ *
263
+ * The program-mode context's lifetime is this handler's — unchanged by
264
+ * the classification insertion: the native compiler server behind it is
265
+ * closed in the `finally` whatever the detection and classification
266
+ * outcome, so no subprocess outlives one analysis. A parse-only context
267
+ * owns nothing to dispose.
268
+ *
269
+ * @param rootPath Absolute or relative project root; validated and
270
+ * realpath-resolved by `prepareAnalysis` (an invalid root throws
271
+ * `InvalidRootPathError`, the server maps to `-32602`).
272
+ * @param patterns The raw `patterns` parameter value; shape-validated by
273
+ * the server (`-32602`, T019) before analysis runs, normalized here.
274
+ * @param stderr Injected diagnostic sink (Testability principle); defaults
275
+ * to `process.stderr`. Stdout is never touched.
276
+ * @returns The serialized function records, `(file, line, name)`-sorted.
277
+ */
278
+ export declare function analyze(rootPath: string, patterns: unknown, stderr?: Writable): Promise<readonly Record<string, unknown>[]>;
279
+ /**
280
+ * The `classify_signals` method's entry (FR-014; research R10, R11): the
281
+ * serialized `Signal[]` payload — the raw evidence behind `analyze`'s
282
+ * classifications, one row per rule that matched per (function record,
283
+ * canonical effect type) pair — in FR-014's `(package, function,
284
+ * side_effect_type, source)` total order, each row already wire-shaped
285
+ * through `serializeSignal` (validated fields, omit-unset-optionals
286
+ * `reasoning`). The returned array — not a `{"signals": [...]}` wrapper —
287
+ * is the payload the server handler wraps into its JSON-RPC success
288
+ * response, exactly as it wraps `analyze`'s array. The return type is
289
+ * `ClassifySignalsResult["signals"]` — the payload half of the wire result
290
+ * interface — so the entry-to-handler hand-off is compile-time pinned: the
291
+ * handler types its wrapper against the interface, and this return cannot
292
+ * drift from the wire contract.
293
+ *
294
+ * The stages are `analyze`'s, identically and in the identical order
295
+ * (FR-013's one-shared-pipeline guarantee is structural, never a second
296
+ * walk): `prepareAnalysis` — the one discovery/bootstrap/extraction
297
+ * pipeline, so the identical discovered, pattern-filtered,
298
+ * exclusion-filtered file set and record set — then `detectEffects`, then
299
+ * the T024 core with the program-mode context still live: the evidence
300
+ * snapshots (`buildRecordEvidence`, caller index included) taken while the
301
+ * checker can still answer, then `classifyPairs` — the pair-keyed fan-out
302
+ * whose four-key-ordered `signals` feed is this entry's payload. The two
303
+ * entries differ by the last stage only: assembly and
304
+ * `serializeFunctionRecord` in `analyze`, feed serialization here.
305
+ *
306
+ * The entry lives here beside `analyze` — not in src/signals/adapter.ts —
307
+ * so the module dependency stays strictly one-directional (convention
308
+ * pack AP-005): this module imports the pure core; nothing under
309
+ * src/signals/ imports this module back.
310
+ *
311
+ * The program-mode context's dispose lifetime is owned here exactly as
312
+ * `analyze` owns its own (the same `finally` discipline): the native
313
+ * compiler server behind the context is closed whatever the detection and
314
+ * classification outcome, so no subprocess outlives one request. A
315
+ * parse-only context owns nothing to dispose. `prepareAnalysis` itself
316
+ * releases the context when extraction throws, and an invalid root throws
317
+ * `InvalidRootPathError` before any context exists — it propagates
318
+ * untouched for the server to map to the shared `-32602` root message.
319
+ *
320
+ * Deterministic (Constitution Principle I): the feed is a pure function of
321
+ * the analyzed tree and analyzer version — fixed row order, fixed
322
+ * reasoning templates, no timestamps or environment-dependent data — so
323
+ * repeated requests over the same tree serialize byte-identically.
324
+ *
325
+ * @param rootPath Absolute or relative project root; validated and
326
+ * realpath-resolved by `prepareAnalysis` (an invalid root throws
327
+ * `InvalidRootPathError`, the server maps to `-32602`).
328
+ * @param patterns The raw `patterns` parameter value; shape-validated by
329
+ * the server (`-32602`) before analysis runs, normalized by
330
+ * `prepareAnalysis`. A set matching nothing yields `[]`, never an error.
331
+ * @param stderr Injected diagnostic sink (Testability principle); defaults
332
+ * to `process.stderr`. Stdout is never touched.
333
+ * @returns The serialized signals — `ClassifySignalsResult["signals"]`, the
334
+ * `readonly Signal[]` the server handler wraps under the result interface's
335
+ * single `signals` key — `(package, function, side_effect_type, source)`
336
+ * -sorted.
337
+ * @throws InvalidRootPathError when the root does not exist, is not a
338
+ * directory, or cannot be accessed; the server handler maps it to the
339
+ * contract's `-32602` response.
340
+ */
341
+ export declare function classifySignals(rootPath: string, patterns: unknown, stderr?: Writable): Promise<ClassifySignalsResult["signals"]>;