reading-stone 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +11 -0
  3. package/README.md +274 -2
  4. package/dist/analysis.d.ts +341 -0
  5. package/dist/analysis.js +392 -0
  6. package/dist/cognitive.d.ts +163 -0
  7. package/dist/cognitive.js +380 -0
  8. package/dist/complexity.d.ts +102 -0
  9. package/dist/complexity.js +163 -0
  10. package/dist/coverage.d.ts +78 -0
  11. package/dist/coverage.js +635 -0
  12. package/dist/detector.d.ts +41 -0
  13. package/dist/detector.js +2134 -0
  14. package/dist/discovery.d.ts +330 -0
  15. package/dist/discovery.js +930 -0
  16. package/dist/doc-coverage.d.ts +155 -0
  17. package/dist/doc-coverage.js +543 -0
  18. package/dist/extract.d.ts +209 -0
  19. package/dist/extract.js +498 -0
  20. package/dist/index.d.ts +64 -0
  21. package/dist/index.js +54 -0
  22. package/dist/internal.d.ts +75 -0
  23. package/dist/internal.js +63 -0
  24. package/dist/main.d.ts +8 -0
  25. package/dist/main.js +39 -0
  26. package/dist/models.d.ts +185 -0
  27. package/dist/models.js +170 -0
  28. package/dist/program.d.ts +207 -0
  29. package/dist/program.js +662 -0
  30. package/dist/protocol.d.ts +88 -0
  31. package/dist/protocol.js +74 -0
  32. package/dist/quality/assertions.d.ts +81 -0
  33. package/dist/quality/assertions.js +425 -0
  34. package/dist/quality/collect.d.ts +66 -0
  35. package/dist/quality/collect.js +412 -0
  36. package/dist/quality/inference.d.ts +86 -0
  37. package/dist/quality/inference.js +603 -0
  38. package/dist/quality/matchers.d.ts +129 -0
  39. package/dist/quality/matchers.js +220 -0
  40. package/dist/quality/pairing.d.ts +133 -0
  41. package/dist/quality/pairing.js +770 -0
  42. package/dist/quality/pipeline.d.ts +59 -0
  43. package/dist/quality/pipeline.js +202 -0
  44. package/dist/quality/types.d.ts +127 -0
  45. package/dist/quality/types.js +92 -0
  46. package/dist/safeio.d.ts +107 -0
  47. package/dist/safeio.js +314 -0
  48. package/dist/server.d.ts +19 -0
  49. package/dist/server.js +451 -0
  50. package/dist/signals/adapter.d.ts +103 -0
  51. package/dist/signals/adapter.js +323 -0
  52. package/dist/signals/caller-index.d.ts +117 -0
  53. package/dist/signals/caller-index.js +147 -0
  54. package/dist/signals/caller.d.ts +76 -0
  55. package/dist/signals/caller.js +108 -0
  56. package/dist/signals/evidence.d.ts +233 -0
  57. package/dist/signals/evidence.js +578 -0
  58. package/dist/signals/interface.d.ts +68 -0
  59. package/dist/signals/interface.js +87 -0
  60. package/dist/signals/jsdoc.d.ts +27 -0
  61. package/dist/signals/jsdoc.js +233 -0
  62. package/dist/signals/naming.d.ts +26 -0
  63. package/dist/signals/naming.js +160 -0
  64. package/dist/signals/routing.d.ts +163 -0
  65. package/dist/signals/routing.js +416 -0
  66. package/dist/signals/types.d.ts +146 -0
  67. package/dist/signals/types.js +99 -0
  68. package/dist/signals/visibility.d.ts +23 -0
  69. package/dist/signals/visibility.js +82 -0
  70. package/dist/taxonomy.d.ts +89 -0
  71. package/dist/taxonomy.js +217 -0
  72. package/package.json +61 -4
