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
package/dist/server.js ADDED
@@ -0,0 +1,451 @@
1
+ import readline from "node:readline";
2
+ import { analyze, classifySignals } from "./analysis.js";
3
+ import { cognitiveComplexity } from "./cognitive.js";
4
+ import { computeComplexity } from "./complexity.js";
5
+ import { parseCoverage } from "./coverage.js";
6
+ import { discover, InvalidRootPathError } from "./discovery.js";
7
+ import { docCoverage } from "./doc-coverage.js";
8
+ import { errorResponse, INTERNAL_ERROR, INVALID_PARAMS, INVALID_REQUEST, initializeResult, METHOD_NOT_FOUND, normalizeId, PARSE_ERROR, serialize, shutdownResult, successResponse, } from "./protocol.js";
9
+ import { testMapping } from "./quality/pipeline.js";
10
+ export class RpcError extends Error {
11
+ code;
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.code = code;
15
+ }
16
+ }
17
+ const MAX_LINE_CHARS = 16 * 1024 * 1024;
18
+ const MAX_METHOD_ECHO = 64;
19
+ function truncateMethodEcho(method) {
20
+ if (method.length <= MAX_METHOD_ECHO) {
21
+ return method;
22
+ }
23
+ return `${method.slice(0, MAX_METHOD_ECHO - 3)}...`;
24
+ }
25
+ function errorMessage(error) {
26
+ return error instanceof Error ? error.message : String(error);
27
+ }
28
+ /**
29
+ * Validates that JSON-RPC `params` is a JSON object — not absent,
30
+ * `null`, or an array — and returns it as a record. Shared by every
31
+ * params-carrying method (initialize, discover, and the analysis
32
+ * methods) so the pinned message lives in exactly one place (FR-027).
33
+ *
34
+ * @param params The raw `params` value from the request envelope.
35
+ * @returns The params object as a string-keyed record.
36
+ * @throws RpcError `-32602` when params is absent, `null`, or an array.
37
+ */
38
+ function requireParamsObject(params) {
39
+ if (params === null || Array.isArray(params) || typeof params !== "object") {
40
+ throw new RpcError(INVALID_PARAMS, "Invalid params: params must be an object");
41
+ }
42
+ return params;
43
+ }
44
+ /**
45
+ * Validates that `root_path` is present and a string. Shared by every
46
+ * root-accepting method, always after `requireParamsObject` (FR-027).
47
+ *
48
+ * @param record The already-validated params record.
49
+ * @returns The root path exactly as the request carried it.
50
+ * @throws RpcError `-32602` when `root_path` is missing or not a string.
51
+ */
52
+ function requireRootPath(record) {
53
+ const rootPath = record.root_path;
54
+ if (typeof rootPath !== "string") {
55
+ throw new RpcError(INVALID_PARAMS, "Invalid params: root_path must be a string");
56
+ }
57
+ return rootPath;
58
+ }
59
+ /**
60
+ * Validates the shared analysis-params surface (FR-027; research R12):
61
+ * params must be an object carrying a string `root_path`, an optional
62
+ * `patterns` that is `null` or an array of strings, and no other key —
63
+ * checked in that order, with the message strings pinned by the
64
+ * analyze/complexity/coverage contracts' error tables. The `patterns`
65
+ * value passes through raw: normalization (`normalizePatterns`) is the
66
+ * pipeline's concern, validation the dispatch layer's.
67
+ *
68
+ * @param params The raw `params` value from the request envelope.
69
+ * @returns The root path and the raw patterns value.
70
+ * @throws RpcError `-32602` for every params row of the contracts'
71
+ * error tables.
72
+ */
73
+ function validateAnalysisParams(params) {
74
+ const record = requireParamsObject(params);
75
+ const rootPath = requireRootPath(record);
76
+ const patterns = record.patterns;
77
+ // `null` is a legal whole-tree marker (Pattern rules), so only a
78
+ // non-null non-array or an array with a non-string element violates.
79
+ if (patterns !== undefined &&
80
+ patterns !== null &&
81
+ (!Array.isArray(patterns) ||
82
+ patterns.some((element) => typeof element !== "string"))) {
83
+ throw new RpcError(INVALID_PARAMS, "Invalid params: patterns must be an array of strings");
84
+ }
85
+ for (const key of Object.keys(record)) {
86
+ if (key !== "root_path" && key !== "patterns") {
87
+ throw new RpcError(INVALID_PARAMS, "Invalid params: params must contain only root_path and patterns");
88
+ }
89
+ }
90
+ return { rootPath, patterns };
91
+ }
92
+ /**
93
+ * Maps `InvalidRootPathError` — thrown by `resolveRoot` when the root
94
+ * does not exist, is not a directory, or cannot be accessed — to the
95
+ * one `-32602` root message every root-accepting method shares (FR-010;
96
+ * the analyze contract's error table pins the same row). The echoed
97
+ * path is the error's cwd-resolved rootPath — not the realpath form —
98
+ * so the response stays a deterministic function of the request. Every
99
+ * other error maps to `null`: the caller rethrows it so handleLine's
100
+ * catch treats it as an analyzer bug (`-32603` with a stderr stack
101
+ * trace), never a client error.
102
+ *
103
+ * @param error An error thrown from a root-accepting handler body.
104
+ * @returns The shared `-32602` error, or `null` for anything else.
105
+ */
106
+ function mapRootPathError(error) {
107
+ if (!(error instanceof InvalidRootPathError)) {
108
+ return null;
109
+ }
110
+ return new RpcError(INVALID_PARAMS, `Invalid params: root_path is not a directory: ${error.rootPath}`);
111
+ }
112
+ export class Server {
113
+ stdin;
114
+ stdout;
115
+ stderr;
116
+ dispatch;
117
+ brokenPipe = false;
118
+ shuttingDown = false;
119
+ constructor(stdin, stdout, stderr, dispatch) {
120
+ this.stdin = stdin;
121
+ this.stdout = stdout;
122
+ this.stderr = stderr;
123
+ this.dispatch = dispatch ?? this.createDefaultDispatch();
124
+ }
125
+ async run() {
126
+ const rl = readline.createInterface({ input: this.stdin });
127
+ try {
128
+ for await (const line of rl) {
129
+ const text = line.endsWith("\r") ? line.slice(0, -1) : line;
130
+ await this.handleLine(text);
131
+ if (this.brokenPipe || this.shuttingDown) {
132
+ break;
133
+ }
134
+ }
135
+ }
136
+ finally {
137
+ rl.close();
138
+ }
139
+ }
140
+ async handleLine(text) {
141
+ if (text.trim().length === 0) {
142
+ return;
143
+ }
144
+ if (text.length > MAX_LINE_CHARS) {
145
+ this.writeResponse(errorResponse(null, INVALID_REQUEST, "Invalid Request"));
146
+ return;
147
+ }
148
+ let parsed;
149
+ try {
150
+ parsed = JSON.parse(text);
151
+ }
152
+ catch {
153
+ this.writeResponse(errorResponse(null, PARSE_ERROR, "Parse error"));
154
+ return;
155
+ }
156
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
157
+ this.writeResponse(errorResponse(null, INVALID_REQUEST, "Invalid Request"));
158
+ return;
159
+ }
160
+ const request = parsed;
161
+ const id = normalizeId(request.id);
162
+ if (request.jsonrpc !== "2.0" || typeof request.method !== "string") {
163
+ this.writeResponse(errorResponse(id, INVALID_REQUEST, "Invalid Request"));
164
+ return;
165
+ }
166
+ const method = request.method;
167
+ const params = (request.params ?? null);
168
+ const handler = this.dispatch.get(method);
169
+ if (handler === undefined) {
170
+ this.writeResponse(errorResponse(id, METHOD_NOT_FOUND, `Method not found: ${truncateMethodEcho(method)}`));
171
+ return;
172
+ }
173
+ try {
174
+ const result = await handler(params);
175
+ this.writeResponse(successResponse(id, result));
176
+ }
177
+ catch (error) {
178
+ if (error instanceof RpcError) {
179
+ this.writeResponse(errorResponse(id, error.code, error.message));
180
+ return;
181
+ }
182
+ if (error instanceof Error && error.stack) {
183
+ this.stderr.write(`${error.stack}\n`);
184
+ }
185
+ else {
186
+ this.stderr.write(`${String(error)}\n`);
187
+ }
188
+ this.writeResponse(errorResponse(id, INTERNAL_ERROR, errorMessage(error)));
189
+ }
190
+ }
191
+ writeResponse(response) {
192
+ try {
193
+ this.stdout.write(`${serialize(response)}\n`);
194
+ }
195
+ catch {
196
+ this.brokenPipe = true;
197
+ }
198
+ }
199
+ createDefaultDispatch() {
200
+ const dispatch = new Map();
201
+ dispatch.set("initialize", (params) => {
202
+ requireRootPath(requireParamsObject(params));
203
+ return initializeResult();
204
+ });
205
+ dispatch.set("shutdown", () => {
206
+ this.shuttingDown = true;
207
+ return shutdownResult();
208
+ });
209
+ // `discover` (FR-009, FR-019): params must be an object carrying exactly
210
+ // one string `root_path`; the validation order and message strings are
211
+ // pinned by contracts/discover.md's error table and must not drift.
212
+ dispatch.set("discover", async (params) => {
213
+ const record = requireParamsObject(params);
214
+ const rootPath = requireRootPath(record);
215
+ const keys = Object.keys(record);
216
+ if (keys.length !== 1 || keys[0] !== "root_path") {
217
+ throw new RpcError(INVALID_PARAMS, "Invalid params: params must contain only root_path");
218
+ }
219
+ try {
220
+ // The server's stderr is forwarded (T024) so discover's
221
+ // safe-reader skip diagnostics reach the process stderr — never
222
+ // stdout, which is reserved for JSON-RPC responses (FR-017).
223
+ return await discover(rootPath, this.stderr);
224
+ }
225
+ catch (error) {
226
+ // Root failures take the shared -32602 message (mapRootPathError);
227
+ // anything else rethrows for handleLine's -32603 mapping.
228
+ throw mapRootPathError(error) ?? error;
229
+ }
230
+ });
231
+ // `analyze` (FR-027, FR-020; contracts/analyze.md error table): the
232
+ // shared analysis-params validation, then the T014 pipeline + T018
233
+ // detector wrapped as `{"functions": [...]}`. The capability
234
+ // response is unchanged — analyze is a core method, not gated
235
+ // behind a capability flag (FR-028).
236
+ dispatch.set("analyze", async (params) => {
237
+ const { rootPath, patterns } = validateAnalysisParams(params);
238
+ try {
239
+ // The pipeline's skip diagnostics flow to the server's stderr —
240
+ // never stdout, which is reserved for JSON-RPC responses
241
+ // (FR-017). The result is already the serialized, wire-shaped
242
+ // record array (T018), so the sorted-key envelope serializer
243
+ // only re-orders keys — repeated requests stay byte-identical
244
+ // (SC-003/SC-006).
245
+ return { functions: await analyze(rootPath, patterns, this.stderr) };
246
+ }
247
+ catch (error) {
248
+ throw mapRootPathError(error) ?? error;
249
+ }
250
+ });
251
+ // `complexity` (FR-027, FR-022; research R12; contracts/complexity.md
252
+ // error table): the SAME shared analysis-params validation as analyze,
253
+ // then the T014 pipeline + T023 computation wrapped as
254
+ // `{"functions": [...]}`. The capability response is unchanged —
255
+ // complexity is a core method, not gated behind a capability flag
256
+ // (FR-028).
257
+ dispatch.set("complexity", async (params) => {
258
+ const { rootPath, patterns } = validateAnalysisParams(params);
259
+ try {
260
+ // computeComplexity (T023) closes the same prepareAnalysis
261
+ // pipeline (T014) analyze runs, so FR-022's parity is structural.
262
+ // Its result is already the serialized, wire-shaped record array,
263
+ // so the sorted-key envelope serializer only re-orders keys —
264
+ // repeated requests stay byte-identical (SC-003/SC-006). Skip
265
+ // diagnostics flow to the server's stderr, never stdout, which is
266
+ // reserved for JSON-RPC responses (FR-017).
267
+ return { functions: await computeComplexity(rootPath, patterns, this.stderr) };
268
+ }
269
+ catch (error) {
270
+ throw mapRootPathError(error) ?? error;
271
+ }
272
+ });
273
+ // `coverage` (FR-027, FR-023–FR-026; research R12; contracts/coverage.md
274
+ // error table): the SAME shared analysis-params validation as
275
+ // analyze/complexity, then the T028 Istanbul artifact parser wrapped
276
+ // as `{"functions": [...]}`. The capability response is unchanged —
277
+ // coverage is a core method, not gated behind a capability flag
278
+ // (FR-028).
279
+ dispatch.set("coverage", async (params) => {
280
+ const { rootPath, patterns } = validateAnalysisParams(params);
281
+ try {
282
+ // parseCoverage (T028) returns the serialized, wire-shaped entry
283
+ // array (empty on every degradation-ladder rung, never a
284
+ // JSON-RPC error), so the sorted-key envelope serializer only
285
+ // re-orders keys — repeated requests stay byte-identical
286
+ // (SC-003/SC-006). Skip diagnostics flow to the server's stderr,
287
+ // never stdout, which is reserved for JSON-RPC responses
288
+ // (FR-017).
289
+ return { functions: await parseCoverage(rootPath, patterns, this.stderr) };
290
+ }
291
+ catch (error) {
292
+ throw mapRootPathError(error) ?? error;
293
+ }
294
+ });
295
+ // `classify_signals` (FR-014/FR-015; research R11; contracts/
296
+ // classify-signals.md error table): the SAME shared analysis-params
297
+ // validation as analyze/complexity/coverage, then the T029 entry —
298
+ // the identical pipeline stages analyze runs, emitting the
299
+ // raw pair-keyed signal feed — wrapped as `{"signals": [...]}`.
300
+ // Unlike the core analysis methods, this one is capability-gated from
301
+ // the platform's side (Gaze calls it when and only when the
302
+ // initialize flag is true, FR-015), so initializeResult() advertises
303
+ // `classify_signals: true` in the same protocol-state unit as this
304
+ // registration — no commit advertises a capability the dispatch table
305
+ // lacks. The method registers unconditionally: no runtime toggle.
306
+ dispatch.set("classify_signals", async (params) => {
307
+ const { rootPath, patterns } = validateAnalysisParams(params);
308
+ try {
309
+ // classifySignals (T029) runs the identical prepareAnalysis →
310
+ // detectEffects → signal-core stages analyze runs (FR-013's
311
+ // one-pipeline guarantee is structural), so the two methods can
312
+ // never disagree about which functions or effects exist. Its
313
+ // result is already the serialized, wire-shaped signal array
314
+ // (T004), so the sorted-key envelope serializer only re-orders
315
+ // keys — repeated requests stay byte-identical (SC-005). The
316
+ // wrapper is typed against ClassifySignalsResult — and the
317
+ // entry's return against ClassifySignalsResult["signals"] — so
318
+ // the one-key {"signals": [...]} wire shape is compile-time
319
+ // enforced end to end. Skip diagnostics flow to the server's
320
+ // stderr, never stdout, which is reserved for JSON-RPC responses
321
+ // (FR-017).
322
+ const result = {
323
+ signals: await classifySignals(rootPath, patterns, this.stderr),
324
+ };
325
+ return result;
326
+ }
327
+ catch (error) {
328
+ throw mapRootPathError(error) ?? error;
329
+ }
330
+ });
331
+ // `test_mapping` (FR-013/FR-014; research R9; contracts/
332
+ // test-mapping.md Sections 1–5): the SAME shared analysis-params
333
+ // validation as analyze/complexity/coverage/classify_signals — one
334
+ // validator, one error table, never a copy — then the T019 entry:
335
+ // the mapping pipeline over the one shared analysis walk, wrapped
336
+ // as the one-key `{"mappings": [...]}` result. Like
337
+ // classify_signals, the method is capability-gated from the
338
+ // platform's side (Gaze calls it when and only when the initialize
339
+ // flag is true, FR-014), so initializeResult() advertises
340
+ // `test_mapping: true` in the same protocol-state unit as this
341
+ // registration — no commit advertises a capability the dispatch
342
+ // table lacks. The method registers unconditionally: no runtime
343
+ // toggle.
344
+ dispatch.set("test_mapping", async (params) => {
345
+ const { rootPath, patterns } = validateAnalysisParams(params);
346
+ try {
347
+ // testMapping (T019) runs the identical prepareAnalysis →
348
+ // detectEffects stages analyze runs (FR-013's one-pipeline
349
+ // guarantee is structural), so analyze and test_mapping can
350
+ // never disagree about which functions or effects exist — the
351
+ // rows ride the same effect sets, sorted by FR-013's stable key
352
+ // inside the entry, so repeated requests stay byte-identical
353
+ // (SC-005). The result is typed as TestMappingResult — the
354
+ // entry returns it whole (the pipeline assembles the one-key
355
+ // object itself; classifySignals returns the bare array, its
356
+ // handler wraps) — so the `{"mappings": [...]}` wire shape is
357
+ // compile-time enforced end to end. Skip diagnostics flow to
358
+ // the server's stderr, never stdout, which is reserved for
359
+ // JSON-RPC responses (spec 001 FR-017).
360
+ const result = await testMapping(rootPath, patterns, this.stderr);
361
+ return result;
362
+ }
363
+ catch (error) {
364
+ throw mapRootPathError(error) ?? error;
365
+ }
366
+ });
367
+ // `doc_coverage` (spec 005 FR-001 to FR-004 and FR-012; protocol.md
368
+ // v1.2.0's doc_coverage schema): the SAME shared analysis-params
369
+ // validation as analyze/complexity/coverage/classify_signals/
370
+ // test_mapping — one validator, one error table, never a copy —
371
+ // then the T008 entry: the exported-symbol documentation walk over
372
+ // the one shared analysis pipeline, wrapped as the one-key
373
+ // `{"symbols": [...]}` result. Like classify_signals and
374
+ // test_mapping, the method is capability-gated from the platform's
375
+ // side (Gaze calls it when and only when the initialize flag is
376
+ // true, spec 005 FR-013), so initializeResult() advertises
377
+ // `doc_coverage: true` in the same protocol-state unit as this
378
+ // registration — no commit advertises a capability the dispatch
379
+ // table lacks. The method registers unconditionally: no runtime
380
+ // toggle. Registering it shrinks the reserved -32601 set to exactly
381
+ // analyze/stream + cognitive_complexity (FR-012).
382
+ dispatch.set("doc_coverage", async (params) => {
383
+ const { rootPath, patterns } = validateAnalysisParams(params);
384
+ try {
385
+ // docCoverage (T008) runs the identical prepareAnalysis stages
386
+ // analyze runs, so FR-004's file-set parity with analyze's
387
+ // source arm is structural. Its result is already the
388
+ // serialized, wire-shaped row array — sorted by (file, line,
389
+ // name) inside the entry — so the sorted-key envelope
390
+ // serializer only re-orders keys: repeated requests stay
391
+ // byte-identical (spec 005 US1 scenario 3). The wrapper is
392
+ // typed against DocCoverageResult and the entry returns the
393
+ // bare `symbols` payload (the computeComplexity split), so the
394
+ // one-key `{"symbols": [...]}` wire shape is compile-time
395
+ // enforced end to end. Skip diagnostics flow to the server's
396
+ // stderr, never stdout, which is reserved for JSON-RPC
397
+ // responses (spec 001 FR-017).
398
+ const result = {
399
+ symbols: await docCoverage(rootPath, patterns, this.stderr),
400
+ };
401
+ return result;
402
+ }
403
+ catch (error) {
404
+ throw mapRootPathError(error) ?? error;
405
+ }
406
+ });
407
+ // `cognitive_complexity` (spec 005 FR-005 to FR-009 and FR-012;
408
+ // protocol.md v1.2.0's cognitive_complexity schema): the SAME shared
409
+ // analysis-params validation as analyze/complexity/coverage/
410
+ // classify_signals/test_mapping/doc_coverage — one validator, one
411
+ // error table, never a copy — then the T016 entry: the SonarSource
412
+ // cognitive-complexity walk over the one shared analysis pipeline,
413
+ // wrapped as the one-key `{"functions": [...]}` result. Like the
414
+ // other capability-gated methods, the method is capability-gated
415
+ // from the platform's side (Gaze calls it when and only when the
416
+ // initialize flag is true, spec 005 FR-013), so initializeResult()
417
+ // advertises `cognitive_complexity: true` in the same
418
+ // protocol-state unit as this registration — no commit advertises a
419
+ // capability the dispatch table lacks. The method registers
420
+ // unconditionally: no runtime toggle. Registering it shrinks the
421
+ // reserved -32601 set to exactly analyze/stream (FR-012).
422
+ dispatch.set("cognitive_complexity", async (params) => {
423
+ const { rootPath, patterns } = validateAnalysisParams(params);
424
+ try {
425
+ // cognitiveComplexity (T016) runs the identical prepareAnalysis
426
+ // stages analyze runs over the same extraction records, so US2-2's
427
+ // parity with the cyclomatic complexity method is structural (a
428
+ // function has a cognitive score if and only if it has a cyclomatic
429
+ // one). Its result is already the serialized, wire-shaped row
430
+ // array — sorted by (file, line, name) inside the entry — so the
431
+ // sorted-key envelope serializer only re-orders keys: repeated
432
+ // requests stay byte-identical (spec 005 US2 scenario 1). The
433
+ // wrapper is typed against CognitiveComplexityResult and the entry
434
+ // returns the bare `functions` payload (the computeComplexity
435
+ // split), so the one-key `{"functions": [...]}` wire shape is
436
+ // compile-time enforced end to end. Skip diagnostics flow to the
437
+ // server's stderr, never stdout, which is reserved for JSON-RPC
438
+ // responses (spec 001 FR-017).
439
+ const result = {
440
+ functions: await cognitiveComplexity(rootPath, patterns, this.stderr),
441
+ };
442
+ return result;
443
+ }
444
+ catch (error) {
445
+ throw mapRootPathError(error) ?? error;
446
+ }
447
+ });
448
+ return dispatch;
449
+ }
450
+ }
451
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1,103 @@
1
+ import type { ExtractionRecord } from "../extract.js";
2
+ import { type Classification, type Effect } from "../models.js";
3
+ import { type SideEffectType } from "../taxonomy.js";
4
+ import type { RecordEvidence } from "./evidence.js";
5
+ import type { Signal } from "./types.js";
6
+ /**
7
+ * One pair's classification result (data-model.md Section 5.4): the pair's
8
+ * wire rows — the extractor signals plus the synthesized contradiction row
9
+ * when it fires, in four-key order — and the formula's `Classification`
10
+ * every same-type effect instance of the pair will carry.
11
+ */
12
+ export interface SignalBundle {
13
+ /** The pair's signals in `(package, function, type, source)` order. */
14
+ readonly signals: readonly Signal[];
15
+ /** The pair's confidence and label (FR-009/FR-010). */
16
+ readonly classification: Classification;
17
+ }
18
+ /**
19
+ * The fan-out result (FR-008; data-model.md Section 5.4): the full
20
+ * `(package, function, side_effect_type, source)`-ordered signal feed and
21
+ * every record's effects rebuilt as new immutable values with
22
+ * `classification` set — `analyze`'s assembly input and
23
+ * `classify_signals`' feed source, one shape for both consumers.
24
+ */
25
+ export interface ClassifiedEffects {
26
+ /** Every emitted signal, in FR-014's four-key order. */
27
+ readonly signals: readonly Signal[];
28
+ /** Each record's effects, rebuilt with classification attached. */
29
+ readonly effects: ReadonlyMap<ExtractionRecord, readonly Effect[]>;
30
+ }
31
+ /**
32
+ * Classifies one (function record, canonical effect type) pair (FR-011;
33
+ * data-model.md Sections 4, 5.4) — the per-pair core `classifyPairs` fans
34
+ * out to, and the seam tests/signals/adapter.test.ts pins directly with
35
+ * hand-built signals (deliberately out-of-set weights included, for the
36
+ * clamp rows real extractor arithmetic cannot reach).
37
+ *
38
+ * The contradiction rule is a property of the PAIR, not a per-signal
39
+ * penalty: when the extractor signals mix at least one positive and at
40
+ * least one negative weight, exactly ONE synthesized row joins the bundle
41
+ * — source `contradiction`, weight −20, the first signal's identity
42
+ * fields, the pair's canonical type, the fixed-template reasoning — and
43
+ * the formula applies the −20 exactly once however many signals of either
44
+ * polarity fired. All-positive and all-negative evidence is agreement,
45
+ * never a contradiction; a weight of 0 is polarity-neutral.
46
+ *
47
+ * The formula (FR-009/FR-010): `clamp(0, 100, 50 + tierBoost +
48
+ * Σ(extractor weights) − (contradiction ? 20 : 0))` — the tier from
49
+ * `TIER_MAP` (the taxonomy is the single tier authority), the sum over the
50
+ * EXTRACTOR signals only (the synthesized row's −20 is the separate
51
+ * one-time term, which is what keeps the emitted feed sum-invariant). The
52
+ * clamp applies to the confidence only — emitted rows keep their real
53
+ * weights, so the evidence a consumer reads is never distorted by the
54
+ * bound.
55
+ *
56
+ * @param extractorSignals The pair's already-extracted signals — the five
57
+ * extractors' defined results, any order; never mutated.
58
+ * @param effectType The pair's canonical effect type — the `TIER_MAP` key
59
+ * and the synthesized row's `side_effect_type`; structural for the empty
60
+ * bundle, where no signal exists to read it from.
61
+ * @returns The pair's `SignalBundle`: its wire rows in four-key order
62
+ * (contradiction row included when it fires) and its `Classification`.
63
+ * @throws Error never in real flow — the identity guard below is
64
+ * structurally unreachable (mixed polarity implies a non-empty bundle) and
65
+ * exists to keep that claim loud rather than asserted.
66
+ */
67
+ export declare function classifyBundle(extractorSignals: readonly Signal[], effectType: SideEffectType): SignalBundle;
68
+ /**
69
+ * Runs the classification fan-out over one prepared analysis's records
70
+ * (FR-008; research R8) — the shared engine both consumers call after
71
+ * `detectEffects` and `buildRecordEvidence`, per the composition contract
72
+ * in this module's header.
73
+ *
74
+ * Pair keying: the extractors run once per (record, DISTINCT canonical
75
+ * effect type) pair — the fan-out counts types, never effect instances —
76
+ * so same-type instances share one bundle's signals and one classification,
77
+ * and distinct types on one record run independently (the routing gate
78
+ * decides per pair; neither pair's evidence leaks to the other). Extractor
79
+ * results are never deduplicated across sources: a naming and a
80
+ * documentation match on one pair yield two signals, never one merged row.
81
+ *
82
+ * Evidence totality is the hard dependency: a record in `records` without
83
+ * an evidence snapshot is an upstream bug and fails loud (the
84
+ * `callerSignal` posture — never a silent skip, which would be a
85
+ * Constitution Principle II silent false negative). A record ABSENT from
86
+ * the effects map is benign no-pairs and still keys the output map (output
87
+ * totality mirrors `detectEffects`' own over `records`).
88
+ *
89
+ * @param records The extraction records, any order; the output map keys
90
+ * every record.
91
+ * @param effects `detectEffects`' per-record effect map, consumed
92
+ * read-only.
93
+ * @param evidence `buildRecordEvidence`'s per-record snapshot map, keyed by
94
+ * the same record references.
95
+ * @returns The `ClassifiedEffects`: the four-key-ordered signal feed and
96
+ * every record's effects rebuilt as new immutable values with
97
+ * `classification` set (AP-004 — the detector's instances are never
98
+ * mutated, every field preserved, input order preserved).
99
+ * @throws Error when a record in `records` has no evidence snapshot, or
100
+ * when an effect's type carries no pair classification (structurally
101
+ * impossible — the pair loop keys every detected type).
102
+ */
103
+ export declare function classifyPairs(records: readonly ExtractionRecord[], effects: ReadonlyMap<ExtractionRecord, readonly Effect[]>, evidence: ReadonlyMap<ExtractionRecord, RecordEvidence>): ClassifiedEffects;