@oscaner-skills/cdd-engine 4.11.0 → 4.13.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,461 @@
1
+ // packages/cdd-engine/src-next/infra/plan-source.ts
2
+ // The plan read + parse + classify seam (design spec §2.1 · §2.4 · §2.7): ONE deep
3
+ // class (`PlanSource`) with TWO entries — the derived face (`readFor`,
4
+ // `entry.slug` → the index's plan row) and the argv face (`readPath`) — and ONE value
5
+ // (`PlanRead`) that carries the behaviour the seven call sites used to re-spell. The
6
+ // tri-state is a class (a private discriminant field + a `kind` getter + the
7
+ // accessors), never a bare discriminated union: no consumer writes
8
+ // `switch (read.kind)` to recover a fact the value already owns.
9
+ //
10
+ // · The path basis is the `RepoRoot` conversion pair: every `DocFs` call takes
11
+ // `root.resolve(root.relativize(rel))`, so a plan under a repository sub-
12
+ // directory reads against the injected root — never `process.cwd()` (NodeFs
13
+ // resolves a literal against the process cwd, which would silently read a
14
+ // healthy plan as unreadable).
15
+ // · IDENTITY, NEVER A NAME (§2.7): both legs ask the injected `SlugIndex`. The
16
+ // derived face takes the slug's plan ROW (`docsOf(slug)`, the plan `doc-type`)
17
+ // and reads that row's declared `rel`; it derives no `<slug>.md`. The reverse
18
+ // lookup asks whether the index holds an IDENTITY document for the slug, and
19
+ // whether the three doc roots' scan surface is clean enough to answer an
20
+ // absence at all. Zero filename derivation survives in this file.
21
+ // · The tri-state is `undeclared` / `unreadable` / `ready`. `undeclared` carries
22
+ // its REASON (`clean` — the root's surface answered "no plan"; `indeterminate` —
23
+ // the plans root dropped or failed to register candidates, so "no plan" is not
24
+ // available and the assembly face says so in one `CDD_WARN:` line). The
25
+ // undecided identity lookup rides the ready state the same way (`undecided`).
26
+ // The fourth shape, `duplicated`, is NOT part of that tri-state: `locate` answers
27
+ // `null` for both zero and two plans, so a caller reading `null` as "no plan"
28
+ // would answer "there is none" about a set of two — the one licence §2.7 forbids.
29
+ // It carries the found set instead, and the board's identity marker face renders
30
+ // it (never a first pick).
31
+ // · `undeclared` has exactly one producer family — `readFor`'s set question. There
32
+ // is no `undeclared` factory: "this phase has no plan yet" is a real read result,
33
+ // not a value a caller can mint. `readPath` never asks the plans root, so an
34
+ // absent argv path is an io read failure — the dispatch face keeps today's bytes.
35
+ //
36
+ // Module-level exports are types / the class family — zero behavior-carrying bare
37
+ // functions (the plan's zero-bare-function discipline).
38
+ var _a;
39
+ import { DocSyntaxError, PlanDocType } from "../contract/doc.js";
40
+ import { FrontMatterExtractor } from "../contract/frontmatter.js";
41
+ import { NodeFs } from "../contract/invariants.js";
42
+ import { TaskGraph } from "../session/graph.js";
43
+ import { ENGINE_RUNTIME } from "./runtime.js";
44
+ import { SlugIndex } from "./slug-index.js";
45
+ /** The state brand: a module-private symbol key that `PlanRead`'s constructor
46
+ * requires, so "exactly one producer family" is judged by `tsc` rather than by a
47
+ * comment. The symbol is not exported, therefore no other module can spell the key
48
+ * and a structural object literal there fails to type-check; every mint lives in
49
+ * this file (`PlanSource`'s states and the fallbacks it threads). */
50
+ const READ_STATE_BRAND = Symbol("cdd.plan-read-state");
51
+ /** The undeclared doc-face wave row (`(none)` — today's bytes for "no plan yet"). */
52
+ const UNDECLARED_WAVE = "(none)";
53
+ /** The cell separator of the plan row (`<path> · <mark>`). */
54
+ const MARK_SEPARATOR = " · ";
55
+ /**
56
+ * PlanRead — the plan read value, one per document read. Every accessor answers one
57
+ * question the call sites used to re-derive with a `switch`; the producer's share is
58
+ * the degradation literal only (a healthy row / a healthy cell returns `null`, and
59
+ * the assembler keeps its byte-identical path).
60
+ */
61
+ export class PlanRead {
62
+ /** The private discriminant — the state is the single source of every accessor. */
63
+ #state;
64
+ /** The constructor takes the branded state, so a `PlanRead` can only be built from
65
+ * a value minted in this module — the single-producer claim is a type, not a
66
+ * convention. */
67
+ constructor(state) {
68
+ this.#state = state;
69
+ }
70
+ /** The read's discriminant (`undeclared` / `unreadable` / `ready`, plus the
71
+ * `duplicated` set that answers no absence). */
72
+ get kind() {
73
+ return this.#state.kind;
74
+ }
75
+ /** The plan row's fact (§2.1): `undeclared` and `duplicated` → null (no single
76
+ * document); `unreadable` and `ready` → the path (unreadable does not mean
77
+ * pathless). An empty string would disguise "no document" as "an empty path" and
78
+ * render half a plan row. */
79
+ path() {
80
+ const state = this.#state;
81
+ if (state.kind === "undeclared" || state.kind === "duplicated")
82
+ return null;
83
+ return state.path;
84
+ }
85
+ /** The frontier's path (§2.1 · §2.5): the document reads out (its front matter
86
+ * parsed), NOT "it parses into a graph". `undeclared` / `duplicated` → null (no
87
+ * document, and no single one to follow); `io` → null (no slug key, so no face is
88
+ * assemblable); `syntax` → the path (the front matter read out, the plan face
89
+ * assembles, and its doc-contract refusal is exactly the next face to point at);
90
+ * `ready` → the path. This is today's per-cause distribution, now a value
91
+ * behaviour. */
92
+ stationPath() {
93
+ const state = this.#state;
94
+ if (state.kind === "ready")
95
+ return state.path;
96
+ if (state.kind === "unreadable" && state.cause === "syntax")
97
+ return state.path;
98
+ return null;
99
+ }
100
+ /** The failure's three facts, the ONE place they are taken from; null unless the
101
+ * read was `unreadable`. The rendered sentence is the word port's, not this
102
+ * value's. */
103
+ failure() {
104
+ const state = this.#state;
105
+ if (state.kind !== "unreadable")
106
+ return null;
107
+ return { path: state.path, cause: state.cause, field: state.field };
108
+ }
109
+ /** The document text (the wave brief's and `#targetSlug`'s source); null when not ready. */
110
+ text() {
111
+ const state = this.#state;
112
+ return state.kind === "ready" ? state.text : null;
113
+ }
114
+ /** The parsed document (the brief's data face); null when not ready. */
115
+ doc() {
116
+ const state = this.#state;
117
+ return state.kind === "ready" ? state.doc : null;
118
+ }
119
+ /** The ready read's two document values in ONE hand-off — the kind contract
120
+ * written in the type, so a caller that already guarded `kind` never re-narrows
121
+ * what the read decided. `text` and `doc` are non-null exactly when `kind` is
122
+ * `ready`; any other kind is a BROKEN invariant (the caller's guard is the only
123
+ * legal entry), so it throws instead of degrading the fact to "no document". */
124
+ document() {
125
+ const state = this.#state;
126
+ if (state.kind !== "ready")
127
+ throw new Error("cdd: a plan read outside the ready state carries no document");
128
+ return { text: state.text, doc: state.doc };
129
+ }
130
+ /** The task graph (the gate's / frontier's / board's one graph input), derived
131
+ * eagerly from the same parse; null when not ready. */
132
+ graph() {
133
+ const state = this.#state;
134
+ return state.kind === "ready" ? state.graph : null;
135
+ }
136
+ /** The reverse-lookup read fact (§2.7); only an argv-face `ready` read can carry one. */
137
+ orphan() {
138
+ const state = this.#state;
139
+ return state.kind === "ready" ? state.orphan : null;
140
+ }
141
+ /** The plan rows the slug names when TWO or more answered — the set the identity
142
+ * marker face renders; empty for every other read. This is the one accessor that
143
+ * makes "two plans" distinguishable from "no plan" (§2.7 (d)). */
144
+ found() {
145
+ const state = this.#state;
146
+ return state.kind === "duplicated" ? state.found : [];
147
+ }
148
+ /** The board's wave data; the empty set when not ready (an empty set is NOT a
149
+ * render signal — `degradedWaveRow` / `cell` own the literals). */
150
+ waves() {
151
+ const state = this.#state;
152
+ return state.kind === "ready" ? state.graph.batches() : [];
153
+ }
154
+ /** The doc-face wave row's degradation literal (§2.4 + the §2.7 fold); null means
155
+ * "the healthy row is the assembler's", never "nothing to show". A duplicated set
156
+ * keeps today's `(none)` here: the plan CELL carries the marker, the wave segment
157
+ * carries no plan fact. */
158
+ degradedWaveRow(words) {
159
+ return this.#degradedWord(words, UNDECLARED_WAVE);
160
+ }
161
+ /** The program-face wave cell's literal (§2.4 + the §2.7 fold); `""` is the
162
+ * undeclared program cell only, and null again hands the healthy cell back. */
163
+ cell(words) {
164
+ return this.#degradedWord(words, words.cellEmpty);
165
+ }
166
+ /** The plan row's cell content (§2.1): the degraded shapes carry the path plus
167
+ * the mark; a healthy `ready` is the bare path; `undeclared` / `slug-absent` /
168
+ * `duplicated` return null (the identity bookkeeping owns those rows). */
169
+ planLine(words) {
170
+ const state = this.#state;
171
+ if (state.kind === "undeclared" || state.kind === "duplicated")
172
+ return null;
173
+ if (state.kind === "unreadable")
174
+ return `${state.path}${MARK_SEPARATOR}${words.planReadWord(state.cause)}`;
175
+ const cause = this.#orphanCause();
176
+ if (cause === "spec-absent")
177
+ return `${state.path}${MARK_SEPARATOR}${words.planOrphanWord()}`;
178
+ if (cause === "slug-absent")
179
+ return null;
180
+ return state.path;
181
+ }
182
+ /** The spec row's cell content — the spec-absent orphan only; every other state
183
+ * (healthy, non-ready, `slug-absent`, undecided) returns null. The undecided read
184
+ * is exactly the case that may NOT print `! no-spec`: the index held nothing, but
185
+ * a doc root could not be read. */
186
+ specLine(words) {
187
+ return this.#orphanCause() === "spec-absent" ? words.planOrphanWord() : null;
188
+ }
189
+ /** The board's `CDD_WARN:` line (stderr): the two unreadable causes, the
190
+ * `spec-absent` orphan, the `slug-absent` fact and the UNDECIDED scan each
191
+ * produce one; `undeclared`-clean, `duplicated` and a healthy `ready` produce null
192
+ * ("no plan yet" is normal, not a failure; the duplicated set is an identity
193
+ * marker on stdout, not a read diagnostic). */
194
+ warnLine(words) {
195
+ const diagnostic = this.#diagnostic(words) ?? this.#undecidedWords(words);
196
+ return diagnostic === null ? null : `${words.warnPrefix} ${diagnostic}`;
197
+ }
198
+ /** The pre-flight refusal (§2.3): the two unreadable causes and the spec-absent
199
+ * orphan; `slug-absent` is stopped earlier by the identity channel, the undecided
200
+ * scan refuses nothing (§2.7 (c): zero refusal), the duplicated set is the
201
+ * identity gate's, and the healthy / undeclared states have nothing to refuse. */
202
+ refusal(words) {
203
+ const state = this.#state;
204
+ const message = state.kind === "unreadable"
205
+ ? this.#failureWords(words, state)
206
+ : this.#orphanCause() === "spec-absent"
207
+ ? this.#orphanWords(words)
208
+ : null;
209
+ return message === null ? null : { gate: "doc-contract", reason: "doc-contract", message };
210
+ }
211
+ // -------------------------------------------------------------------------
212
+ // the private behaviour — one place per semantic
213
+ // -------------------------------------------------------------------------
214
+ /** The degraded literal both faces share; the undeclared word is the only cell
215
+ * the two faces spell differently (`(none)` vs the empty program cell). */
216
+ #degradedWord(words, undeclared) {
217
+ const state = this.#state;
218
+ if (state.kind === "undeclared" || state.kind === "duplicated")
219
+ return undeclared;
220
+ if (state.kind === "unreadable")
221
+ return words.planReadWord(state.cause);
222
+ const cause = this.#orphanCause();
223
+ if (cause === "spec-absent")
224
+ return words.planOrphanWord();
225
+ if (cause === "slug-absent")
226
+ return null;
227
+ return state.doc.taskBlocks.length === 0 ? words.planEmptyWord() : null;
228
+ }
229
+ /** The ready state's orphan cause, or null (non-ready / healthy / undecided). */
230
+ #orphanCause() {
231
+ const state = this.#state;
232
+ if (state.kind !== "ready")
233
+ return null;
234
+ return state.orphan?.cause ?? null;
235
+ }
236
+ /** The ready state's declared slug, read off the parsed head it already carries. */
237
+ #slugOf() {
238
+ const state = this.#state;
239
+ if (state.kind !== "ready")
240
+ return null;
241
+ return state.doc.head?.slug ?? null;
242
+ }
243
+ /** The failure message of one unreadable state: `<word> <path>[: <field>]`. The
244
+ * io cause has no field, so it never renders a `null` tail. */
245
+ #failureWords(words, state) {
246
+ const head = `${words.planReadWord(state.cause)} ${state.path}`;
247
+ return state.field === null ? head : `${head}: ${state.field}`;
248
+ }
249
+ /** The orphan diagnostic of the ready state — the `spec-absent` sentence (the slug
250
+ * alone, zero derived path) or the `slug-absent` one; null when neither applies. */
251
+ #orphanWords(words) {
252
+ const orphan = this.orphan();
253
+ if (orphan === null)
254
+ return null;
255
+ if (orphan.cause === "slug-absent")
256
+ return words.planSlugMissing();
257
+ const slug = this.#slugOf();
258
+ return slug === null ? null : words.planOrphanSpec(slug);
259
+ }
260
+ /** The undecided-scan diagnostic — one line naming the dirty doc roots and their
261
+ * discarded count; null for every decided read. */
262
+ #undecidedWords(words) {
263
+ const state = this.#state;
264
+ const undecided = state.kind === "undeclared"
265
+ ? state.reason.kind === "indeterminate"
266
+ ? state.reason.undecided
267
+ : null
268
+ : state.kind === "ready"
269
+ ? state.undecided
270
+ : null;
271
+ return undecided === null
272
+ ? null
273
+ : words.planDiscardedWord(undecided.roots, undecided.discarded);
274
+ }
275
+ /** The one diagnostic source `warnLine` and `refusal` share. */
276
+ #diagnostic(words) {
277
+ const state = this.#state;
278
+ if (state.kind === "unreadable")
279
+ return this.#failureWords(words, state);
280
+ return this.#orphanWords(words);
281
+ }
282
+ }
283
+ /**
284
+ * PlanSource — the plan read seam: one instance per command, constructed in the
285
+ * command preamble (after the repo root AND the command's ONE identity index exist)
286
+ * and passed down as a parameter. It owns the read + parse + classify path both
287
+ * entries share; BOTH of its questions are identity questions and both are answered
288
+ * by the injected index. It never builds one: a second index would be a second
289
+ * snapshot of the disk, and the tri-state's "clean or not" answer must come from the
290
+ * same scan the rest of the command reads.
291
+ */
292
+ export class PlanSource {
293
+ /** The path basis — the injected repo root (required: the root is a per-command fact). */
294
+ #root;
295
+ /** The command's ONE identity index — both legs ask it (zero self-built scan). */
296
+ #index;
297
+ /** The filesystem seam (defaults to node:fs). */
298
+ #fs;
299
+ /** The ONE plan parser this source reads through (the plan doc type's single
300
+ * read point, beside the `docTypeParsers` registry row). */
301
+ #parser = new PlanDocType("plan");
302
+ constructor(root, index, fs = new NodeFs()) {
303
+ this.#root = root;
304
+ this.#index = index;
305
+ this.#fs = fs;
306
+ }
307
+ /** The derived face — the slug's PLAN ROW, never a derived file name (§2.7). The
308
+ * set answers, and only its single element is read: zero rows is the clean
309
+ * `undeclared` gap when the plans root's surface can answer an absence, the
310
+ * undecided read when it cannot; two or more rows is the `duplicated` set (a
311
+ * first pick here would answer "the plan" about a document the slug does not
312
+ * single out). A null entry (an identity the index did not register) carries no
313
+ * slug, so it reads exactly like a slug-less entry: `undeclared`, clean. */
314
+ readFor(entry) {
315
+ const slug = entry?.slug ?? null;
316
+ if (slug === null || !SlugIndex.isLegalSlug(slug))
317
+ return this.#undeclaredClean();
318
+ const plans = this.#index.docsOf(slug).filter((doc) => doc.docType === "plan");
319
+ if (plans.length === 0)
320
+ return this.#undeclaredAtPlansRoot();
321
+ if (plans.length > 1)
322
+ return new PlanRead({
323
+ kind: "duplicated",
324
+ found: plans.map((doc) => doc.rel),
325
+ [READ_STATE_BRAND]: true,
326
+ });
327
+ const rel = plans[0].rel;
328
+ const content = this.#fs.read(this.#abs(rel));
329
+ if (content === null)
330
+ return this.#ioFailure(rel);
331
+ return this.#classify(rel, content, null, null);
332
+ }
333
+ /** The argv face: the caller names the path, so a failed read is NEVER
334
+ * `undeclared` — the dispatch face keeps today's usage bytes. The reverse
335
+ * lookup runs once, here, and its result rides into the shared tail as a
336
+ * parameter; the tail itself probes nothing. */
337
+ readPath(rel) {
338
+ const path = this.#root.relativize(rel);
339
+ const content = this.#fs.read(this.#root.resolve(path));
340
+ if (content === null)
341
+ return this.#ioFailure(path);
342
+ const { head } = FrontMatterExtractor.split(content);
343
+ const lookup = this.#lookupOf(head);
344
+ return this.#classify(path, content, lookup.orphan, lookup.undecided);
345
+ }
346
+ // -------------------------------------------------------------------------
347
+ // the private read chain
348
+ // -------------------------------------------------------------------------
349
+ /** The absolute syscall form of one repo-relative path — the ONE conversion pair
350
+ * every `DocFs` call goes through (never a bare path resolved by the process cwd). */
351
+ #abs(rel) {
352
+ return this.#root.resolve(this.#root.relativize(rel));
353
+ }
354
+ /** The clean undeclared read — the phase carries no plan and the surface said so. */
355
+ #undeclaredClean() {
356
+ return new PlanRead({
357
+ kind: "undeclared",
358
+ reason: { kind: "clean" },
359
+ [READ_STATE_BRAND]: true,
360
+ });
361
+ }
362
+ /** The undeclared read at the plans root: a clean surface is the real gap, a dirty
363
+ * one only the undecided reading of it (spec §2.7). */
364
+ #undeclaredAtPlansRoot() {
365
+ const discard = this.#index.discarded().plans;
366
+ const discarded = discard.unreadable + discard.unregistered;
367
+ if (discarded === 0)
368
+ return this.#undeclaredClean();
369
+ return new PlanRead({
370
+ kind: "undeclared",
371
+ reason: {
372
+ kind: "indeterminate",
373
+ undecided: { roots: [ENGINE_RUNTIME.docRoots.plans], discarded },
374
+ },
375
+ [READ_STATE_BRAND]: true,
376
+ });
377
+ }
378
+ /** The io read failure — the bytes did not read. `DocFs.read` carries no errno,
379
+ * so the failure records the path and the cause only; the sentence the reader
380
+ * sees is composed by the diagnostics (`#failureWords`), never stored. */
381
+ #ioFailure(path) {
382
+ return new PlanRead({
383
+ kind: "unreadable",
384
+ path,
385
+ cause: "io",
386
+ field: null,
387
+ [READ_STATE_BRAND]: true,
388
+ });
389
+ }
390
+ /** The shared read tail: front-matter split, ONE parse, the eager graph. The
391
+ * reverse-lookup result arrives as parameters (`null` on the derived face), so
392
+ * this tail contains no probe. A grammar break is the typed `DocSyntaxError` and
393
+ * becomes the `syntax` failure; any other throw is a programming break. */
394
+ #classify(path, content, orphan, undecided) {
395
+ const { head } = FrontMatterExtractor.split(content);
396
+ try {
397
+ const doc = this.#parser.parse(content.split("\n"), head);
398
+ const graph = new TaskGraph(doc);
399
+ return new PlanRead({
400
+ kind: "ready",
401
+ path,
402
+ text: content,
403
+ doc,
404
+ graph,
405
+ orphan,
406
+ undecided,
407
+ [READ_STATE_BRAND]: true,
408
+ });
409
+ }
410
+ catch (error) {
411
+ if (!(error instanceof DocSyntaxError))
412
+ throw error;
413
+ return new PlanRead({
414
+ kind: "unreadable",
415
+ path,
416
+ cause: "syntax",
417
+ field: error.field,
418
+ [READ_STATE_BRAND]: true,
419
+ });
420
+ }
421
+ }
422
+ /** The reverse lookup (§2.7) — an IDENTITY question, never a name probe: does the
423
+ * index hold an identity document for this slug, and if not, may the three doc
424
+ * roots answer that absence? A legal slug is the only shape worth asking (an
425
+ * illegal one is the identity channel's judgment, not an orphan); an absent slug
426
+ * is the `slug-absent` read fact. */
427
+ #lookupOf(head) {
428
+ const slug = head.slug;
429
+ if (slug === null)
430
+ return { orphan: { cause: "slug-absent" }, undecided: null };
431
+ if (!SlugIndex.isLegalSlug(slug))
432
+ return { orphan: null, undecided: null };
433
+ if (this.#index.hasIdentity(slug))
434
+ return { orphan: null, undecided: null };
435
+ const undecided = _a.#undecidedOf(this.#index.discarded());
436
+ if (undecided !== null)
437
+ return { orphan: null, undecided };
438
+ return { orphan: { cause: "spec-absent" }, undecided: null };
439
+ }
440
+ /** The dirty doc roots of one scan — null when every root could answer an absence.
441
+ * A root that dropped a candidate, or indexed one without a registered doc type,
442
+ * cannot: its silence is not the disk's (spec §2.7). */
443
+ static #undecidedOf(discarded) {
444
+ const rows = [
445
+ [ENGINE_RUNTIME.docRoots.overalls, discarded.overalls],
446
+ [ENGINE_RUNTIME.docRoots.specs, discarded.specs],
447
+ [ENGINE_RUNTIME.docRoots.plans, discarded.plans],
448
+ ];
449
+ const roots = [];
450
+ let total = 0;
451
+ for (const [root, discard] of rows) {
452
+ const count = discard.unreadable + discard.unregistered;
453
+ if (count === 0)
454
+ continue;
455
+ roots.push(root);
456
+ total += count;
457
+ }
458
+ return roots.length === 0 ? null : { roots, discarded: total };
459
+ }
460
+ }
461
+ _a = PlanSource;
@@ -2,7 +2,9 @@
2
2
  // The identity index (spec §2.1/§2.2): ONE scan over the doc roots