@@ -0,0 +1,59 @@
1
+ import type { Writable } from "node:stream";
2
+ import { type TestMappingResult } from "./types.js";
3
+ /**
4
+ * The `test_mapping` method's entry (FR-012/FR-013; data-model.md
5
+ * Sections 1 and 8): the serialized `MappingRow[]` payload — one row per
6
+ * (paired test, assertion), assembled in FR-013's stable-key order and
7
+ * already wire-shaped through `serializeMappingRow`, under the result
8
+ * interface's single `mappings` key.
9
+ *
10
+ * The stages, in order (all inside the context's live window):
11
+ *
12
+ * 1. `prepareAnalysis(rootPath, patterns, stderr, { includeTestArm: true })`
13
+ * — the one shared pipeline (FR-013's one-pipeline guarantee is
14
+ * structural, never a second walk): the identical target records
15
+ * `analyze` reports, the full pattern-UNfiltered test arm, and the
16
+ * bootstrapped `ProgramContext` admitting the test files.
17
+ * `InvalidRootPathError` propagates untouched for the server to map
18
+ * to the shared `-32602` root message.
19
+ * 2. `detectEffects` over the target records — the same effect sets
20
+ * `analyze` reports, threaded through the `TargetIndex` so pairing
21
+ * and inference share one detection result.
22
+ * 3. `collectTestFunctions` over the test arm — the test-side input,
23
+ * sorted by `(relPath, collection index)`.
24
+ * 4. `buildTargetIndex` + `pairTests` — the three pairing strategies
25
+ * (naming, calls, imports) in first-match-wins priority order.
26
+ * 5. `collectAssertions` per paired test (memoized per test function —
27
+ * a test paired with several targets walks its callback once, never
28
+ * once per pair), US4's provenance inputs per paired test with
29
+ * assertions (the live context plus the test file's file-local
30
+ * helper table — `collectFileLocalHelpers`, memoized per test file so
31
+ * one file's top level scans once however many of its tests pair),
32
+ * `inferSideEffectType` per (pair, assertion).
33
+ * 6. Row assembly and the stable-key sort, then `serializeMappingRow`.
34
+ *
35
+ * The program-mode context's dispose lifetime is owned here exactly as
36
+ * the analysis handlers own theirs (the same `finally` discipline): the
37
+ * native compiler server behind the context is closed whatever the
38
+ * stage outcomes, so no subprocess outlives one request. A parse-only
39
+ * context owns nothing to dispose. `prepareAnalysis` itself releases
40
+ * the context when extraction throws, and an invalid root throws before
41
+ * any context exists.
42
+ *
43
+ * @param rootPath Absolute or relative project root; validated and
44
+ * realpath-resolved by `prepareAnalysis` (an invalid root throws
45
+ * `InvalidRootPathError`, the server maps to `-32602`).
46
+ * @param patterns The raw `patterns` parameter value; shape-validated by
47
+ * the server (`-32602`) before analysis runs, normalized by
48
+ * `prepareAnalysis`. Patterns narrow the TARGET arm exactly as `analyze`
49
+ * applies them; the test arm is never narrowed (FR-006). A set matching
50
+ * nothing yields `{"mappings": []}`, never an error.
51
+ * @param stderr Injected diagnostic sink (Testability principle);
52
+ * defaults to `process.stderr`. Stdout is never touched.
53
+ * @returns The `TestMappingResult` — `{ mappings: [...] }`, rows in
54
+ * FR-013's stable-key order, `[]` for every empty-input shape.
55
+ * @throws InvalidRootPathError when the root does not exist, is not a
56
+ * directory, or cannot be accessed; the server handler maps it to the
57
+ * contract's `-32602` response.
58
+ */
59
+ export declare function testMapping(rootPath: string, patterns?: unknown, stderr?: Writable): Promise<TestMappingResult>;
@@ -0,0 +1,202 @@
1
+ // The `test_mapping` method entry (T019; FR-012/FR-013; research R2, R8;
2
+ // data-model.md Sections 1 and 8; Constitution Principles I, III, and V).
3
+ //
4
+ // `testMapping` orchestrates the mapping pipeline's stages over the ONE
5
+ // shared analysis pipeline: `prepareAnalysis` with the test-arm widening
6
+ // (FR-006 — the identical discovered, pattern-filtered,
7
+ // exclusion-filtered target set `analyze` reports, plus the full test
8
+ // arm), `detectEffects` over those targets (the same effect sets
9
+ // `analyze` reports), then the mapping stages — test collection, target
10
+ // indexing, pairing (naming, calls, imports — first-match-wins), assertion
11
+ // collection, inference — and FR-013's row assembly, stable-key sort, and
12
+ // serialization.
13
+ //
14
+ // Every stage is deterministic (Constitution I): the result is a pure
15
+ // function of the analyzed tree and analyzer version — no timestamps, no
16
+ // environment-dependent data — so repeated requests over the same tree
17
+ // serialize byte-identically (the two-walk golden R10 pins it end to
18
+ // end, walk included).
19
+ //
20
+ // Strictly static (Constitution V): test files are untrusted input,
21
+ // parsed with the compiler API inside the bounded hermetic host, never
22
+ // executed or imported — the throwing-module canary in
23
+ // tests/quality/pipeline.test.ts pins it. Skip diagnostics flow to the
24
+ // injected stderr sink, never stdout (it is reserved for JSON-RPC
25
+ // responses).
26
+ //
27
+ // Empty inputs are successes, never errors (US1-8): no test files, no
28
+ // production targets, a match-nothing pattern set, or no pairs all
29
+ // yield `{"mappings": []}`.
30
+ import { prepareAnalysis } from "../analysis.js";
31
+ import { detectEffects } from "../detector.js";
32
+ import { derivePackage } from "../models.js";
33
+ import { collectAssertions } from "./assertions.js";
34
+ import { collectTestFunctions } from "./collect.js";
35
+ import { collectFileLocalHelpers, inferSideEffectType, } from "./inference.js";
36
+ import { buildTargetIndex, pairTests } from "./pairing.js";
37
+ import { serializeMappingRow, } from "./types.js";
38
+ /**
39
+ * FR-013's stable row key: `(test_file, test_function, target_package,
40
+ * target_function, assertion line, assertion character)` — UTF-16
41
+ * code-unit comparison (JavaScript's default `<`) for the string keys,
42
+ * numeric comparison for line and character, so line 10 sorts after
43
+ * line 9, never lexicographically where `"10" < "9"`.
44
+ *
45
+ * Full-key ties return `0` and the platform-stable sort resolves them
46
+ * by emission order — the AST-walk collection order the rows were
47
+ * assembled in — which is the pinned final tie-break: two matcher
48
+ * invocations sharing one expect chain (identical anchor, identical
49
+ * pair) emit in the source order of their matcher properties
50
+ * (data-model Section 8).
51
+ *
52
+ * @param a Left pending row.
53
+ * @param b Right pending row.
54
+ * @returns The six-key comparison result.
55
+ */
56
+ function comparePendingRows(a, b) {
57
+ if (a.row.test_file !== b.row.test_file) {
58
+ return a.row.test_file < b.row.test_file ? -1 : 1;
59
+ }
60
+ if (a.row.test_function !== b.row.test_function) {
61
+ return a.row.test_function < b.row.test_function ? -1 : 1;
62
+ }
63
+ if (a.row.target_package !== b.row.target_package) {
64
+ return a.row.target_package < b.row.target_package ? -1 : 1;
65
+ }
66
+ if (a.row.target_function !== b.row.target_function) {
67
+ return a.row.target_function < b.row.target_function ? -1 : 1;
68
+ }
69
+ if (a.line !== b.line) {
70
+ return a.line - b.line;
71
+ }
72
+ return a.character - b.character;
73
+ }
74
+ /**
75
+ * The `test_mapping` method's entry (FR-012/FR-013; data-model.md
76
+ * Sections 1 and 8): the serialized `MappingRow[]` payload — one row per
77
+ * (paired test, assertion), assembled in FR-013's stable-key order and
78
+ * already wire-shaped through `serializeMappingRow`, under the result
79
+ * interface's single `mappings` key.
80
+ *
81
+ * The stages, in order (all inside the context's live window):
82
+ *
83
+ * 1. `prepareAnalysis(rootPath, patterns, stderr, { includeTestArm: true })`
84
+ * — the one shared pipeline (FR-013's one-pipeline guarantee is
85
+ * structural, never a second walk): the identical target records
86
+ * `analyze` reports, the full pattern-UNfiltered test arm, and the
87
+ * bootstrapped `ProgramContext` admitting the test files.
88
+ * `InvalidRootPathError` propagates untouched for the server to map
89
+ * to the shared `-32602` root message.
90
+ * 2. `detectEffects` over the target records — the same effect sets
91
+ * `analyze` reports, threaded through the `TargetIndex` so pairing
92
+ * and inference share one detection result.
93
+ * 3. `collectTestFunctions` over the test arm — the test-side input,
94
+ * sorted by `(relPath, collection index)`.
95
+ * 4. `buildTargetIndex` + `pairTests` — the three pairing strategies
96
+ * (naming, calls, imports) in first-match-wins priority order.
97
+ * 5. `collectAssertions` per paired test (memoized per test function —
98
+ * a test paired with several targets walks its callback once, never
99
+ * once per pair), US4's provenance inputs per paired test with
100
+ * assertions (the live context plus the test file's file-local
101
+ * helper table — `collectFileLocalHelpers`, memoized per test file so
102
+ * one file's top level scans once however many of its tests pair),
103
+ * `inferSideEffectType` per (pair, assertion).
104
+ * 6. Row assembly and the stable-key sort, then `serializeMappingRow`.
105
+ *
106
+ * The program-mode context's dispose lifetime is owned here exactly as
107
+ * the analysis handlers own theirs (the same `finally` discipline): the
108
+ * native compiler server behind the context is closed whatever the
109
+ * stage outcomes, so no subprocess outlives one request. A parse-only
110
+ * context owns nothing to dispose. `prepareAnalysis` itself releases
111
+ * the context when extraction throws, and an invalid root throws before
112
+ * any context exists.
113
+ *
114
+ * @param rootPath Absolute or relative project root; validated and
115
+ * realpath-resolved by `prepareAnalysis` (an invalid root throws
116
+ * `InvalidRootPathError`, the server maps to `-32602`).
117
+ * @param patterns The raw `patterns` parameter value; shape-validated by
118
+ * the server (`-32602`) before analysis runs, normalized by
119
+ * `prepareAnalysis`. Patterns narrow the TARGET arm exactly as `analyze`
120
+ * applies them; the test arm is never narrowed (FR-006). A set matching
121
+ * nothing yields `{"mappings": []}`, never an error.
122
+ * @param stderr Injected diagnostic sink (Testability principle);
123
+ * defaults to `process.stderr`. Stdout is never touched.
124
+ * @returns The `TestMappingResult` — `{ mappings: [...] }`, rows in
125
+ * FR-013's stable-key order, `[]` for every empty-input shape.
126
+ * @throws InvalidRootPathError when the root does not exist, is not a
127
+ * directory, or cannot be accessed; the server handler maps it to the
128
+ * contract's `-32602` response.
129
+ */
130
+ export async function testMapping(rootPath, patterns, stderr = process.stderr) {
131
+ const prepared = await prepareAnalysis(rootPath, patterns, stderr, {
132
+ includeTestArm: true,
133
+ });
134
+ try {
135
+ // The same detection result analyze reports, taken while the
136
+ // program-mode context is live (checker queries ride it) and shared
137
+ // by the target index and the inference stage — never a second walk.
138
+ const effects = detectEffects(prepared.records, prepared.context);
139
+ const tests = collectTestFunctions(prepared.testPaths, prepared.context, prepared.rootPath, stderr);
140
+ const index = buildTargetIndex(prepared.records, effects, prepared.context);
141
+ const pairs = pairTests(tests, index, prepared.rootPath, stderr);
142
+ // Assertion collection memoized per test function: a test paired
143
+ // with several same-named targets walks its callback subtree once,
144
+ // and every pair's rows read the identical sites — evidence never
145
+ // recomputed per assertion (research R8's single-walk discipline).
146
+ const assertionsByTest = new Map();
147
+ // The per-test-file helper table memo (T031; FR-011): file-scope
148
+ // helpers are a property of the FILE, so the table computes once per
149
+ // relPath and every test in the file reads the identical evidence
150
+ // (research R8's single-walk discipline).
151
+ const helpersByFile = new Map();
152
+ const pending = [];
153
+ for (const pair of pairs) {
154
+ const sites = assertionsByTest.get(pair.test);
155
+ const assertions = sites ?? collectAssertions(pair.test, stderr);
156
+ if (sites === undefined) {
157
+ assertionsByTest.set(pair.test, assertions);
158
+ }
159
+ const targetEffects = index.effects.get(pair.target) ?? [];
160
+ // US4's provenance inputs (T031; FR-011): built only when rows will
161
+ // be built — the live context plus the test file's file-local
162
+ // helper table. A null-callback test collects no assertions, so no
163
+ // inputs are built for it.
164
+ let provenance;
165
+ if (assertions.length > 0 && pair.test.callback !== null) {
166
+ let helpers = helpersByFile.get(pair.test.relPath);
167
+ if (helpers === undefined) {
168
+ helpers = collectFileLocalHelpers(pair.test.callback.getSourceFile());
169
+ helpersByFile.set(pair.test.relPath, helpers);
170
+ }
171
+ provenance = { context: prepared.context, helpers };
172
+ }
173
+ for (const assertion of assertions) {
174
+ pending.push({
175
+ row: {
176
+ test_function: pair.test.qualifiedTitle,
177
+ test_file: pair.test.relPath,
178
+ assertion_location: `${pair.test.relPath}:${assertion.line}`,
179
+ assertion_type: assertion.kind,
180
+ target_function: pair.target.name,
181
+ target_package: derivePackage(pair.target.relPath),
182
+ side_effect_type: inferSideEffectType(assertion, pair, targetEffects, provenance),
183
+ confidence: pair.confidence,
184
+ },
185
+ line: assertion.line,
186
+ character: assertion.character,
187
+ });
188
+ }
189
+ }
190
+ // The platform-stable sort: full-key ties (two matcher invocations
191
+ // sharing one expect chain) keep their AST-walk collection order —
192
+ // the pinned final tie-break.
193
+ pending.sort(comparePendingRows);
194
+ return { mappings: pending.map((entry) => serializeMappingRow(entry.row)) };
195
+ }
196
+ finally {
197
+ if (prepared.context.mode === "program") {
198
+ prepared.context.dispose();
199
+ }
200
+ }
201
+ }
202
+ //# sourceMappingURL=pipeline.js.map
@@ -0,0 +1,127 @@
1
+ import { type SideEffectType } from "../taxonomy.js";
2
+ /**
3
+ * The test-mapping wire record (FR-001; research R1, R8; data-model.md
4
+ * Section 2) — one row per (paired test, assertion): a test with three
5
+ * assertions yields three rows sharing target fields with distinct
6
+ * `assertion_location` values (US1-2).
7
+ *
8
+ * Field names are the wire spellings — snake_case per the protocol
9
+ * payload contract, TypeScript identifiers identical to the wire names
10
+ * (the `FunctionRecord.side_effects` precedent from src/models.ts and
11
+ * src/signals/types.ts). Entities are immutable value records:
12
+ * `readonly` fields, never mutated after construction (convention pack
13
+ * AP-004).
14
+ *
15
+ * Serialization enforces the same Constitution Principle I rules as the
16
+ * models.ts and signals/types.ts serializers, rather than trusting
17
+ * call-site discipline — fail loud, never emit invalid protocol data:
18
+ *
19
+ * - `assertion_type` membership in the closed five-value kind set
20
+ * (Gaze's assertion-type set — never empty, never `null`).
21
+ * - `side_effect_type` CANONICAL membership through `resolveSideEffectType`
22
+ * — a canonical name passes, anything else throws. This is the one
23
+ * deliberate divergence from `serializeSignal`, which RESOLVES an
24
+ * alias input to its canonical target (aliases are legitimate detector
25
+ * spellings there). Here an alias is a construction-time bug that must
26
+ * not reach the wire (data-model Section 2; spec FR-001's "canonical
27
+ * type membership"): inference constructs canonical-typed values
28
+ * directly, so an alias spelling can only mean a broken construction
29
+ * path. Both routes go through the same resolver oracle — the
30
+ * mechanism is shared, the contract is stricter here.
31
+ * - `confidence` an integer in [0, 100].
32
+ * - Every string field type-checked (`test_function` possibly empty —
33
+ * non-static titles — but always a string).
34
+ *
35
+ * No protocol method consumes these records yet — by design: the
36
+ * collection, pairing, assertion, and inference stages land in later
37
+ * tasks of this feature (US1–US4), all emitting `MappingRow` values
38
+ * through this one shape. Defining it once here is what keeps every
39
+ * stage wire-shaped instead of inventing per-module ad-hoc structures.
40
+ */
41
+ /**
42
+ * The closed assertion-kind vocabulary (FR-001/FR-008; data-model.md
43
+ * Section 3): exactly Gaze's assertion-type set — the porting contract's
44
+ * `docs/porting/taxonomy-reference.md` § Assertion Types and the
45
+ * `assertion_type` enum of Gaze's JSON report schema. Never empty: Gaze
46
+ * counts a row toward assertion-detection confidence only when its type
47
+ * is non-empty, and its Go-native detector routes unknown forms to
48
+ * `custom` (amended by OpenSpec change `align-assertion-types`).
49
+ */
50
+ export type AssertionKind = "equality" | "error_check" | "nil_check" | "diff_check" | "custom";
51
+ /**
52
+ * One test-to-assertion mapping row (FR-001; data-model.md Section 2).
53
+ *
54
+ * `side_effect_type` must be canonical: the inference layer constructs
55
+ * canonical-typed values through the taxonomy directly, and
56
+ * `serializeMappingRow` enforces canonical membership again as defense
57
+ * in depth — aliases never reach the wire.
58
+ */
59
+ export interface MappingRow {
60
+ /**
61
+ * The describe-qualified test title (data-model Section 5.1): enclosing
62
+ * describe titles joined `" > "`, then the test title. Possibly empty —
63
+ * non-static titles collect as `""` — but always a string.
64
+ */
65
+ readonly test_function: string;
66
+ /** Root-relative POSIX path of the test file. */
67
+ readonly test_file: string;
68
+ /** `"<relPath>:<line>"` — the expect/assert call's 1-based line; no column. */
69
+ readonly assertion_location: string;
70
+ /** The classified kind (Section 4's normative table). */
71
+ readonly assertion_type: AssertionKind;
72
+ /** The target record's declared name. */
73
+ readonly target_function: string;
74
+ /** `derivePackage(targetRecord.relPath)` — the dotted module path. */
75
+ readonly target_package: string;
76
+ /** One of the 48 canonical taxonomy names — aliases never emitted. */
77
+ readonly side_effect_type: SideEffectType;
78
+ /** Integer in [0, 100] — the pairing strategy's fixed value (90/70/80/75). */
79
+ readonly confidence: number;
80
+ }
81
+ /**
82
+ * The `test_mapping` result shape (FR-013; data-model.md Section 2): a
83
+ * single `mappings` key holding the wire rows — exactly one key, with an
84
+ * empty analysis a `{"mappings": []}` success rather than an error
85
+ * (US1-8).
86
+ *
87
+ * Ordering is the emitter's responsibility (the pipeline, FR-013): the
88
+ * stable key `(test_file, test_function, target_package, target_function,
89
+ * assertion line, assertion character)`, UTF-16 code-unit comparison for
90
+ * strings and numeric for line/character, with the deterministic
91
+ * AST-walk collection order as the stable-sort final tie-break.
92
+ *
93
+ * The pin is load-bearing end to end: the pipeline entry
94
+ * (src/quality/pipeline.ts) and the server handler construct their
95
+ * result against this interface, so the wire shape is compile-time
96
+ * enforced rather than merely declared (the ClassifySignalsResult
97
+ * precedent).
98
+ */
99
+ export interface TestMappingResult {
100
+ /** The rows in FR-013's stable-key order; `[]` for empty inputs — never an error. */
101
+ readonly mappings: readonly MappingRow[];
102
+ }
103
+ /**
104
+ * Serializes a `MappingRow` to its wire shape (FR-001): all eight fields
105
+ * are always present, emitted in the wire order data-model Section 2's
106
+ * field table lists.
107
+ *
108
+ * The return is typed `MappingRow` — the validated wire-shaped value —
109
+ * so the pipeline's payload and the server handler's `TestMappingResult`
110
+ * wrapper are compile-time pinned to this shape (FR-013's wire contract,
111
+ * enforced rather than asserted).
112
+ *
113
+ * Validation fails loud (Constitution Principle I): `assertion_type`
114
+ * outside the closed five-value kind set, a `side_effect_type` that is
115
+ * not a canonical taxonomy name (aliases included — they are
116
+ * construction-time bugs here, unlike `serializeSignal`'s resolve
117
+ * behavior), a `confidence` that is not an integer in [0, 100], or a
118
+ * non-string value in any string field. These are programming errors in
119
+ * the mapping pipeline, not runtime conditions to absorb.
120
+ *
121
+ * @param row The mapping row to serialize.
122
+ * @returns The validated wire-shaped `MappingRow`: the eight fields in
123
+ * wire order.
124
+ * @throws Error when any field fails its closed-set, canonical-membership,
125
+ * integer-bound, or string-type check.
126
+ */
127
+ export declare function serializeMappingRow(row: MappingRow): MappingRow;
@@ -0,0 +1,92 @@
1
+ import { resolveSideEffectType } from "../taxonomy.js";
2
+ /**
3
+ * The five closed kind values — the serializer's membership set. A `Set`
4
+ * (like models.ts's `CLASSIFICATION_LABELS` and signals/types.ts's
5
+ * `SIGNAL_SOURCES`) so lookups consult own data only, never the
6
+ * prototype chain. Constructed with the `AssertionKind` element type so
7
+ * a misspelled member is a compile error.
8
+ */
9
+ const ASSERTION_KINDS = new Set([
10
+ "equality",
11
+ "error_check",
12
+ "nil_check",
13
+ "diff_check",
14
+ "custom",
15
+ ]);
16
+ /**
17
+ * Fail-loud guard for a required string field: throws when `value` is not
18
+ * a string (Constitution Principle I — invalid record content never
19
+ * reaches the wire). The field is named in the message for actionable
20
+ * diagnostics.
21
+ *
22
+ * A module-private twin of models.ts's and signals/types.ts's guards
23
+ * rather than a shared export: the serializers keep their validation
24
+ * helpers private (the house pattern), and this module's scope is the
25
+ * mapping row alone.
26
+ *
27
+ * @param value The field value to type-check.
28
+ * @param field Human-readable field description for the error message.
29
+ */
30
+ function requireString(value, field) {
31
+ if (typeof value !== "string") {
32
+ throw new Error(`Invalid ${field}: expected a string, got ${typeof value}`);
33
+ }
34
+ }
35
+ /**
36
+ * Serializes a `MappingRow` to its wire shape (FR-001): all eight fields
37
+ * are always present, emitted in the wire order data-model Section 2's
38
+ * field table lists.
39
+ *
40
+ * The return is typed `MappingRow` — the validated wire-shaped value —
41
+ * so the pipeline's payload and the server handler's `TestMappingResult`
42
+ * wrapper are compile-time pinned to this shape (FR-013's wire contract,
43
+ * enforced rather than asserted).
44
+ *
45
+ * Validation fails loud (Constitution Principle I): `assertion_type`
46
+ * outside the closed five-value kind set, a `side_effect_type` that is
47
+ * not a canonical taxonomy name (aliases included — they are
48
+ * construction-time bugs here, unlike `serializeSignal`'s resolve
49
+ * behavior), a `confidence` that is not an integer in [0, 100], or a
50
+ * non-string value in any string field. These are programming errors in
51
+ * the mapping pipeline, not runtime conditions to absorb.
52
+ *
53
+ * @param row The mapping row to serialize.
54
+ * @returns The validated wire-shaped `MappingRow`: the eight fields in
55
+ * wire order.
56
+ * @throws Error when any field fails its closed-set, canonical-membership,
57
+ * integer-bound, or string-type check.
58
+ */
59
+ export function serializeMappingRow(row) {
60
+ requireString(row.test_function, "mapping test_function");
61
+ requireString(row.test_file, "mapping test_file");
62
+ requireString(row.assertion_location, "mapping assertion_location");
63
+ requireString(row.target_function, "mapping target_function");
64
+ requireString(row.target_package, "mapping target_package");
65
+ if (!ASSERTION_KINDS.has(row.assertion_type)) {
66
+ throw new Error(`Invalid assertion type: ${row.assertion_type}`);
67
+ }
68
+ // Canonical membership through the shared resolver oracle: a canonical
69
+ // name resolves to itself and passes; an alias resolves to a DIFFERENT
70
+ // canonical target and fails; an unknown string resolves to undefined
71
+ // and fails. Aliases are construction-time bugs that must not reach the
72
+ // wire (data-model Section 2) — the deliberate divergence from
73
+ // serializeSignal's resolve-and-emit behavior, which stays correct for
74
+ // signals because detector spellings there may legitimately be aliases.
75
+ if (resolveSideEffectType(row.side_effect_type) !== row.side_effect_type) {
76
+ throw new Error(`Invalid side effect type: ${row.side_effect_type}`);
77
+ }
78
+ if (!Number.isInteger(row.confidence) || row.confidence < 0 || row.confidence > 100) {
79
+ throw new Error(`Invalid mapping confidence: ${row.confidence} (must be an integer in the range 0-100)`);
80
+ }
81
+ return {
82
+ test_function: row.test_function,
83
+ test_file: row.test_file,
84
+ assertion_location: row.assertion_location,
85
+ assertion_type: row.assertion_type,
86
+ target_function: row.target_function,
87
+ target_package: row.target_package,
88
+ side_effect_type: row.side_effect_type,
89
+ confidence: row.confidence,
90
+ };
91
+ }
92
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,107 @@
1
+ import type { Writable } from "node:stream";
2
+ /**
3
+ * Shared safe file reader for every file-touching analysis (FR-017, FR-018;
4
+ * research R4, R5 — Constitution Principle V).
5
+ *
6
+ * Analyzed trees are untrusted input, so no caller reads files under its own
7
+ * discipline: all reading funnels through `readBounded` — or, for callers
8
+ * bound to a synchronous contract (the TypeScript `CompilerHost.readFile`
9
+ * signature), through `readBoundedSync` — one guarded sequence whose order
10
+ * is load-bearing:
11
+ *
12
+ * 1. **Containment** (FR-018, research R5) runs before any filesystem
13
+ * access — the candidate is the resolved root joined with the walk-built
14
+ * relative path, and `path.relative(root, candidate)` must stay
15
+ * non-absolute and must not begin with `..`, or the path is rejected
16
+ * unread. The walk can never produce an escape (walked segments contain
17
+ * no `..` and symlinks are never followed); the independent check is
18
+ * defense in depth protecting future callers that receive paths from
19
+ * other sources (research R5).
20
+ * 2. **`lstat` — never `stat`** so the final symlink is not followed: a
21
+ * symlink is skipped as itself, and non-regular files (FIFOs, devices,
22
+ * sockets) are skipped before `open` is attempted. The pre-open
23
+ * regular-file check is the FIFO DoS defense — opening a FIFO for
24
+ * reading blocks until a writer appears (research R4).
25
+ * 3. **Size cap**: the lstat size is checked against `MAX_FILE_BYTES`
26
+ * before open, so an oversized file is never opened at all.
27
+ * 4. **Bounded read**: only then does the file open, and the read length is
28
+ * clamped by the caller's `budget`.
29
+ *
30
+ * Every skip writes exactly one diagnostic line — `reading-stone: skipping
31
+ * <relPath>: <reason>` — to the injected stderr sink and resolves `null`;
32
+ * a skip never throws and never aborts the enclosing request, and stdout is
33
+ * never touched (it is reserved for JSON-RPC responses, FR-017). Reason
34
+ * strings are short and stable, so stderr output is deterministic for the
35
+ * same tree (Constitution Principle I).
36
+ *
37
+ * `readBoundedSync` runs the same sequence minus containment: it receives
38
+ * an absolute path from the caller (the compiler host resolves paths the
39
+ * analyzer never walked, including the `typescript` package's own lib
40
+ * files), so root containment stays the caller's decision. Its skips
41
+ * return `undefined` — the `CompilerHost.readFile` absent-file signal —
42
+ * after the same one-line diagnostic, with the absolute path echoed
43
+ * verbatim.
44
+ */
45
+ /**
46
+ * The hard per-file byte cap (FR-017): a candidate whose lstat size exceeds
47
+ * 16 MiB is skipped before it is ever opened. Fixed, not
48
+ * caller-configurable — the bound mirrors the reference analyzer's
49
+ * `MAX_FILE_BYTES` and the server's `MAX_LINE_CHARS` precedent; no single
50
+ * file may dominate the analyzer's memory.
51
+ */
52
+ export declare const MAX_FILE_BYTES: number;
53
+ /**
54
+ * Reads at most `budget` bytes of one candidate file beneath the analysis
55
+ * root, running the full safe-read sequence (FR-017, FR-018; research R4,
56
+ * R5): containment, `lstat`, regular-file check, size cap, open,
57
+ * budget-clamped read, strict UTF-8 decode.
58
+ *
59
+ * The caller (the tree walk, or a later analysis method) supplies paths
60
+ * relative to a resolved root; `readBounded` never reads a path that
61
+ * escapes it. `MAX_FILE_BYTES` is the hard cap on the lstat size; `budget`
62
+ * additionally clamps how many bytes are actually read (a 64 KiB marker
63
+ * prefix, a whole-file 16 MiB read). A non-positive budget reads nothing
64
+ * and resolves to the empty string. A budget that splits a multi-byte
65
+ * UTF-8 sequence yields a `decode error` skip — the truncated prefix is
66
+ * not valid standalone UTF-8, and signaling the loss beats silently
67
+ * dropping the partial character.
68
+ *
69
+ * Every skip resolves `null` after writing exactly one diagnostic line to
70
+ * `stderr`; `readBounded` never throws for skip conditions and never aborts
71
+ * the enclosing request (FR-017).
72
+ *
73
+ * @param root Resolved absolute analysis root; containment is enforced
74
+ * against this root (the caller resolves a symlinked root once at the
75
+ * boundary, before walking).
76
+ * @param relPath Walk-built root-relative POSIX path, echoed verbatim in
77
+ * diagnostics.
78
+ * @param budget Maximum number of bytes to read from the file.
79
+ * @param stderr Injected diagnostic sink (Testability principle — the
80
+ * Server passes its own `stderr`); stdout is never touched.
81
+ * @returns The decoded file content, or `null` when the file was skipped.
82
+ */
83
+ export declare function readBounded(root: string, relPath: string, budget: number, stderr: Writable): Promise<string | null>;
84
+ /**
85
+ * The synchronous bounded read for callers bound to a sync contract — the
86
+ * TypeScript `CompilerHost.readFile` signature (research R1). The guard
87
+ * sequence is `readBounded`'s minus containment (see the module header):
88
+ * the caller hands back compiler-resolved absolute paths, so root
89
+ * containment stays the caller's decision.
90
+ *
91
+ * In order: `lstatSync` regular-file check (FIFOs, devices, sockets, and
92
+ * symlinks skipped before the open — the FIFO DoS defense, research R4),
93
+ * `MAX_FILE_BYTES` size cap checked before open, bounded synchronous
94
+ * read, strict UTF-8 decode through the shared module decoder.
95
+ *
96
+ * Every skip returns `undefined` after writing exactly one diagnostic
97
+ * line to `stderr`; `readBoundedSync` never throws for skip conditions.
98
+ * `undefined` — not `null` — matches the `CompilerHost.readFile`
99
+ * absent-file signal the caller serves.
100
+ *
101
+ * @param absPath Absolute candidate path, echoed verbatim in diagnostics.
102
+ * @param stderr Injected diagnostic sink (Testability principle — the
103
+ * compiler host passes the server's own `stderr`); stdout is never touched.
104
+ * @returns The decoded file content, or `undefined` when the file was
105
+ * skipped.
106
+ */
107
+ export declare function readBoundedSync(absPath: string, stderr: Writable): string | undefined;