@oscaner-skills/cdd-engine 4.12.0 → 4.14.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.
@@ -0,0 +1,893 @@
1
+ // packages/cdd-engine/src-next/contract/pins.ts
2
+ // P37 T6 — the pin parseability gate (design spec §7.1 · §7.2 · §7.4). A pin is a
3
+ // claim a document makes about the tree: a path, a bare symbol, or a test title. A
4
+ // pin that resolves nowhere leaves a claim nobody can re-check, so the gate reports
5
+ // it — one criterion, fed by three corpora, executed on two faces:
6
+ //
7
+ // · the engine suite's structural test over the whole docs corpus (`scan`);
8
+ // · the document review's read-back over the JUDGED document's own body
9
+ // (`scanText`, called from `face/lifecycle.ts#reconstruct`);
10
+ // · the handoff read-back over each finding's `contract.path` (`pathResolves`,
11
+ // the same `#reconstruct` — `PinAudit`'s markdown scan never carries that cell).
12
+ //
13
+ // WHAT IS A PIN is part of the gate (§7.1): a backticked token is judged only when it
14
+ // is repo-root relative, is not product vocabulary, and is not an ephemeral artifact.
15
+ // Without those three exclusions the scanner would treat prose vocabulary as a claim.
16
+ // The product family is matched by SHAPE (its concrete instances are machine-local
17
+ // names — `plan-fix-1.c1.rulings.json`, `tasks-1-fix-1-a2.c1.json` — which can never
18
+ // resolve in another clone), while the template family is excluded only when the token
19
+ // IS the entry: a real `<dir>/<slug>-overall.md` reference is still a judged
20
+ // coordinate, and it is exactly the stale-path case §7.3 migrates.
21
+ //
22
+ // The three shapes are judged on their own terms: a path by the THREE-TIER resolution
23
+ // of §7.1 (exact entry → unique suffix → ambiguity, never a first hit) and never by
24
+ // content — content matching cannot be mechanical; a bare symbol against an identifier
25
+ // index of the reviewed repo's OWN sources (built once, cached, and read from the code
26
+ // body — `PinSource` — never from raw bytes); and a test title against the named test
27
+ // file's bytes. The symbol corpus is the repo the judge runs in, because the engine is
28
+ // installed into consumer trees that carry none of this repo's paths: a hard-wired root
29
+ // list would leave the index empty there and report every live symbol-shaped pin dead.
30
+ //
31
+ // The time face (§7.3) rides the same judgment: a path a plan's `Create:` line
32
+ // declares, that the tree has not landed, and that the plan has not been closed on is
33
+ // PENDING — not dead. `ForwardPaths` computes that table once and all three corpora
34
+ // read it, so one pending path answers identically wherever it is judged.
35
+ //
36
+ // A MEMBER reference is a spelling of the bare-symbol shape, not a fourth shape (§7.1):
37
+ // the symbol index is a flat identifier set, so a member written with its carrier in one
38
+ // token (`HandoffSchema.gradingViolations` · `BoardView#summaryToken`) is judged in two
39
+ // halves — the carrier by the bare path / bare symbol sieve, the member by the same
40
+ // symbol shape test — and either half failing to resolve is one finding. §7.3's time face
41
+ // rides the carrier half unchanged: §7.1 sieves that half by the bare path form, so the
42
+ // carrier IS the pending path a plan's `Create:` line declares, and it answers here as it
43
+ // answers there (the member half is not consulted — a path the tree has not landed
44
+ // declares no members). The shape stays `symbol`, so the census reading is unchanged by
45
+ // this spelling. An empty carrier is not a member reference (`#reconstruct` names its own
46
+ // symbol, `#` is its prefix), so that token falls back to the whole-token symbol judgment.
47
+ //
48
+ // The corpus declaration (§7.1) lives HERE as `corpusOf(root)`, so the scan, the
49
+ // structural test and the census read one declaration rather than three copies of a
50
+ // list. The README half expands `packages/` at CALL time: `face/lifecycle.ts` imports
51
+ // this module on every `cdd` command, and a consumer's installed tree has no
52
+ // `packages/` directory, so a module-scope file-system read would throw on load.
53
+ //
54
+ // `PinAudit.census` is the ONE census accessor (§8.2): four readings off the same scan,
55
+ // never a second parse. The registry that exposes them is `contract/census.ts`.
56
+ //
57
+ // Zero document structure and zero semantics are judged here: this is the narrow form
58
+ // of the P28 reversal, not a docs corpus validator.
59
+ //
60
+ // Module-level exports are types / the declared vocabularies / the classes — zero
61
+ // behavior-carrying bare functions.
62
+ var _a, _b;
63
+ import { readdirSync, readFileSync, statSync } from "node:fs";
64
+ import path from "node:path";
65
+ import { ENGINE_DOC_ROOTS } from "../infra/doc-roots.js";
66
+ import { SlugIndex } from "../infra/slug-index.js";
67
+ import { ArtifactRegistry } from "../session/round-artifacts.js";
68
+ import { docTypeParsers } from "./doc.js";
69
+ import { FrontMatterExtractor } from "./frontmatter.js";
70
+ /** The retired workspace name that no matrix row owns any more — vocabulary, never a
71
+ * coordinate (§7.1 exclusion ②). Every LIVE artifact name is answered by the matrix
72
+ * itself (`ArtifactRegistry.ownsName`), so this set stays a list of names the tree no
73
+ * longer renders rather than a second naming table. */
74
+ const RETIRED_PRODUCT_NAMES = new Set(["liveness.json"]);
75
+ /** The template vocabulary — excluded only when the token IS the entry (§7.1): a real
76
+ * `docs/kairos/specs/<slug>-overall.md` is still a judged path. */
77
+ const TEMPLATE_WORDS = new Set(["X.md", "-overall.md", "-design.md"]);
78
+ /** The extensions a SEPARATOR-LESS token must carry to be a path — a dotted member name
79
+ * (`process.env` · `HOSTS.env`) is a symbol, not a file. A token carrying `/` is a path
80
+ * whatever its extension: the separator already says it names a location, so an asset
81
+ * coordinate (`docs/diagrams/src/architecture.png`) is judged rather than slipping into
82
+ * prose. */
83
+ const FILE_EXTENSIONS = new Set([
84
+ "ts",
85
+ "tsx",
86
+ "js",
87
+ "mjs",
88
+ "cjs",
89
+ "json",
90
+ "md",
91
+ "yml",
92
+ "yaml",
93
+ "sh",
94
+ "toml",
95
+ "txt",
96
+ "css",
97
+ "html",
98
+ ]);
99
+ /** The directories a walk never descends into — build output, VCS internals and the
100
+ * machine-local workspace products name no pin (and reading them would let a local
101
+ * `.kairos/` file make a coordinate resolve, which is exactly the reading §7.3's
102
+ * migration exists to stop depending on). The same list keeps an installed copy of the
103
+ * engine out of the symbol index: `node_modules/` is a dependency, not a declaration of
104
+ * the reviewed tree. */
105
+ const SKIP_DIRS = new Set([".git", ".kairos", "node_modules", "dist", ".pi"]);
106
+ /** The README family's package half — every `packages/<dir>/README*.md`, expanded from
107
+ * the tree at CALL time so the declaration stays a rule and never a list. A caller
108
+ * whose root carries no `packages/` directory (a consumer's installed tree) gets no
109
+ * package READMEs instead of a throw: the expansion is a corpus question, not a load
110
+ * precondition. */
111
+ const packageReadmesOf = (root) => {
112
+ try {
113
+ return readdirSync(path.join(root, "packages"), { withFileTypes: true })
114
+ .filter((entry) => entry.isDirectory())
115
+ .flatMap((entry) => readdirSync(path.join(root, "packages", entry.name))
116
+ .filter((name) => /^README.*\.md$/.test(name))
117
+ .map((name) => `packages/${entry.name}/${name}`));
118
+ }
119
+ catch {
120
+ return [];
121
+ }
122
+ };
123
+ /** The §7.1 corpus declaration — the ONE place the judged markdown roots are written:
124
+ * the docs tree plus the README family, no baseline, no allowlist, no exemption. The
125
+ * root comes from the caller (`face/cli.ts#rootOf()` in production, the test's own
126
+ * `import.meta.url` root in the suite); this module never resolves one for itself. */
127
+ export const corpusOf = (root) => [
128
+ "docs/kairos",
129
+ "README.md",
130
+ "README.zh-CN.md",
131
+ ...packageReadmesOf(root),
132
+ ];
133
+ /**
134
+ * PinVocabulary — the pin DEFINITION (§7.1). A token is judged only when the three
135
+ * exclusions leave it a claim; the shape classifiers then say which of the three
136
+ * shapes (if any) the token belongs to, so a command word, a flag or a placeholder is
137
+ * never mistaken for a coordinate.
138
+ */
139
+ // biome-ignore lint/complexity/noStaticOnlyClass: the pin DEFINITION is a declared static vocabulary and a shape classifier set — the repo's zero-bare-function discipline admits no standalone predicates.
140
+ export class PinVocabulary {
141
+ /** Whether a backticked token is a pin at all — the three exclusions, in order. */
142
+ static isPin(token) {
143
+ if (token.length === 0)
144
+ return false;
145
+ // ① repo-root relative: a `./` / `../` shorthand or a `...` elision is prose.
146
+ if (/^\.\.?\//.test(token) || /^\.\.\./.test(token))
147
+ return false;
148
+ // ② not product vocabulary (the product family by shape, the template family only
149
+ // when the token is the entry itself).
150
+ if (PinVocabulary.#isProduct(token) || TEMPLATE_WORDS.has(token))
151
+ return false;
152
+ // ③ not an ephemeral artifact: a `.changeset/*.md` is consumed at release.
153
+ if (token.startsWith(".changeset/") && token.endsWith(".md"))
154
+ return false;
155
+ return true;
156
+ }
157
+ /** The product-family judgment (§7.1 exclusion ②, by shape): a basename the artifact
158
+ * matrix owns (the workspace literals, every round family, the sidecar) or one of the
159
+ * retired names the tree no longer renders. Matched on the BASENAME, so
160
+ * `.kairos/cdd/<workspace>/progress.json` is product vocabulary while a real
161
+ * `<dir>/<slug>-overall.md` stays a judged coordinate. */
162
+ static #isProduct(token) {
163
+ const base = token.split("/").pop() ?? token;
164
+ return RETIRED_PRODUCT_NAMES.has(base) || ArtifactRegistry.ownsName(base);
165
+ }
166
+ /** The placeholder metacharacters — a token carrying one is a PATTERN, and a pattern
167
+ * is none of the three shapes: `*-overall.md` names a family, `<slug>-design.md`
168
+ * names a rule for deriving a path. Neither is a coordinate a reader can follow. */
169
+ static isPattern(token) {
170
+ return /[*<>{}|\s]/.test(token);
171
+ }
172
+ /** The path shape `path.ext[:line[-line]]`, or null when the token is not
173
+ * path-shaped. An extension is required — `BLOCKED/TIMEOUT`, `--spec/--plan` and
174
+ * `findings/artifacts/notes` are prose compounds, and `ReviewKey` is a symbol. The
175
+ * extension VOCABULARY, however, only gates a token with no separator: behind a `/`,
176
+ * "the asset I cite" is a judged claim whatever the asset's extension
177
+ * (`docs/diagrams/src/architecture.png`), while `process.env` carries no separator
178
+ * and needs its extension in the vocabulary to be a file at all. What still decides
179
+ * is the SHAPE, not the vocabulary: `#` marks a member half
180
+ * (`session/ledger.ts#Round.findingsPath`), a segment opening with `.` is a dotfile
181
+ * name (`.kairos/.gitignore`), and an extension must look like one (lowercase, letter
182
+ * first) — which leaves `@scope/pkg@1.3.0` and `REVIEWS.wave/branch.axesGuide` prose
183
+ * where they belong. */
184
+ static pathOf(token) {
185
+ if (PinVocabulary.isPattern(token))
186
+ return null;
187
+ const match = /^(?<file>[^\s:]+)(?::(?<first>\d+)(?:-(?<last>\d+))?)?$/.exec(token);
188
+ const groups = match?.groups;
189
+ if (groups === undefined)
190
+ return null;
191
+ const file = groups.file;
192
+ // A leading-dot or leading-dash token with no separator names a SUFFIX
193
+ // (`.rulings.json` · `.md` · `-overall.md`), which §7.1's second exclusion lists as
194
+ // vocabulary: it is a word about names, not a name. A prefixed PATH
195
+ // (`.github/workflows/x.yml`, `docs/kairos/specs/<slug>-overall.md`) still carries
196
+ // its separator and stays a coordinate.
197
+ if ((file.startsWith(".") || file.startsWith("-")) && !file.includes("/"))
198
+ return null;
199
+ // `#` is a member separator, never a byte of a tree path: the member branch judges
200
+ // these, and reading one as a path would report a carrier/link as a missing file.
201
+ if (file.includes("#"))
202
+ return null;
203
+ const extension = /\.([A-Za-z0-9]+)$/.exec(file)?.[1] ?? "";
204
+ // An extension is a lowercase name (`ts` · `md` · `png`), not a version tail
205
+ // (`@scope/pkg@1.3.0` → `0`) nor a dotted prose compound (`REVIEWS.wave/branch.axesGuide`).
206
+ if (!/^[a-z][a-z0-9]*$/.test(extension))
207
+ return null;
208
+ if (!FILE_EXTENSIONS.has(extension) && !file.includes("/"))
209
+ return null;
210
+ // A final segment opening with `.` is a dotfile NAME (`.kairos/.gitignore`), a
211
+ // configuration word rather than a coordinate the migration can chase.
212
+ if ((file.split("/").pop() ?? file).startsWith("."))
213
+ return null;
214
+ const first = groups.first === undefined ? undefined : Number(groups.first);
215
+ const last = groups.last === undefined ? undefined : Number(groups.last);
216
+ return {
217
+ path: file,
218
+ ...(first === undefined ? {} : { firstLine: first }),
219
+ ...(last === undefined ? {} : { lastLine: last }),
220
+ };
221
+ }
222
+ /** The test-title shape `file.test.ts::title`, or null. The FILE half must be a
223
+ * coordinate (no placeholder metacharacter); the title half is prose and may carry
224
+ * spaces — that is what a test title is. */
225
+ static testOf(token) {
226
+ const at = token.indexOf("::");
227
+ if (at === -1)
228
+ return null;
229
+ const file = token.slice(0, at);
230
+ const title = token.slice(at + 2).trim();
231
+ if (/[*<>{}|]/.test(file) || !file.endsWith(".test.ts") || title.length === 0)
232
+ return null;
233
+ return { file, title };
234
+ }
235
+ /** A member reference — the bare-symbol shape written across two halves (§7.1). The
236
+ * trailing call arguments are prose about the call, so they are peeled first. A token
237
+ * carrying a `#` splits at its LAST `#` (a path carrier carries dots of its own),
238
+ * otherwise at its FIRST `.`. An EMPTY carrier is not a member reference: a token that
239
+ * starts with `#` puts the boundary at index 0, and there `#` is the symbol's own
240
+ * prefix — the caller falls back to the whole-token symbol judgment rather than
241
+ * reading an empty carrier. Both halves must pass their own sieve; a half that is
242
+ * prose makes the whole token prose.
243
+ */
244
+ static memberOf(token) {
245
+ const head = token.replace(/\([^()]*\)$/, "");
246
+ const boundary = head.lastIndexOf("#") !== -1 ? head.lastIndexOf("#") : head.indexOf(".");
247
+ if (boundary <= 0)
248
+ return null;
249
+ const carrier = head.slice(0, boundary);
250
+ const member = head.slice(boundary + 1);
251
+ if (PinVocabulary.pathOf(carrier) === null && !PinVocabulary.isSymbol(carrier))
252
+ return null;
253
+ if (!PinVocabulary.isSymbol(member))
254
+ return null;
255
+ return { carrier, member };
256
+ }
257
+ /** A bare symbol — a code identifier, not an English word. The shape admits three
258
+ * spellings: a private member (`#member`), a name with an underscore
259
+ * (`INPUT_FINDINGS`), or a camel / Pascal name (`findingsOf`, `ReviewKey`). An
260
+ * all-lowercase word (`wave`) and a hex prefix (`b69bb177`) are prose, not symbols —
261
+ * judging them would report every backticked noun in the corpus. */
262
+ static isSymbol(token) {
263
+ if (!/^#?[A-Za-z_$][A-Za-z0-9_$]*$/.test(token))
264
+ return false;
265
+ if (token.startsWith("#"))
266
+ return token.length > 1;
267
+ if (token.includes("_"))
268
+ return true;
269
+ return /[A-Z]/.test(token.slice(1));
270
+ }
271
+ }
272
+ /**
273
+ * PinSpans — the markdown reader. Only INLINE code spans are claims: a fenced block is
274
+ * example code (its bytes are not a document's assertion), and the span's content is
275
+ * the text between a backtick run and the next run of the same length.
276
+ */
277
+ // biome-ignore lint/complexity/noStaticOnlyClass: the markdown span reader is a declared static reader set — the repo's zero-bare-function discipline admits no standalone parser.
278
+ export class PinSpans {
279
+ /** Every inline code span of one markdown body, in document order. */
280
+ static tokensOf(text) {
281
+ const tokens = [];
282
+ let fenced = false;
283
+ for (const line of text.split("\n")) {
284
+ if (/^\s*(```|~~~)/.test(line)) {
285
+ fenced = !fenced;
286
+ continue;
287
+ }
288
+ if (fenced)
289
+ continue;
290
+ for (const span of PinSpans.#spansIn(line))
291
+ tokens.push(span);
292
+ }
293
+ return tokens;
294
+ }
295
+ /** The inline spans of one line — a run of `n` backticks closed by the next run of
296
+ * the same length; an unmatched run ends the line's scan (never an invented span). */
297
+ static #spansIn(line) {
298
+ const spans = [];
299
+ let index = 0;
300
+ while (index < line.length) {
301
+ const open = line.indexOf("`", index);
302
+ if (open === -1)
303
+ break;
304
+ let width = 0;
305
+ while (line[open + width] === "`")
306
+ width += 1;
307
+ const closer = line.indexOf("`".repeat(width), open + width);
308
+ if (closer === -1)
309
+ break;
310
+ spans.push(line.slice(open + width, closer));
311
+ index = closer + width;
312
+ }
313
+ return spans;
314
+ }
315
+ }
316
+ /**
317
+ * PinSource — the declaration reader behind the symbol index (§7.1). A name resolves
318
+ * only when it survives in CODE: comment bodies and regex-literal bodies are blanked
319
+ * first (length- and line-preserving, so a later reader's position stays true) — the
320
+ * two places a deleted name outlives its declaration, namely the typed prose of a
321
+ * comment and a retirement guard's own pattern text.
322
+ *
323
+ * String and template literals are deliberately KEPT: in this tree they are where live
324
+ * vocabulary is declared (`face/words.ts` spells `CDD_BLOCKED:` as a literal ·
325
+ * `contract/lint.ts` derives `DependsOn id` from a literal · the round-context tokens
326
+ * are emitted from prompt literals). Blanking them reported 82 live `CDD_BLOCKED` pins
327
+ * and 94 `DependsOn` pins as dead, so a literal is a value the code carries, not prose
328
+ * about a name.
329
+ */
330
+ // biome-ignore lint/complexity/noStaticOnlyClass: the declaration reader is a declared static reader set — the repo's zero-bare-function discipline admits no standalone parser.
331
+ export class PinSource {
332
+ /** One source text with every comment and regex literal body blanked — the
333
+ * declaration corpus the identifier index tokenizes. */
334
+ static codeOf(source) {
335
+ const out = source.split("");
336
+ const blank = (from, to) => {
337
+ for (let at = from; at < to && at < out.length; at += 1) {
338
+ if (out[at] !== "\n")
339
+ out[at] = " ";
340
+ }
341
+ };
342
+ let index = 0;
343
+ let previous = "";
344
+ while (index < source.length) {
345
+ const char = source[index];
346
+ const next = source[index + 1];
347
+ if (char === "/" && next === "/") {
348
+ const start = index;
349
+ while (index < source.length && source[index] !== "\n")
350
+ index += 1;
351
+ blank(start, index);
352
+ }
353
+ else if (char === "/" && next === "*") {
354
+ const start = index;
355
+ index += 2;
356
+ while (index < source.length && !(source[index] === "*" && source[index + 1] === "/")) {
357
+ index += 1;
358
+ }
359
+ index += 2;
360
+ blank(start, index);
361
+ }
362
+ else if (char === "'" || char === '"' || char === "`") {
363
+ // kept verbatim — see the class header: a literal is a value, not prose
364
+ const quote = char;
365
+ index += 1;
366
+ while (index < source.length && source[index] !== quote) {
367
+ if (source[index] === "\\")
368
+ index += 1;
369
+ index += 1;
370
+ }
371
+ index += 1;
372
+ }
373
+ else if (char === "/" && PinSource.#regexMayStart(previous)) {
374
+ const start = index;
375
+ index += 1;
376
+ let inClass = false;
377
+ while (index < source.length) {
378
+ const inner = source[index];
379
+ if (inner === "\n")
380
+ break;
381
+ if (inner === "\\") {
382
+ index += 2;
383
+ continue;
384
+ }
385
+ if (inner === "[") {
386
+ inClass = true;
387
+ index += 1;
388
+ continue;
389
+ }
390
+ if (inner === "]") {
391
+ inClass = false;
392
+ index += 1;
393
+ continue;
394
+ }
395
+ index += 1;
396
+ if (inner === "/" && !inClass)
397
+ break;
398
+ }
399
+ blank(start, index);
400
+ }
401
+ else {
402
+ if (char.trim() !== "")
403
+ previous = char;
404
+ index += 1;
405
+ }
406
+ }
407
+ return out.join("");
408
+ }
409
+ /** Whether a `/` at `previous` (the last non-space code char, "" at file start) may
410
+ * open a regex literal rather than being a division operator. */
411
+ static #regexMayStart(previous) {
412
+ return previous === "" || !/[A-Za-z0-9_$)\]]/.test(previous);
413
+ }
414
+ }
415
+ /**
416
+ * PinIndex — the resolution face: the repo's own entry list (files and directories, for
417
+ * suffix resolution and the symbol index's source files), and the per-file reads the
418
+ * line-count and test-title shapes need. Everything is built lazily and cached, so one
419
+ * audit instance pays the walk once.
420
+ */
421
+ export class PinIndex {
422
+ #root;
423
+ #entries = null;
424
+ #symbols = null;
425
+ #lineCounts = new Map();
426
+ constructor(root) {
427
+ this.#root = root;
428
+ }
429
+ /** Every repo entry (file or directory), repo-relative — the path shape's corpus. */
430
+ entries() {
431
+ this.#entries ??= PinIndex.#walk(this.#root, this.#root);
432
+ return this.#entries;
433
+ }
434
+ /** The identifier set of the reviewed repo's own sources — the symbol shape's corpus.
435
+ * It rides the entry walk the path shape already pays for, so the symbols the gate
436
+ * accepts are declared in the tree the judged documents describe; no root list is
437
+ * hard-wired, because the engine runs inside consumer repos whose sources live under
438
+ * paths this repo never names (`src/`, `lib/`), and an index built from such a list is
439
+ * empty there. Identifiers come from the code body (`PinSource.codeOf`), never from raw
440
+ * bytes: a name kept alive only by a comment or a guard test's own regex is prose
441
+ * about the name, not the name being there. A private member indexes as
442
+ * `artifactCellOf` (`#` is not an identifier character), which is why `isSymbol`
443
+ * strips it too. */
444
+ symbols() {
445
+ if (this.#symbols !== null)
446
+ return this.#symbols;
447
+ const symbols = new Set();
448
+ for (const entry of this.entries()) {
449
+ if (!PinIndex.#isSource(entry))
450
+ continue;
451
+ const text = this.textOf(entry);
452
+ if (text === null)
453
+ continue;
454
+ for (const match of PinSource.codeOf(text).matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)) {
455
+ symbols.add(match[0]);
456
+ }
457
+ }
458
+ this.#symbols = symbols;
459
+ return symbols;
460
+ }
461
+ /** The repo entry a pin's path resolves to, across §7.1's three tiers. A suffix
462
+ * match lets a doc write the tail of a long path; tier ① keeps an EXACT spelling
463
+ * from falling into a shorter same-tailed sibling (`README.md` is the repo root
464
+ * copy, never `.changeset/README.md`), and tier ③ reports every candidate instead
465
+ * of silently choosing a first hit. */
466
+ resolve(pinPath) {
467
+ const normalized = PinIndex.normalize(pinPath);
468
+ if (normalized.length === 0)
469
+ return { kind: "absent" };
470
+ const entries = this.entries();
471
+ if (entries.includes(normalized))
472
+ return { kind: "resolved", entry: normalized };
473
+ const candidates = entries.filter((entry) => entry.endsWith(`/${normalized}`));
474
+ if (candidates.length === 1)
475
+ return { kind: "resolved", entry: candidates[0] };
476
+ if (candidates.length > 1)
477
+ return { kind: "ambiguous", candidates };
478
+ return { kind: "absent" };
479
+ }
480
+ /** The ONE spelling of a pin path's normalization — a leading `./` and trailing
481
+ * slashes are prose, not coordinates. */
482
+ static normalize(pinPath) {
483
+ return pinPath.replace(/^\.\//, "").replace(/\/+$/, "");
484
+ }
485
+ /** One entry's text, null when it cannot be read (a directory, a vanished file). */
486
+ textOf(entry) {
487
+ try {
488
+ return readFileSync(path.join(this.#root, entry), "utf8");
489
+ }
490
+ catch {
491
+ return null;
492
+ }
493
+ }
494
+ /** One entry's line count — 0 when it cannot be read. A closing newline ENDS the last
495
+ * line instead of opening a phantom one, so a pin naming `last + 1` is dead rather
496
+ * than one-line lenient. */
497
+ lineCountOf(entry) {
498
+ const cached = this.#lineCounts.get(entry);
499
+ if (cached !== undefined)
500
+ return cached;
501
+ const text = this.textOf(entry);
502
+ const count = text === null ? 0 : PinIndex.#linesOf(text);
503
+ this.#lineCounts.set(entry, count);
504
+ return count;
505
+ }
506
+ /** The real lines of one text — its newlines, plus a tail only when the tail is not
507
+ * empty (`""` has none, `"a\\n"` has one, `"a"` has one). */
508
+ static #linesOf(text) {
509
+ if (text.length === 0)
510
+ return 0;
511
+ const lines = text.split("\n").length;
512
+ return text.endsWith("\n") ? lines - 1 : lines;
513
+ }
514
+ /** Whether one test file contains the named title's bytes. */
515
+ testContains(entry, title) {
516
+ const text = this.textOf(entry);
517
+ return text?.includes(title) ?? false;
518
+ }
519
+ /** Whether one entry is a source file the symbol index reads. */
520
+ static #isSource(entry) {
521
+ return /\.(ts|tsx|js|mjs|cjs|json)$/.test(entry);
522
+ }
523
+ /** Every entry under one directory (or the file itself), repo-relative — one walk,
524
+ * skipping the build / VCS directories. */
525
+ static #walk(target, root) {
526
+ const entries = [];
527
+ let stat;
528
+ try {
529
+ stat = statSync(target);
530
+ }
531
+ catch {
532
+ return entries;
533
+ }
534
+ if (!stat.isDirectory())
535
+ return [path.relative(root, target)];
536
+ for (const dirent of readdirSync(target, { withFileTypes: true })) {
537
+ if (SKIP_DIRS.has(dirent.name))
538
+ continue;
539
+ const at = path.join(target, dirent.name);
540
+ entries.push(path.relative(root, at));
541
+ if (dirent.isDirectory())
542
+ entries.push(...PinIndex.#walk(at, root));
543
+ }
544
+ return entries;
545
+ }
546
+ }
547
+ /**
548
+ * ForwardPaths — §7.3's time face: the paths a plan's `Create:` lines declare while the
549
+ * tree has not landed them yet. The judgment lives HERE, once, and the three corpora
550
+ * (`scan` · `scanText` · `pathResolves`) read the same table — a pending path therefore
551
+ * answers identically wherever it is judged, which is what lets the pin census be one
552
+ * reading rather than three.
553
+ *
554
+ * Three conditions, all read from DECLARED values (§7.3): the declaring plan shares an
555
+ * identity key with the judged document, the path is absent from the tree (the caller
556
+ * asks only after resolution failed), and the plan has not been closed by its program's
557
+ * `## Phase inventory` row. A repository with no closure face — a single-spec, or a
558
+ * charter without that table — is bounded by the DECLARATION itself: a plan still on the
559
+ * tree and still writing the line is not closed.
560
+ *
561
+ * The identity facts are read from the documents' own front matter, never from file names
562
+ * and never through a second `SlugIndex`: P36's guard keeps the identity index to the
563
+ * command preamble's three sites, and `#reconstruct` builds none (its own note), so this
564
+ * face reads the same DECLARED values that index groups by. The slug grammar is still
565
+ * `SlugIndex.isLegalSlug` — one spelling of the value judgment.
566
+ */
567
+ export class ForwardPaths {
568
+ #index;
569
+ #heads = null;
570
+ #plans = null;
571
+ #pending = new Map();
572
+ constructor(index) {
573
+ this.#index = index;
574
+ }
575
+ /** Whether the judged document's own plan declares this absent path and has not been
576
+ * closed on it (§7.3). A `null` judged document — a wave / branch round — has no
577
+ * subject for condition ①, so the skip never holds there. */
578
+ skips(pinPath, judged) {
579
+ if (judged === null)
580
+ return false;
581
+ const normalized = PinIndex.normalize(pinPath);
582
+ return this.#pendingOf(judged).some((declared) => declared === normalized || declared.endsWith(`/${normalized}`));
583
+ }
584
+ /** The pending paths of one judged document — one table per identity, memoized, so a
585
+ * corpus scan pays one computation rather than one per token. */
586
+ #pendingOf(judged) {
587
+ const cached = this.#pending.get(judged);
588
+ if (cached !== undefined)
589
+ return cached;
590
+ const slug = this.#headsOf().find((head) => head.rel === judged)?.head.slug ?? null;
591
+ const paths = slug === null
592
+ ? []
593
+ : this.#plansOf()
594
+ .filter((plan) => _a.#shares(plan, slug) && !this.#isClosed(plan))
595
+ .flatMap((plan) => plan.paths);
596
+ this.#pending.set(judged, paths);
597
+ return paths;
598
+ }
599
+ /** Condition ① — the judged document's `slug:` equals the plan's, or the `program:`
600
+ * its same-slug identity document declares. */
601
+ static #shares(plan, slug) {
602
+ return plan.slug === slug || plan.programs.includes(slug);
603
+ }
604
+ /** Condition ③ — the plan's program charter names it in a `✔ Done(…)` row. */
605
+ #isClosed(plan) {
606
+ return plan.programs.some((program) => this.#closedBy(program, plan.slug));
607
+ }
608
+ /** Whether one program's charter closes the plan: the `Implementation plan` cell is
609
+ * written `✔ Done(`file` · date)` and that FILE NAME resolves to exactly one
610
+ * indexed document whose `slug:` is the plan's. Zero or several hits read as CLOSED —
611
+ * a registration that no longer resolves cannot establish "not closed", so a dead
612
+ * `✔ Done` row never buys a silent skip. */
613
+ #closedBy(program, slug) {
614
+ const heads = this.#headsOf();
615
+ const charter = heads.find((head) => head.head.slug === program && head.head.docType === "overall");
616
+ if (charter === undefined)
617
+ return false;
618
+ const parsed = docTypeParsers.overall.parse(charter.body.split("\n"), charter.head);
619
+ if (parsed.tables["Phase inventory"].headerRow === null)
620
+ return false;
621
+ for (const phase of parsed.chain.phases) {
622
+ const done = /✔ Done(`(?<file>[^`]+)`/.exec(phase.planCell)?.groups?.file;
623
+ if (done === undefined)
624
+ continue;
625
+ const hits = heads.filter((head) => path.basename(head.rel) === done);
626
+ if (hits.length !== 1 || hits[0]?.head.slug === slug)
627
+ return true;
628
+ }
629
+ return false;
630
+ }
631
+ /** One declaration table per audit instance — every plan that writes a `Create:`
632
+ * line, with the identity keys condition ① compares. */
633
+ #plansOf() {
634
+ if (this.#plans !== null)
635
+ return this.#plans;
636
+ const heads = this.#headsOf();
637
+ const plans = [];
638
+ for (const head of heads) {
639
+ const slug = head.head.slug;
640
+ if (head.head.docType !== "plan" || !SlugIndex.isLegalSlug(slug))
641
+ continue;
642
+ const paths = _a.#declaredPathsOf(head.body);
643
+ if (paths.length === 0)
644
+ continue;
645
+ plans.push({ slug, programs: _a.#programsOf(heads, slug), paths });
646
+ }
647
+ this.#plans = plans;
648
+ return plans;
649
+ }
650
+ /** The `program:` values the plan's same-slug identity documents declare — the second
651
+ * identity key, which lives on the identity document and never on the plan. */
652
+ static #programsOf(heads, slug) {
653
+ const programs = [];
654
+ for (const head of heads) {
655
+ if (head.head.slug !== slug || head.head.docType === "plan")
656
+ continue;
657
+ const program = head.head.program;
658
+ if (program === null || programs.includes(program))
659
+ continue;
660
+ programs.push(program);
661
+ }
662
+ return programs;
663
+ }
664
+ /** The paths one plan body's `Create:` lines write — path-shaped spans only, so the
665
+ * parenthetical prose beside a declaration is never mistaken for one. */
666
+ static #declaredPathsOf(body) {
667
+ const paths = [];
668
+ for (const line of body.split("\n")) {
669
+ if (!/^\s*[-*]\s+Create:/.test(line))
670
+ continue;
671
+ for (const token of PinSpans.tokensOf(line)) {
672
+ const form = PinVocabulary.pathOf(token);
673
+ if (form === null || paths.includes(form.path))
674
+ continue;
675
+ paths.push(form.path);
676
+ }
677
+ }
678
+ return paths;
679
+ }
680
+ /** The declared heads of the three doc roots — one read pass, memoized. */
681
+ #headsOf() {
682
+ if (this.#heads !== null)
683
+ return this.#heads;
684
+ const heads = [];
685
+ for (const rel of this.#index.entries()) {
686
+ if (!rel.endsWith(".md") || !_a.#inDocRoots(rel))
687
+ continue;
688
+ const text = this.#index.textOf(rel);
689
+ if (text === null)
690
+ continue;
691
+ const { head, body } = FrontMatterExtractor.split(text);
692
+ heads.push({ rel, head, body });
693
+ }
694
+ this.#heads = heads;
695
+ return heads;
696
+ }
697
+ /** Whether one repo-relative path lies inside a declared doc root — path grammar only. */
698
+ static #inDocRoots(rel) {
699
+ return Object.values(ENGINE_DOC_ROOTS).some((root) => rel.startsWith(`${root}/`));
700
+ }
701
+ }
702
+ _a = ForwardPaths;
703
+ /**
704
+ * PinAudit — the gate. `scan` judges a declared corpus of markdown roots, `scanText`
705
+ * judges one document body, and `pathResolves` judges a declared coordinate on its own
706
+ * (the handoff `contract.path` corpus). The three entry points share one criterion and
707
+ * one index; each corpus keeps its own read point.
708
+ *
709
+ * Rule zero (over the 200-line class limit): the gate stays one class because the three
710
+ * entry points are ONE criterion over ONE index and ONE pending-path table — `census`
711
+ * reads `scan`'s own length (§8.2), and splitting along the judge / resolve / read seams
712
+ * would hand that same index through a second seam without removing a variation.
713
+ */
714
+ export class PinAudit {
715
+ #root;
716
+ #index;
717
+ #forward;
718
+ constructor(root) {
719
+ this.#root = root;
720
+ this.#index = new PinIndex(root);
721
+ this.#forward = new ForwardPaths(this.#index);
722
+ }
723
+ /** One corpus file's text — the read the scan and the census gate share, so a second
724
+ * reader never opens the corpus through a mechanism of its own. */
725
+ textOf(entry) {
726
+ return this.#index.textOf(entry);
727
+ }
728
+ /** The four census readings (§8.2) — one scan and one file listing, so `total` is
729
+ * that scan's length rather than a second count and `files` is the corpus volume.
730
+ * The roots are the caller's already-resolved corpus (`corpusOf(root)`); this class
731
+ * never names a root of its own. */
732
+ census(roots) {
733
+ const findings = this.scan(roots);
734
+ const files = this.filesOf(roots);
735
+ const symbol = findings.filter((finding) => finding.shape === "symbol").length;
736
+ const path = findings.filter((finding) => finding.shape === "path" || finding.shape === "test").length;
737
+ return { symbol, path, total: findings.length, files: files.length };
738
+ }
739
+ /** The corpus the scan would read — the file list, so a structural test can pin its
740
+ * size instead of hoping the glob is stable. */
741
+ filesOf(roots) {
742
+ const files = [];
743
+ for (const root of roots) {
744
+ const at = path.resolve(this.#root, root);
745
+ for (const entry of _b.#walkFiles(at, this.#root))
746
+ files.push(entry);
747
+ }
748
+ return files;
749
+ }
750
+ /** Every dead pin of a markdown corpus — one finding per unresolvable token. */
751
+ scan(roots) {
752
+ const findings = [];
753
+ for (const file of this.filesOf(roots)) {
754
+ const text = this.#index.textOf(file);
755
+ if (text === null)
756
+ continue;
757
+ for (const finding of this.scanText(text, file))
758
+ findings.push(finding);
759
+ }
760
+ return findings;
761
+ }
762
+ /** Every dead pin of one document body — the document review's read-back corpus. */
763
+ scanText(text, source) {
764
+ const findings = [];
765
+ for (const token of PinSpans.tokensOf(text)) {
766
+ const finding = this.#judge(token, source, source);
767
+ if (finding !== null)
768
+ findings.push(finding);
769
+ }
770
+ return findings;
771
+ }
772
+ /** Whether one declared coordinate resolves — the `contract.path` corpus' one
773
+ * question. A path with a line suffix is judged on its path alone (the handoff
774
+ * anchor owns the line, the gate owns the coordinate). §7.3's time face applies
775
+ * here too: a pending `Create:` declaration of the JUDGED document's own plan is
776
+ * not dead — `null` judged (a wave / branch round) has no subject for that
777
+ * condition, so a pending path stays a finding there. */
778
+ pathResolves(pinPath, judged) {
779
+ const form = PinVocabulary.pathOf(pinPath);
780
+ const path = form?.path ?? pinPath;
781
+ if (this.#index.resolve(path).kind === "resolved")
782
+ return true;
783
+ return this.#forward.skips(path, judged);
784
+ }
785
+ /** One token's judgment — the test shape first (it also ends in `.ts`), then the path
786
+ * shape, then the bare symbol; anything else is prose, not a pin. `judged` is the
787
+ * document the round judges (§7.3 condition ①'s subject) — `scan` and `scanText`
788
+ * pass their own `source`, because that source IS the judged document. */
789
+ #judge(token, source, judged) {
790
+ if (!PinVocabulary.isPin(token))
791
+ return null;
792
+ const test = PinVocabulary.testOf(token);
793
+ if (test !== null) {
794
+ const file = this.#index.resolve(test.file);
795
+ if (file.kind !== "resolved") {
796
+ return _b.#finding(token, "test", source, file.kind === "ambiguous"
797
+ ? `its test file \`${test.file}\` matches ${file.candidates.length} entries (${file.candidates.join(" · ")})`
798
+ : `its test file \`${test.file}\` is not in the tree`);
799
+ }
800
+ if (this.#index.testContains(file.entry, test.title))
801
+ return null;
802
+ return _b.#finding(token, "test", source, `\`${file.entry}\` carries no test titled \`${test.title}\``);
803
+ }
804
+ const form = PinVocabulary.pathOf(token);
805
+ if (form !== null) {
806
+ const resolution = this.#index.resolve(form.path);
807
+ if (resolution.kind === "absent") {
808
+ if (this.#forward.skips(form.path, judged))
809
+ return null;
810
+ return _b.#finding(token, "path", source, `the path \`${form.path}\` is not in the tree`);
811
+ }
812
+ if (resolution.kind === "ambiguous") {
813
+ return _b.#finding(token, "path", source, `the path \`${form.path}\` names ${resolution.candidates.length} entries (${resolution.candidates.join(" · ")}), so it points at no single file`);
814
+ }
815
+ const named = form.lastLine ?? form.firstLine;
816
+ const lines = this.#index.lineCountOf(resolution.entry);
817
+ if (named !== undefined && named > lines) {
818
+ return _b.#finding(token, "path", source, `\`${resolution.entry}\` has ${lines} lines, so line ${named} does not exist`);
819
+ }
820
+ return null;
821
+ }
822
+ if (PinVocabulary.isSymbol(token)) {
823
+ const name = token.startsWith("#") ? token.slice(1) : token;
824
+ if (this.#index.symbols().has(name))
825
+ return null;
826
+ return _b.#finding(token, "symbol", source, `no symbol named \`${name}\` exists in the sources of this tree`);
827
+ }
828
+ const member = PinVocabulary.memberOf(token);
829
+ if (member === null)
830
+ return null;
831
+ // the carrier half is sieved by the bare path form, whose three tiers are explicit:
832
+ // an ambiguous basename names EVERY candidate instead of resolving nowhere (tier ③
833
+ // never picks one), exactly as the bare-path branch above reads it
834
+ const carrierResolution = PinVocabulary.pathOf(member.carrier) === null ? null : this.#index.resolve(member.carrier);
835
+ if (carrierResolution?.kind === "ambiguous") {
836
+ return _b.#finding(token, "symbol", source, `its carrier \`${member.carrier}\` names ${carrierResolution.candidates.length} entries (${carrierResolution.candidates.join(" · ")}), so it points at no single file`);
837
+ }
838
+ // §7.3's time face rides this half too: §7.1 sieves a member's carrier by the bare
839
+ // path form, so the carrier IS that path — a pending `Create:` declaration of the
840
+ // judged document's own plan must answer here exactly as the bare-path branch above
841
+ // answers it, or one pending path answers two ways inside one corpus. The member half
842
+ // is not consulted: a path the tree has not landed declares no members, so demanding
843
+ // one would ask for exactly the coordinate loss the skip exists to prevent.
844
+ if (carrierResolution?.kind === "absent" && this.#forward.skips(member.carrier, judged)) {
845
+ return null;
846
+ }
847
+ const carrier = carrierResolution === null
848
+ ? this.#index.symbols().has(member.carrier)
849
+ : carrierResolution.kind === "resolved";
850
+ const memberExists = this.#index.symbols().has(member.member);
851
+ if (carrier && memberExists)
852
+ return null;
853
+ return _b.#finding(token, "symbol", source, carrier
854
+ ? `no symbol named \`${member.member}\` exists in the sources of this tree`
855
+ : `its carrier \`${member.carrier}\` resolves nowhere in the tree`);
856
+ }
857
+ /** One finding's summary — the ONE wording the guard test and the round's injected
858
+ * warn share. */
859
+ static #finding(token, shape, source, reason) {
860
+ return {
861
+ pin: token,
862
+ shape,
863
+ source,
864
+ summary: `the pin \`${token}\` in ${source} resolves nowhere — ${reason}`,
865
+ };
866
+ }
867
+ /** The markdown files under one corpus root (or the root itself when it is a file). */
868
+ static #walkFiles(at, root) {
869
+ let stat;
870
+ try {
871
+ stat = statSync(at);
872
+ }
873
+ catch {
874
+ return [];
875
+ }
876
+ if (!stat.isDirectory())
877
+ return [path.relative(root, at)];
878
+ const files = [];
879
+ for (const dirent of readdirSync(at, { withFileTypes: true })) {
880
+ if (SKIP_DIRS.has(dirent.name))
881
+ continue;
882
+ const child = path.join(at, dirent.name);
883
+ if (dirent.isDirectory()) {
884
+ files.push(..._b.#walkFiles(child, root));
885
+ }
886
+ else if (dirent.name.endsWith(".md")) {
887
+ files.push(path.relative(root, child));
888
+ }
889
+ }
890
+ return files;
891
+ }
892
+ }
893
+ _b = PinAudit;