3
3
  // (`ENGINE_RUNTIME.docRoots`) groups every document by its front-matter facts.
4
4
  // The index is the single judgment surface for document identity:
5
- // · lookups — `identityDoc` / `planOf` / `phaseSpecsOf` / `overallOf` / `entryAt`;
5
+ // · lookups — `docsOf` / `hasIdentity` / `phaseSpecsOf` / `overallOf` / `entryAt`;
6
+ // the slug lookups answer the SET (0 / 1 / n) and never pick a first: ambiguity is
7
+ // the read face's judgment, not the index's choice;
6
8
  // · violations — duplicate identity document · duplicate plan · missing `slug:` ·
7
9
  // illegal `slug:` value · `program:` target with no overall document.
8
10
  // Identity is the `slug:` value, never the file name; a document's class is its
@@ -21,6 +23,8 @@ import { SLUG_VALUE_PATTERN } from "../contract/declare.js";
21
23
  import { FrontMatterExtractor } from "../contract/frontmatter.js";
22
24
  import { DOC_KEYS } from "../contract/project.js";
23
25
  import { ENGINE_RUNTIME } from "./runtime.js";
26
+ /** The doc roots in scan order — the ONE order `build` scans and `discarded` reports. */
27
+ const DOC_ROOT_KEYS = ["overalls", "specs", "plans"];
24
28
  /**
25
29
  * SlugIndex — the identity index over the doc roots. Construct it through
26
30
  * `build` (the one scanning entry point); every lookup and the violation list
@@ -58,8 +62,11 @@ export class SlugIndex {
58
62
  #bySlug;
59
63
  /** The materialized judgment over this scan. */
