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/safeio.js ADDED
@@ -0,0 +1,314 @@
1
+ import { closeSync, lstatSync, openSync, readSync } from "node:fs";
2
+ import { lstat, open } from "node:fs/promises";
3
+ import { isAbsolute, join, relative } from "node:path";
4
+ import { TextDecoder } from "node:util";
5
+ /**
6
+ * Shared safe file reader for every file-touching analysis (FR-017, FR-018;
7
+ * research R4, R5 — Constitution Principle V).
8
+ *
9
+ * Analyzed trees are untrusted input, so no caller reads files under its own
10
+ * discipline: all reading funnels through `readBounded` — or, for callers
11
+ * bound to a synchronous contract (the TypeScript `CompilerHost.readFile`
12
+ * signature), through `readBoundedSync` — one guarded sequence whose order
13
+ * is load-bearing:
14
+ *
15
+ * 1. **Containment** (FR-018, research R5) runs before any filesystem
16
+ * access — the candidate is the resolved root joined with the walk-built
17
+ * relative path, and `path.relative(root, candidate)` must stay
18
+ * non-absolute and must not begin with `..`, or the path is rejected
19
+ * unread. The walk can never produce an escape (walked segments contain
20
+ * no `..` and symlinks are never followed); the independent check is
21
+ * defense in depth protecting future callers that receive paths from
22
+ * other sources (research R5).
23
+ * 2. **`lstat` — never `stat`** so the final symlink is not followed: a
24
+ * symlink is skipped as itself, and non-regular files (FIFOs, devices,
25
+ * sockets) are skipped before `open` is attempted. The pre-open
26
+ * regular-file check is the FIFO DoS defense — opening a FIFO for
27
+ * reading blocks until a writer appears (research R4).
28
+ * 3. **Size cap**: the lstat size is checked against `MAX_FILE_BYTES`
29
+ * before open, so an oversized file is never opened at all.
30
+ * 4. **Bounded read**: only then does the file open, and the read length is
31
+ * clamped by the caller's `budget`.
32
+ *
33
+ * Every skip writes exactly one diagnostic line — `reading-stone: skipping
34
+ * <relPath>: <reason>` — to the injected stderr sink and resolves `null`;
35
+ * a skip never throws and never aborts the enclosing request, and stdout is
36
+ * never touched (it is reserved for JSON-RPC responses, FR-017). Reason
37
+ * strings are short and stable, so stderr output is deterministic for the
38
+ * same tree (Constitution Principle I).
39
+ *
40
+ * `readBoundedSync` runs the same sequence minus containment: it receives
41
+ * an absolute path from the caller (the compiler host resolves paths the
42
+ * analyzer never walked, including the `typescript` package's own lib
43
+ * files), so root containment stays the caller's decision. Its skips
44
+ * return `undefined` — the `CompilerHost.readFile` absent-file signal —
45
+ * after the same one-line diagnostic, with the absolute path echoed
46
+ * verbatim.
47
+ */
48
+ /**
49
+ * The hard per-file byte cap (FR-017): a candidate whose lstat size exceeds
50
+ * 16 MiB is skipped before it is ever opened. Fixed, not
51
+ * caller-configurable — the bound mirrors the reference analyzer's
52
+ * `MAX_FILE_BYTES` and the server's `MAX_LINE_CHARS` precedent; no single
53
+ * file may dominate the analyzer's memory.
54
+ */
55
+ export const MAX_FILE_BYTES = 16 * 1024 * 1024;
56
+ /**
57
+ * Strict UTF-8 decoder shared by every read. `fatal: true` turns invalid
58
+ * byte sequences into a thrown `TypeError`, which `readBounded` maps to a
59
+ * `decode error` skip — never the silent U+FFFD replacement that
60
+ * `Buffer.prototype.toString` would apply (a mojibake source file must be
61
+ * signaled, not silently mangled). One-shot `decode()` calls carry no state
62
+ * between invocations, so a single shared instance is safe. A leading UTF-8
63
+ * BOM is consumed (stripped from the decoded string), which the
64
+ * generated-marker scanner relies on (research R6).
65
+ */
66
+ const UTF_8_DECODER = new TextDecoder("utf-8", { fatal: true });
67
+ /**
68
+ * Reads at most `budget` bytes of one candidate file beneath the analysis
69
+ * root, running the full safe-read sequence (FR-017, FR-018; research R4,
70
+ * R5): containment, `lstat`, regular-file check, size cap, open,
71
+ * budget-clamped read, strict UTF-8 decode.
72
+ *
73
+ * The caller (the tree walk, or a later analysis method) supplies paths
74
+ * relative to a resolved root; `readBounded` never reads a path that
75
+ * escapes it. `MAX_FILE_BYTES` is the hard cap on the lstat size; `budget`
76
+ * additionally clamps how many bytes are actually read (a 64 KiB marker
77
+ * prefix, a whole-file 16 MiB read). A non-positive budget reads nothing
78
+ * and resolves to the empty string. A budget that splits a multi-byte
79
+ * UTF-8 sequence yields a `decode error` skip — the truncated prefix is
80
+ * not valid standalone UTF-8, and signaling the loss beats silently
81
+ * dropping the partial character.
82
+ *
83
+ * Every skip resolves `null` after writing exactly one diagnostic line to
84
+ * `stderr`; `readBounded` never throws for skip conditions and never aborts
85
+ * the enclosing request (FR-017).
86
+ *
87
+ * @param root Resolved absolute analysis root; containment is enforced
88
+ * against this root (the caller resolves a symlinked root once at the
89
+ * boundary, before walking).
90
+ * @param relPath Walk-built root-relative POSIX path, echoed verbatim in
91
+ * diagnostics.
92
+ * @param budget Maximum number of bytes to read from the file.
93
+ * @param stderr Injected diagnostic sink (Testability principle — the
94
+ * Server passes its own `stderr`); stdout is never touched.
95
+ * @returns The decoded file content, or `null` when the file was skipped.
96
+ */
97
+ export async function readBounded(root, relPath, budget, stderr) {
98
+ const skip = (reason) => {
99
+ stderr.write(`reading-stone: skipping ${relPath}: ${reason}\n`);
100
+ return null;
101
+ };
102
+ // (1) Containment (FR-018, research R5) — before any filesystem access.
103
+ // The "begins with `..`" test is deliberately literal: as defense in
104
+ // depth it errs toward rejecting, so even a pathological in-root sibling
105
+ // such as `..hidden.ts` is refused unread rather than risk an escape.
106
+ const candidate = join(root, relPath);
107
+ const relativeToRoot = relative(root, candidate);
108
+ if (isAbsolute(relativeToRoot) || relativeToRoot.startsWith("..")) {
109
+ return skip("path escapes root");
110
+ }
111
+ // (2) lstat — never stat, so the final symlink is not followed. A file
112
+ // that vanished between the walk and this read (ENOENT), or that cannot
113
+ // be stat'd (EACCES on a parent directory), is a skip like any other.
114
+ let stats;
115
+ try {
116
+ stats = await lstat(candidate);
117
+ }
118
+ catch {
119
+ return skip("unreadable");
120
+ }
121
+ if (stats.isSymbolicLink()) {
122
+ return skip("symlink");
123
+ }
124
+ if (!stats.isFile()) {
125
+ return skip("not a regular file");
126
+ }
127
+ // (3) Size cap (FR-017) — from the lstat result, before open: an
128
+ // oversized file is never opened.
129
+ if (stats.size > MAX_FILE_BYTES) {
130
+ return skip("exceeds 16 MiB size limit");
131
+ }
132
+ // The read length is clamped by both the caller's budget and the lstat
133
+ // size (itself capped at MAX_FILE_BYTES), so the buffer allocation is
134
+ // bounded by the smaller of the two; a non-positive budget or size
135
+ // reads nothing.
136
+ const readLength = Math.max(0, Math.min(budget, stats.size));
137
+ // (4) Open + bounded read. Any filesystem failure here — including the
138
+ // permission-denied open of a chmod-000 file — is the same skip.
139
+ let bytes;
140
+ try {
141
+ bytes = await readPrefix(candidate, readLength);
142
+ }
143
+ catch {
144
+ return skip("unreadable");
145
+ }
146
+ try {
147
+ return UTF_8_DECODER.decode(bytes);
148
+ }
149
+ catch {
150
+ return skip("decode error");
151
+ }
152
+ }
153
+ /**
154
+ * Opens `candidate` and reads at most `readLength` bytes from its start
155
+ * into a fresh `Buffer`, closing the handle before resolving.
156
+ *
157
+ * The read loop advances by explicit position and stops at EOF, so a file
158
+ * that changed size after its lstat is still read deterministically:
159
+ * exactly the bytes present, never more than `readLength`.
160
+ *
161
+ * @param candidate Absolute candidate path already proven contained and
162
+ * within the size cap by `readBounded`'s guards.
163
+ * @param readLength Maximum number of bytes to read; never negative.
164
+ * @returns The bytes actually read (a view of length at most `readLength`).
165
+ */
166
+ async function readPrefix(candidate, readLength) {
167
+ // TOCTOU residual (research R4, spec US3): between readBounded's lstat
168
+ // and this open, the path can be swapped — regular file to FIFO,
169
+ // truncated, or removed. The accepted mitigation is this open in "r"
170
+ // mode plus the guarded read below: if a swap made the target blocking
171
+ // or non-regular, the open or the read errors and flows through the
172
+ // same skip path rather than hanging the request. The pre-open lstat
173
+ // remains the actual FIFO DoS defense; the TOCTOU-free alternative
174
+ // (open + fstat on the handle) was rejected because the open itself
175
+ // blocks on a FIFO before fstat can run, and O_NONBLOCK is not portable
176
+ // through Node's open flags (research R4).
177
+ const handle = await open(candidate, "r");
178
+ try {
179
+ const buffer = Buffer.alloc(readLength);
180
+ let bytesRead = 0;
181
+ while (bytesRead < readLength) {
182
+ const { bytesRead: chunkBytes } = await handle.read(buffer, bytesRead, readLength - bytesRead, bytesRead);
183
+ if (chunkBytes === 0) {
184
+ break; // EOF before readLength: the file shrank since lstat.
185
+ }
186
+ bytesRead += chunkBytes;
187
+ }
188
+ return buffer.subarray(0, bytesRead);
189
+ }
190
+ finally {
191
+ try {
192
+ await handle.close();
193
+ }
194
+ catch {
195
+ // A close failure after the bytes were read does not invalidate
196
+ // them; swallowing it keeps this helper's failure surface limited
197
+ // to the open and the read (both mapped to skips by the caller).
198
+ }
199
+ }
200
+ }
201
+ /**
202
+ * The synchronous bounded read for callers bound to a sync contract — the
203
+ * TypeScript `CompilerHost.readFile` signature (research R1). The guard
204
+ * sequence is `readBounded`'s minus containment (see the module header):
205
+ * the caller hands back compiler-resolved absolute paths, so root
206
+ * containment stays the caller's decision.
207
+ *
208
+ * In order: `lstatSync` regular-file check (FIFOs, devices, sockets, and
209
+ * symlinks skipped before the open — the FIFO DoS defense, research R4),
210
+ * `MAX_FILE_BYTES` size cap checked before open, bounded synchronous
211
+ * read, strict UTF-8 decode through the shared module decoder.
212
+ *
213
+ * Every skip returns `undefined` after writing exactly one diagnostic
214
+ * line to `stderr`; `readBoundedSync` never throws for skip conditions.
215
+ * `undefined` — not `null` — matches the `CompilerHost.readFile`
216
+ * absent-file signal the caller serves.
217
+ *
218
+ * @param absPath Absolute candidate path, echoed verbatim in diagnostics.
219
+ * @param stderr Injected diagnostic sink (Testability principle — the
220
+ * compiler host passes the server's own `stderr`); stdout is never touched.
221
+ * @returns The decoded file content, or `undefined` when the file was
222
+ * skipped.
223
+ */
224
+ export function readBoundedSync(absPath, stderr) {
225
+ const skip = (reason) => {
226
+ stderr.write(`reading-stone: skipping ${absPath}: ${reason}\n`);
227
+ return undefined;
228
+ };
229
+ // (1) lstatSync — never statSync, so the final symlink is not followed. A
230
+ // file that vanished (ENOENT), or that cannot be stat'd (EACCES on a
231
+ // parent directory), is a skip like any other.
232
+ let stats;
233
+ try {
234
+ stats = lstatSync(absPath);
235
+ }
236
+ catch {
237
+ return skip("unreadable");
238
+ }
239
+ if (stats.isSymbolicLink()) {
240
+ return skip("symlink");
241
+ }
242
+ if (!stats.isFile()) {
243
+ return skip("not a regular file");
244
+ }
245
+ // (2) Size cap — from the lstat result, before open: an oversized file is
246
+ // never opened.
247
+ if (stats.size > MAX_FILE_BYTES) {
248
+ return skip("exceeds 16 MiB size limit");
249
+ }
250
+ // (3) Bounded synchronous read. Any filesystem failure here — including
251
+ // the permission-denied open of a chmod-000 file — is the same skip.
252
+ let bytes;
253
+ try {
254
+ bytes = readPrefixSync(absPath, stats.size);
255
+ }
256
+ catch {
257
+ return skip("unreadable");
258
+ }
259
+ try {
260
+ return UTF_8_DECODER.decode(bytes);
261
+ }
262
+ catch {
263
+ return skip("decode error");
264
+ }
265
+ }
266
+ /**
267
+ * Synchronous counterpart of `readPrefix`: opens `candidate` and reads at
268
+ * most `readLength` bytes from its start into a fresh `Buffer`, closing
269
+ * the descriptor before returning.
270
+ *
271
+ * `fs.readFileSync` is deliberately not used: it accepts no length bound
272
+ * (its options object silently ignores one), so a file that grew between
273
+ * the lstat and the read would be read whole — unbounded memory on an
274
+ * untrusted tree. The explicit `readSync` loop holds the read at the
275
+ * lstat size, exactly as `readPrefix` does for `readBounded`.
276
+ *
277
+ * @param candidate Absolute candidate path already proven a regular file
278
+ * within the size cap by `readBoundedSync`'s guards.
279
+ * @param readLength Maximum number of bytes to read; never negative.
280
+ * @returns The bytes actually read (a view of length at most `readLength`).
281
+ */
282
+ function readPrefixSync(candidate, readLength) {
283
+ // TOCTOU residual (research R4): the sync sequence has no await points,
284
+ // so only an external process can swap or shrink the target between the
285
+ // lstat and this open. A regular-file-to-FIFO swap in that window would
286
+ // BLOCK this open — Node's synchronous fs provides no non-blocking mode —
287
+ // so the pre-open lstat regular-file check is the sole FIFO defense; the
288
+ // "r"-mode open and the guarded read below keep every other swap
289
+ // (removed, unreadable, truncated) on the error path, the same skip.
290
+ const descriptor = openSync(candidate, "r");
291
+ try {
292
+ const buffer = Buffer.alloc(readLength);
293
+ let bytesRead = 0;
294
+ while (bytesRead < readLength) {
295
+ const chunkBytes = readSync(descriptor, buffer, bytesRead, readLength - bytesRead, bytesRead);
296
+ if (chunkBytes === 0) {
297
+ break; // EOF before readLength: the file shrank since lstat.
298
+ }
299
+ bytesRead += chunkBytes;
300
+ }
301
+ return buffer.subarray(0, bytesRead);
302
+ }
303
+ finally {
304
+ try {
305
+ closeSync(descriptor);
306
+ }
307
+ catch {
308
+ // A close failure after the bytes were read does not invalidate
309
+ // them; swallowing it keeps this helper's failure surface limited
310
+ // to the open and the read (both mapped to skips by the caller).
311
+ }
312
+ }
313
+ }
314
+ //# sourceMappingURL=safeio.js.map
@@ -0,0 +1,19 @@
1
+ import type { Readable, Writable } from "node:stream";
2
+ export declare class RpcError extends Error {
3
+ readonly code: number;
4
+ constructor(code: number, message: string);
5
+ }
6
+ export type Handler = (params: object | null) => object | Promise<object>;
7
+ export declare class Server {
8
+ private readonly stdin;
9
+ private readonly stdout;
10
+ private readonly stderr;
11
+ private readonly dispatch;
12
+ private brokenPipe;
13
+ private shuttingDown;
14
+ constructor(stdin: Readable, stdout: Writable, stderr: Writable, dispatch?: Map<string, Handler>);
15
+ run(): Promise<void>;
16
+ private handleLine;
17
+ private writeResponse;
18
+ private createDefaultDispatch;
19
+ }