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,75 @@
1
+ /**
2
+ * Shared internal primitives consumed across the analysis modules (the
3
+ * review council's DRY finding, dispatch 44e85014): the `(file, line,
4
+ * name)` total order every wire payload is sorted by, and the lexical
5
+ * path-containment test every root-relative spelling flows through.
6
+ *
7
+ * A dedicated leaf module — `node:path` is its only import — so every
8
+ * consumer (extract, detector, complexity, coverage, program) can share
9
+ * these without an import cycle or a layering inversion: extract.ts as
10
+ * the canonical site was considered and rejected because program.ts (a
11
+ * module extract itself depends on) and coverage.ts would then import
12
+ * from their own consumer or an unrelated pipeline stage for a path
13
+ * primitive. Internal, not protocol-visible: `src/index.ts` deliberately
14
+ * does not re-export this module (convention pack AP-001's explicit
15
+ * barrel of the public surface only).
16
+ */
17
+ /**
18
+ * The record identity the `(file, line, name)` order sorts by: the
19
+ * root-relative POSIX file path, the 1-based declaration line, and the
20
+ * declared name. `FunctionRecord` and `ComplexityEntry` carry these
21
+ * fields under exactly these names; `ExtractionRecord` spells the file
22
+ * field `relPath` and adapts at its comparator.
23
+ */
24
+ export interface FileLineName {
25
+ /** Root-relative POSIX path of the declaring file. */
26
+ readonly file: string;
27
+ /** 1-based line of the function declaration. */
28
+ readonly line: number;
29
+ /** The function's declared name. */
30
+ readonly name: string;
31
+ }
32
+ /**
33
+ * The FR-008/FR-020 total order: `(file, line, name)` with codepoint
34
+ * comparison for the string keys — the platform-default string comparison
35
+ * the wire contract's golden tests pin — numeric line ordering between
36
+ * them, and `0` on full-key ties so the platform-default stable sort
37
+ * resolves them by emission (source) order — the getter-before-setter
38
+ * resolution for a one-line accessor pair.
39
+ *
40
+ * @param a Left record.
41
+ * @param b Right record.
42
+ * @returns The three-key comparison result.
43
+ */
44
+ export declare function compareFileLineName(a: FileLineName, b: FileLineName): number;
45
+ /**
46
+ * Lexical containment: `candidate`'s root-relative POSIX spelling under
47
+ * `base`, or `null` when the candidate is not strictly inside. The
48
+ * "begins with `..`" test is deliberately literal (the safeio precedent):
49
+ * as defense in depth it errs toward rejecting, so even a pathological
50
+ * in-base sibling such as `..hidden.ts` is refused rather than risk an
51
+ * escape.
52
+ *
53
+ * @param base Containing directory (an analysis root or library root).
54
+ * @param candidate Absolute path to test.
55
+ * @returns The root-relative POSIX path, or `null` when not under `base`.
56
+ */
57
+ export declare function relativeUnderBase(base: string, candidate: string): string | null;
58
+ /**
59
+ * The mapping-stage AST walk depth budget (spec 004 plan.md's Scale/Scope
60
+ * pin; the `extract.ts` `AST_DEPTH_BUDGET` shape — fixed, not
61
+ * caller-configurable): far beyond real-world suite nesting, low enough
62
+ * that the recursive test-arm walks (collection, assertion detection,
63
+ * and the strategy/provenance walks to come) cannot exhaust the native
64
+ * stack on adversarial input. Iteration-2 review fix F2: the mapping
65
+ * pipeline does NOT inherit `prepareAnalysis`'s depth budget — extract's
66
+ * `AST_DEPTH_BUDGET` guards the extraction walk only — so every
67
+ * mapping-stage walk owns a bound, and this is the shared one.
68
+ *
69
+ * Deliberately independent of extract's own module-private constant:
70
+ * each guards a different walk with a different per-frame cost, and
71
+ * coupling them would let one walk's bound change the other's behavior;
72
+ * the shared SHAPE (fixed bound, sentinel, per-unit skip, one
73
+ * diagnostic), not the shared constant, is the contract.
74
+ */
75
+ export declare const MAPPING_WALK_DEPTH_BUDGET = 2000;
@@ -0,0 +1,63 @@
1
+ import { isAbsolute, relative, sep } from "node:path";
2
+ /**
3
+ * The FR-008/FR-020 total order: `(file, line, name)` with codepoint
4
+ * comparison for the string keys — the platform-default string comparison
5
+ * the wire contract's golden tests pin — numeric line ordering between
6
+ * them, and `0` on full-key ties so the platform-default stable sort
7
+ * resolves them by emission (source) order — the getter-before-setter
8
+ * resolution for a one-line accessor pair.
9
+ *
10
+ * @param a Left record.
11
+ * @param b Right record.
12
+ * @returns The three-key comparison result.
13
+ */
14
+ export function compareFileLineName(a, b) {
15
+ if (a.file !== b.file) {
16
+ return a.file < b.file ? -1 : 1;
17
+ }
18
+ if (a.line !== b.line) {
19
+ return a.line - b.line;
20
+ }
21
+ if (a.name !== b.name) {
22
+ return a.name < b.name ? -1 : 1;
23
+ }
24
+ return 0;
25
+ }
26
+ /**
27
+ * Lexical containment: `candidate`'s root-relative POSIX spelling under
28
+ * `base`, or `null` when the candidate is not strictly inside. The
29
+ * "begins with `..`" test is deliberately literal (the safeio precedent):
30
+ * as defense in depth it errs toward rejecting, so even a pathological
31
+ * in-base sibling such as `..hidden.ts` is refused rather than risk an
32
+ * escape.
33
+ *
34
+ * @param base Containing directory (an analysis root or library root).
35
+ * @param candidate Absolute path to test.
36
+ * @returns The root-relative POSIX path, or `null` when not under `base`.
37
+ */
38
+ export function relativeUnderBase(base, candidate) {
39
+ const rel = relative(base, candidate);
40
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) {
41
+ return null;
42
+ }
43
+ return rel.split(sep).join("/");
44
+ }
45
+ /**
46
+ * The mapping-stage AST walk depth budget (spec 004 plan.md's Scale/Scope
47
+ * pin; the `extract.ts` `AST_DEPTH_BUDGET` shape — fixed, not
48
+ * caller-configurable): far beyond real-world suite nesting, low enough
49
+ * that the recursive test-arm walks (collection, assertion detection,
50
+ * and the strategy/provenance walks to come) cannot exhaust the native
51
+ * stack on adversarial input. Iteration-2 review fix F2: the mapping
52
+ * pipeline does NOT inherit `prepareAnalysis`'s depth budget — extract's
53
+ * `AST_DEPTH_BUDGET` guards the extraction walk only — so every
54
+ * mapping-stage walk owns a bound, and this is the shared one.
55
+ *
56
+ * Deliberately independent of extract's own module-private constant:
57
+ * each guards a different walk with a different per-frame cost, and
58
+ * coupling them would let one walk's bound change the other's behavior;
59
+ * the shared SHAPE (fixed bound, sentinel, per-unit skip, one
60
+ * diagnostic), not the shared constant, is the contract.
61
+ */
62
+ export const MAPPING_WALK_DEPTH_BUDGET = 2000;
63
+ //# sourceMappingURL=internal.js.map
package/dist/main.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ import type { Readable, Writable } from "node:stream";
3
+ export interface Io {
4
+ stdin: Readable;
5
+ stdout: Writable;
6
+ stderr: Writable;
7
+ }
8
+ export declare function main(argv?: string[], io?: Io): Promise<number>;
package/dist/main.js ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync } from "node:fs";
3
+ import { pathToFileURL } from "node:url";
4
+ import { Server } from "./server.js";
5
+ export async function main(argv = process.argv.slice(2), io) {
6
+ const stdin = io?.stdin ?? process.stdin;
7
+ const stdout = io?.stdout ?? process.stdout;
8
+ const stderr = io?.stderr ?? process.stderr;
9
+ if (argv.length !== 1 || argv[0] !== "--stdio") {
10
+ stderr.write("reading-stone --stdio\n");
11
+ return 2;
12
+ }
13
+ if (stdout === process.stdout) {
14
+ stdout.on("error", (error) => {
15
+ if (error.code === "EPIPE") {
16
+ stdin.destroy();
17
+ }
18
+ });
19
+ }
20
+ await new Server(stdin, stdout, stderr).run();
21
+ return 0;
22
+ }
23
+ function isMainModule() {
24
+ if (process.argv[1] === undefined) {
25
+ return false;
26
+ }
27
+ try {
28
+ return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ if (isMainModule()) {
35
+ void main().then((code) => {
36
+ process.exitCode = code;
37
+ });
38
+ }
39
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1,185 @@
1
+ import { type SideEffectType } from "./taxonomy.js";
2
+ /**
3
+ * Shared record models for analysis results (FR-013–FR-016; research R10)
4
+ * — the immutable value records every later analysis method (side-effect
5
+ * detection, complexity, coverage) constructs, the serializers that turn
6
+ * them into wire-shaped JSON, and the package-name derivation that
7
+ * populates `FunctionRecord.package`.
8
+ *
9
+ * No protocol method consumes these records yet — by design: `analyze`
10
+ * lands in a later issue (spec US2). Defining the shapes once here is what
11
+ * keeps every consumer protocol-shaped instead of inventing per-module
12
+ * ad-hoc structures.
13
+ *
14
+ * Serialization enforces two Constitution Principle I rules rather than
15
+ * trusting call-site discipline:
16
+ *
17
+ * - Omit-unset-optionals: an optional field that is absent or explicitly
18
+ * `undefined` is omitted from the serialized object — never emitted as
19
+ * `null` (the protocol forbids `null` for omitted fields; US2 scenario 3).
20
+ * - Fail loud: invalid record content — a non-canonical side-effect type, a
21
+ * non-string description, an out-of-range confidence — throws instead of
22
+ * emitting invalid protocol data. A malformed record is an analyzer bug;
23
+ * silently shipping it would corrupt every score Gaze computes from it.
24
+ *
25
+ * Naming follows the wire/identifier split `DiscoveryResult` documents in
26
+ * discovery.ts: wire-format fields are snake_case per the protocol payload
27
+ * contract (`side_effects`), while TypeScript identifiers stay camelCase
28
+ * (convention pack CS-006). Entities are immutable value records —
29
+ * `readonly` fields, never mutated after construction (convention pack
30
+ * AP-004).
31
+ */
32
+ /**
33
+ * The classification of an effect (FR-014): how confidently the analyzer
34
+ * believes the effect belongs to the function's contract.
35
+ *
36
+ * `label` distinguishes the three protocol outcomes — the effect is
37
+ * required by the function's contract (`contractual`), happens as a
38
+ * byproduct (`incidental`), or cannot be determined with confidence
39
+ * (`ambiguous`). Reporting ambiguity instead of dropping the effect is
40
+ * what Constitution Principle II demands: an ambiguous classification is
41
+ * a truthful signal; a silent omission is a false negative.
42
+ *
43
+ * `confidence` is an integer percentage 0–100. Out-of-range or fractional
44
+ * values are programming errors: `serializeClassification` throws rather
45
+ * than emit them (Constitution Principle I).
46
+ */
47
+ export interface Classification {
48
+ /** One of the three protocol labels; membership is validated at serialization. */
49
+ readonly label: "contractual" | "incidental" | "ambiguous";
50
+ /** Integer confidence percentage, 0–100 inclusive. */
51
+ readonly confidence: number;
52
+ }
53
+ /**
54
+ * A single observable side effect attributed to a function (FR-013).
55
+ *
56
+ * `type` must be a canonical `SideEffectType`: detection code resolves any
57
+ * alias spelling through `resolveSideEffectType` before constructing an
58
+ * `Effect`, and `serializeEffect` enforces canonical membership again as
59
+ * defense in depth.
60
+ *
61
+ * Optional fields follow the omit-unset-optionals rule: absent (or
62
+ * explicitly `undefined`) at construction, omitted from serialization —
63
+ * never `null`.
64
+ */
65
+ export interface Effect {
66
+ /** The canonical side-effect type — the only vocabulary reportable on the wire. */
67
+ readonly type: SideEffectType;
68
+ /** Human-readable explanation of the observed effect. */
69
+ readonly description: string;
70
+ /** `"file:line:col"` location relative to the analysis root. */
71
+ readonly location?: string;
72
+ /** The attribute, parameter, or exception involved. */
73
+ readonly target?: string;
74
+ /** Opaque metadata passed through to Gaze without interpretation. */
75
+ readonly detail?: Record<string, unknown>;
76
+ /** The contractual/incidental classification, when one was determined. */
77
+ readonly classification?: Classification;
78
+ }
79
+ /**
80
+ * A function observed in the analyzed project (FR-015) — the unit every
81
+ * analysis result is attributed to.
82
+ *
83
+ * Field names mirror the wire payload exactly: `side_effects` is snake_case
84
+ * per the protocol contract, the same documented exception `DiscoveryResult`
85
+ * uses in discovery.ts; every other name is identical in both worlds.
86
+ * `file` is the path relative to `root_path` with POSIX separators, `line`
87
+ * is the 1-based declaration line, and `package` is the dotted module path
88
+ * `derivePackage` produces from `file`.
89
+ */
90
+ export interface FunctionRecord {
91
+ /** The function's declared name. */
92
+ readonly name: string;
93
+ /** Dotted module path derived by `derivePackage` from `file`. */
94
+ readonly package: string;
95
+ /** Root-relative POSIX path of the declaring file. */
96
+ readonly file: string;
97
+ /** 1-based line of the function declaration. */
98
+ readonly line: number;
99
+ /** The effects attributed to the function; serialized as the `side_effects` array. */
100
+ readonly side_effects: readonly Effect[];
101
+ }
102
+ /**
103
+ * Serializes a `Classification` to its wire shape (FR-014): both fields
104
+ * are always present — `{ label, confidence }`.
105
+ *
106
+ * Validation fails loud (Constitution Principle I): a `label` outside the
107
+ * three protocol literals, or a `confidence` that is not an integer within
108
+ * 0–100, throws rather than emits invalid protocol data. These are
109
+ * programming errors in detection code, not runtime conditions to absorb.
110
+ *
111
+ * @param classification The classification to serialize.
112
+ * @returns A JSON-ready object with `label` and `confidence`.
113
+ * @throws Error when `label` is not one of the three protocol literals, or
114
+ * `confidence` is not an integer in 0–100.
115
+ */
116
+ export declare function serializeClassification(classification: Classification): Record<string, unknown>;
117
+ /**
118
+ * Serializes an `Effect` to its wire shape (FR-013): required `type` and
119
+ * `description` are always emitted; each optional field (`location`,
120
+ * `target`, `detail`, `classification`) appears only when set — omitted,
121
+ * never `null`, when absent or explicitly `undefined` (US2 scenario 3).
122
+ * `classification` serializes recursively through
123
+ * `serializeClassification`.
124
+ *
125
+ * Validation fails loud (Constitution Principle I). `type` is checked
126
+ * through the same resolver detection code uses: a canonical name passes
127
+ * through, an alias spelling that slipped past construction resolves to
128
+ * its canonical target (aliases never reach the wire), and a string that
129
+ * is neither canonical nor alias throws. `description` must be a string.
130
+ *
131
+ * @param effect The effect to serialize.
132
+ * @returns A JSON-ready object with `type` and `description`, plus each
133
+ * optional field that is set.
134
+ * @throws Error when `type` is neither a canonical side-effect type nor an
135
+ * alias, or `description` is not a string.
136
+ */
137
+ export declare function serializeEffect(effect: Effect): Record<string, unknown>;
138
+ /**
139
+ * Serializes a `FunctionRecord` to its wire shape (FR-015): `name`,
140
+ * `package`, `file`, and `line` are always emitted, and `side_effects` is
141
+ * emitted as a JSON array of `serializeEffect` outputs under its
142
+ * snake_case wire name.
143
+ *
144
+ * Validation fails loud (Constitution Principle I): `name`, `package`, and
145
+ * `file` must be strings, and `line` must be a positive (1-based)
146
+ * integer. Each effect in `side_effects` is validated by `serializeEffect`
147
+ * as it is mapped.
148
+ *
149
+ * @param record The function record to serialize.
150
+ * @returns A JSON-ready object with `name`, `package`, `file`, `line`, and
151
+ * `side_effects`.
152
+ * @throws Error when any of `name`/`package`/`file` is not a string, when
153
+ * `line` is not a positive integer, or when any effect fails
154
+ * `serializeEffect`'s validation.
155
+ */
156
+ export declare function serializeFunctionRecord(record: FunctionRecord): Record<string, unknown>;
157
+ /**
158
+ * Derives the dotted package path from a root-relative POSIX source path
159
+ * (FR-016; research R10): strip the final extension, join the remaining
160
+ * segments with dots, then drop a trailing `.index` segment — an index
161
+ * module represents its directory.
162
+ *
163
+ * Exact behavior (data-model.md table):
164
+ *
165
+ * | Input | Output |
166
+ * |-------|--------|
167
+ * | `pkg/mod.ts` | `pkg.mod` |
168
+ * | `pkg/index.ts` | `pkg` |
169
+ * | `src/deep/thing.ts` | `src.deep.thing` |
170
+ * | `index.ts` | `index` |
171
+ * | `a.b.ts` | `a.b` |
172
+ *
173
+ * A top-level `index.ts` derives to `"index"`: the join produces no dotted
174
+ * `.index` suffix to strip, mirroring the reference analyzer's top-level
175
+ * `__init__.py` handling (research R10).
176
+ *
177
+ * Path splitting uses `node:path`'s `posix` namespace deliberately: the
178
+ * input is a wire-format POSIX-separator string (as discovery produces),
179
+ * not a host-filesystem path, so parsing must not vary with the host
180
+ * platform the way the `win32`-flavored default helpers would on Windows.
181
+ *
182
+ * @param relPath Root-relative POSIX path of a source file.
183
+ * @returns The dotted module path, with a trailing `index` segment dropped.
184
+ */
185
+ export declare function derivePackage(relPath: string): string;
package/dist/models.js ADDED
@@ -0,0 +1,170 @@
1
+ import { posix } from "node:path";
2
+ import { resolveSideEffectType } from "./taxonomy.js";
3
+ /**
4
+ * The three classification labels (FR-014) — the serializer's membership
5
+ * set. A `Set` (like taxonomy's `CANONICAL_NAMES`) so lookups consult own
6
+ * data only, never the prototype chain.
7
+ */
8
+ const CLASSIFICATION_LABELS = new Set([
9
+ "contractual",
10
+ "incidental",
11
+ "ambiguous",
12
+ ]);
13
+ /**
14
+ * Fail-loud guard for a required string field: throws when `value` is not
15
+ * a string (Constitution Principle I — invalid record content never
16
+ * reaches the wire). The field is named in the message for actionable
17
+ * diagnostics.
18
+ *
19
+ * @param value The field value to type-check.
20
+ * @param field Human-readable field description for the error message.
21
+ */
22
+ function requireString(value, field) {
23
+ if (typeof value !== "string") {
24
+ throw new Error(`Invalid ${field}: expected a string, got ${typeof value}`);
25
+ }
26
+ }
27
+ /**
28
+ * Serializes a `Classification` to its wire shape (FR-014): both fields
29
+ * are always present — `{ label, confidence }`.
30
+ *
31
+ * Validation fails loud (Constitution Principle I): a `label` outside the
32
+ * three protocol literals, or a `confidence` that is not an integer within
33
+ * 0–100, throws rather than emits invalid protocol data. These are
34
+ * programming errors in detection code, not runtime conditions to absorb.
35
+ *
36
+ * @param classification The classification to serialize.
37
+ * @returns A JSON-ready object with `label` and `confidence`.
38
+ * @throws Error when `label` is not one of the three protocol literals, or
39
+ * `confidence` is not an integer in 0–100.
40
+ */
41
+ export function serializeClassification(classification) {
42
+ const { label, confidence } = classification;
43
+ if (!CLASSIFICATION_LABELS.has(label)) {
44
+ throw new Error(`Invalid classification label: ${label}`);
45
+ }
46
+ if (!Number.isInteger(confidence) || confidence < 0 || confidence > 100) {
47
+ throw new Error(`Invalid classification confidence: ${confidence} (must be an integer in the range 0-100)`);
48
+ }
49
+ return { label, confidence };
50
+ }
51
+ /**
52
+ * Serializes an `Effect` to its wire shape (FR-013): required `type` and
53
+ * `description` are always emitted; each optional field (`location`,
54
+ * `target`, `detail`, `classification`) appears only when set — omitted,
55
+ * never `null`, when absent or explicitly `undefined` (US2 scenario 3).
56
+ * `classification` serializes recursively through
57
+ * `serializeClassification`.
58
+ *
59
+ * Validation fails loud (Constitution Principle I). `type` is checked
60
+ * through the same resolver detection code uses: a canonical name passes
61
+ * through, an alias spelling that slipped past construction resolves to
62
+ * its canonical target (aliases never reach the wire), and a string that
63
+ * is neither canonical nor alias throws. `description` must be a string.
64
+ *
65
+ * @param effect The effect to serialize.
66
+ * @returns A JSON-ready object with `type` and `description`, plus each
67
+ * optional field that is set.
68
+ * @throws Error when `type` is neither a canonical side-effect type nor an
69
+ * alias, or `description` is not a string.
70
+ */
71
+ export function serializeEffect(effect) {
72
+ const type = resolveSideEffectType(effect.type);
73
+ if (type === undefined) {
74
+ throw new Error(`Invalid side effect type: ${effect.type}`);
75
+ }
76
+ requireString(effect.description, "effect description");
77
+ const serialized = {
78
+ type,
79
+ description: effect.description,
80
+ };
81
+ if (effect.location !== undefined) {
82
+ serialized.location = effect.location;
83
+ }
84
+ if (effect.target !== undefined) {
85
+ serialized.target = effect.target;
86
+ }
87
+ if (effect.detail !== undefined) {
88
+ serialized.detail = effect.detail;
89
+ }
90
+ if (effect.classification !== undefined) {
91
+ serialized.classification = serializeClassification(effect.classification);
92
+ }
93
+ return serialized;
94
+ }
95
+ /**
96
+ * Serializes a `FunctionRecord` to its wire shape (FR-015): `name`,
97
+ * `package`, `file`, and `line` are always emitted, and `side_effects` is
98
+ * emitted as a JSON array of `serializeEffect` outputs under its
99
+ * snake_case wire name.
100
+ *
101
+ * Validation fails loud (Constitution Principle I): `name`, `package`, and
102
+ * `file` must be strings, and `line` must be a positive (1-based)
103
+ * integer. Each effect in `side_effects` is validated by `serializeEffect`
104
+ * as it is mapped.
105
+ *
106
+ * @param record The function record to serialize.
107
+ * @returns A JSON-ready object with `name`, `package`, `file`, `line`, and
108
+ * `side_effects`.
109
+ * @throws Error when any of `name`/`package`/`file` is not a string, when
110
+ * `line` is not a positive integer, or when any effect fails
111
+ * `serializeEffect`'s validation.
112
+ */
113
+ export function serializeFunctionRecord(record) {
114
+ requireString(record.name, "function record name");
115
+ requireString(record.package, "function record package");
116
+ requireString(record.file, "function record file");
117
+ if (!Number.isInteger(record.line) || record.line < 1) {
118
+ throw new Error(`Invalid function record line: ${record.line} (must be a positive integer)`);
119
+ }
120
+ return {
121
+ name: record.name,
122
+ package: record.package,
123
+ file: record.file,
124
+ line: record.line,
125
+ side_effects: record.side_effects.map((effect) => serializeEffect(effect)),
126
+ };
127
+ }
128
+ /**
129
+ * Derives the dotted package path from a root-relative POSIX source path
130
+ * (FR-016; research R10): strip the final extension, join the remaining
131
+ * segments with dots, then drop a trailing `.index` segment — an index
132
+ * module represents its directory.
133
+ *
134
+ * Exact behavior (data-model.md table):
135
+ *
136
+ * | Input | Output |
137
+ * |-------|--------|
138
+ * | `pkg/mod.ts` | `pkg.mod` |
139
+ * | `pkg/index.ts` | `pkg` |
140
+ * | `src/deep/thing.ts` | `src.deep.thing` |
141
+ * | `index.ts` | `index` |
142
+ * | `a.b.ts` | `a.b` |
143
+ *
144
+ * A top-level `index.ts` derives to `"index"`: the join produces no dotted
145
+ * `.index` suffix to strip, mirroring the reference analyzer's top-level
146
+ * `__init__.py` handling (research R10).
147
+ *
148
+ * Path splitting uses `node:path`'s `posix` namespace deliberately: the
149
+ * input is a wire-format POSIX-separator string (as discovery produces),
150
+ * not a host-filesystem path, so parsing must not vary with the host
151
+ * platform the way the `win32`-flavored default helpers would on Windows.
152
+ *
153
+ * @param relPath Root-relative POSIX path of a source file.
154
+ * @returns The dotted module path, with a trailing `index` segment dropped.
155
+ */
156
+ export function derivePackage(relPath) {
157
+ // parse() splits the basename into stem + final extension with correct
158
+ // leading-dot handling (".gitignore" has no extension), and reports "."
159
+ // as the directory of a top-level file.
160
+ const { dir, name } = posix.parse(relPath);
161
+ const segments = dir === "" || dir === "." ? [name] : [...dir.split("/"), name];
162
+ const dotted = segments.join(".");
163
+ // Drop one trailing ".index" segment; a bare top-level "index" has no
164
+ // preceding dot, so it survives (the documented edge case).
165
+ if (dotted.endsWith(".index")) {
166
+ return dotted.slice(0, -".index".length);
167
+ }
168
+ return dotted;
169
+ }
170
+ //# sourceMappingURL=models.js.map