60
64
  #violations;
61
- constructor(entries) {
65
+ /** The per-root discarded candidates, produced by the SAME scan as `entries`. */
66
+ #discarded;
67
+ constructor(entries, discarded) {
62
68
  this.entries = entries;
69
+ this.#discarded = discarded;
63
70
  const byRel = new Map();
64
71
  const bySlug = new Map();
65
72
  for (const entry of entries) {
@@ -80,33 +87,48 @@ export class SlugIndex {
80
87
  * optional `fs` is the caller's scan seam (the judgment plane's in-memory
81
88
  * `DocFs`); absent, the node:fs scan is the production default. */
82
89
  static build(repoRoot, fs) {
83
- const entries = [
84
- ...SlugIndex.#scanRoot(repoRoot, ENGINE_RUNTIME.docRoots.overalls, fs),
85
- ...SlugIndex.#scanRoot(repoRoot, ENGINE_RUNTIME.docRoots.specs, fs),
86
- ...SlugIndex.#scanRoot(repoRoot, ENGINE_RUNTIME.docRoots.plans, fs),
87
- ].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
88
- return new SlugIndex(entries);
90
+ const scanned = DOC_ROOT_KEYS.map((key) => SlugIndex.#scanRoot(repoRoot, ENGINE_RUNTIME.docRoots[key], fs));
91
+ const entries = scanned
92
+ .flatMap((root) => root.entries)
93
+ .sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
94
+ return new SlugIndex(entries, {
95
+ overalls: scanned[0].discard,
96
+ specs: scanned[1].discard,
97
+ plans: scanned[2].discard,
98
+ });
99
+ }
100
+ /** The candidates each doc root dropped or indexed without a registered doc type —
101
+ * the fact "this root cannot answer an absence" (spec §2.7). Produced by the same
102
+ * scan as `entries`, so a read that asks both never sees two snapshots. */
103
+ discarded() {
104
+ return this.#discarded;
105
+ }
106
+ /** Whether every doc root's scan surface is clean — the whole-doc-roots absence
107
+ * question the identity reverse lookup asks (a clean miss is `spec-absent`; a
108
+ * dirty surface is an UNDECIDED read, never an absence). */
109
+ docRootsClean() {
110
+ return DOC_ROOT_KEYS.every((key) => {
111
+ const discard = this.#discarded[key];
112
+ return discard.unreadable === 0 && discard.unregistered === 0;
113
+ });
89
114
  }
90
115
  /** The entry at one repo-root-relative path, or null when the path is not indexed. */
91
116
  entryAt(rel) {
92
117
  return this.#byRel.get(rel) ?? null;
93
118
  }
94
- /** The identity document (overall / phase-spec / single-spec) carrying the
95
- * slug, or null when no identity document does. */
96
- identityDoc(slug) {
97
- for (const entry of this.#bySlug.get(slug) ?? []) {
98
- if (SlugIndex.#isIdentity(entry))
99
- return entry;
100
- }
101
- return null;
119
+ /** Every indexed document declaring the slug, in scan order — 0, 1 or n. The index
120
+ * answers the SET and NEVER selects: "the first one" is the defect this member
121
+ * retires, so a caller that needs one path reads it through the doc domain
122
+ * (`read({domain: "doc", …})`), which refuses an ambiguous set instead of choosing. */
123
+ docsOf(slug) {
124
+ return this.#bySlug.get(slug) ?? [];
102
125
  }
103
- /** The plan document carrying the slug, or null when no plan does. */
104
- planOf(slug) {
105
- for (const entry of this.#bySlug.get(slug) ?? []) {
106
- if (entry.docType === "plan")
107
- return entry;
108
- }
109
- return null;
126
+ /** Whether any IDENTITY document (overall / phase-spec / single-spec) declares the
127
+ * slug — the identity question the cross-doc chain asks. n ≥ 1 is true: a duplicated
128
+ * identity is still an identity (its ambiguity is `duplicatedRolesOf`'s judgment),
129
+ * so this member never lets a caller say "the slug names no identity document". */
130
+ hasIdentity(slug) {
131
+ return this.docsOf(slug).some((entry) => SlugIndex.#isIdentity(entry));
110
132
  }
111
133
  /** The phase-spec documents whose `program:` names the program slug, in program
112
134
  * order: the slugs' `-p<major>[.<minor>…]` tail numerically (p2 before p10,
@@ -193,22 +215,31 @@ export class SlugIndex {
193
215
  }
194
216
  /** Scan one doc root — the names come from `#entryNames`, the document judgment
195
217
  * from the shared `#readDoc` predicate (a `*.md` name whose content reads). An
196
- * unreadable candidate is not a document. */
218
+ * unreadable candidate is not a document, and a candidate that reads without a
219
+ * registered `doc-type:` is no identity document — BOTH are counted here, per root,
220
+ * so the absence question of §2.7 can be told apart from an undecided surface. */
197
221
  static #scanRoot(repoRoot, root, fs) {
198
222
  const entries = [];
223
+ let unreadable = 0;
224
+ let unregistered = 0;
199
225
  for (const name of SlugIndex.#entryNames(path.join(repoRoot, root), fs)) {
200
226
  if (!name.endsWith(".md"))
201
227
  continue;
202
228
  const rel = path.join(root, name);
203
229
  const abs = path.join(repoRoot, rel);
204
230
  const content = SlugIndex.#readDoc(abs, fs);
205
- if (content === null)
231
+ if (content === null) {
232
+ unreadable++;
206
233
  continue;
234
+ }
207
235
  const { head } = FrontMatterExtractor.split(content);
236
+ const docType = SlugIndex.#docTypeOf(head.docType);
237
+ if (docType === null)
238
+ unregistered++;
208
239
  entries.push({
209
240
  path: abs,
210
241
  rel,
211
- docType: SlugIndex.#docTypeOf(head.docType),
242
+ docType,
212
243
  slug: head.slug,
213
244
  program: head.program,
214
245
  version: head.version,
@@ -216,7 +247,7 @@ export class SlugIndex {
216
247
  title: head.title,
217
248
  });
218
249
  }
219
- return entries;
250
+ return { entries, discard: { unreadable, unregistered } };
220
251
  }
221
252
  /** The entry names of one doc root — the ONE `readdirSync` call site (the
222
253
  * injected seam's `list` otherwise). Names only: the document judgment is
@@ -14,7 +14,7 @@
14
14
  // key is the document's declared `slug:`, judged by the ONE identity index
15
15
  // (infra/slug-index.ts).
16
16
  import { createHash } from "node:crypto";
17
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
17
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
18
18
  import path from "node:path";
19
19
  import { parse } from "jsonc-parser";
20
20
  import { AtomicWriter } from "./atomic.js";
@@ -91,6 +91,24 @@ export class Workspace {
91
91
  resolve(name) {
92
92
  return path.join(this.path, name);
93
93
  }
94
+ /** The workspace directory's FILE names, in stable order — the ONE read of "what is
95
+ * in this workspace" (spec §2.5). Two consumers ask it and read the same list: the
96
+ * artifact matrix's `misplaced` judgment (which names attribute to one identity) and
97
+ * the ledger's orphan scan (which names no recorded round owns). A second
98
+ * `readdirSync` next to this one would be a second snapshot, so the orphan scan and
99
+ * the attribution judgment could disagree about what is on disk. An absent or
100
+ * unreadable directory is the empty fact: no workspace entry is a read failure. */
101
+ names() {
102
+ try {
103
+ return readdirSync(this.path, { withFileTypes: true })
104
+ .filter((entry) => entry.isFile())
105
+ .map((entry) => entry.name)
106
+ .sort();
107
+ }
108
+ catch {
109
+ return [];
110
+ }
111
+ }
94
112
  /** Read a JSON child — the tri-state face: `{kind:"ok",value}` on a present,
95
113
  * parseable file; `{kind:"missing"}` when the path does not exist; `{kind:
96
114
  * "malformed"}` when the file is present but its bytes are unparseable (a bad