@oscaner-skills/cdd-engine 4.12.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.
@@ -1,10 +1,10 @@
1
1
  // packages/cdd-engine/src-next/infra/plan-source.ts
2
- // Task 2 — the plan read + parse + classify seam (design spec §2.1 · §2.4 · §2.7):
3
- // ONE deep class (`PlanSource`) with TWO entries — the derived face (`readFor`,
4
- // `entry.slug` → `${docRoots.plans}/<slug>.md`) and the argv face (`readPath`) —
5
- // and ONE value (`PlanRead`) that carries the behaviour the seven call sites used
6
- // to re-spell. The tri-state is a class (a private discriminant field + a `kind`
7
- // getter + the accessors), never a bare discriminated union: no consumer writes
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
8
  // `switch (read.kind)` to recover a fact the value already owns.
9
9
  //
10
10
  // · The path basis is the `RepoRoot` conversion pair: every `DocFs` call takes
@@ -12,23 +12,30 @@
12
12
  // directory reads against the injected root — never `process.cwd()` (NodeFs
13
13
  // resolves a literal against the process cwd, which would silently read a
14
14
  // healthy plan as unreadable).
15
- // · `undeclared` has exactly one producer — the derived face's own read (a null
16
- // slug, or a derived path that is not on disk). There is no `undeclared`
17
- // factory: "this phase has no plan yet" is a real read result, not a value a
18
- // caller can mint. `readPath` never probes existence, so an absent argv path
19
- // is an io read failure — the dispatch face keeps today's usage bytes.
20
- // · The reverse lookup is part of the READ (§2.7): whether `<slug>-design.md`
21
- // exists decides if this plan names a phase. It is a read fact, not a doc-shape
22
- // violation — zero rules registered, zero `Finding`, zero new `kind` token. It
23
- // runs on the argv face only (`readFor`'s entry IS the identity document, so
24
- // `spec-absent` is structurally unreachable there) and it only probes
25
- // existence (`DocFs.exists`), never a content predicate. The probe sits in the
26
- // `readPath` entry itself, NOT in the shared read tail: the derived face passes
27
- // `null`, so "the derived face never reverse-looks-up" is a fact of the seam
28
- // rather than a flag each call site has to keep straight.
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.
29
35
  //
30
36
  // Module-level exports are types / the class family — zero behavior-carrying bare
31
37
  // functions (the plan's zero-bare-function discipline).
38
+ var _a;
32
39
  import { DocSyntaxError, PlanDocType } from "../contract/doc.js";
33
40
  import { FrontMatterExtractor } from "../contract/frontmatter.js";
34
41
  import { NodeFs } from "../contract/invariants.js";
@@ -39,7 +46,7 @@ import { SlugIndex } from "./slug-index.js";
39
46
  * requires, so "exactly one producer family" is judged by `tsc` rather than by a
40
47
  * comment. The symbol is not exported, therefore no other module can spell the key
41
48
  * and a structural object literal there fails to type-check; every mint lives in
42
- * this file (`PlanSource`'s three states and the fallbacks it threads). */
49
+ * this file (`PlanSource`'s states and the fallbacks it threads). */
43
50
  const READ_STATE_BRAND = Symbol("cdd.plan-read-state");
44
51
  /** The undeclared doc-face wave row (`(none)` — today's bytes for "no plan yet"). */
45
52
  const UNDECLARED_WAVE = "(none)";
@@ -60,23 +67,28 @@ export class PlanRead {
60
67
  constructor(state) {
61
68
  this.#state = state;
62
69
  }
63
- /** The tri-state discriminant (`undeclared` / `unreadable` / `ready`). */
70
+ /** The read's discriminant (`undeclared` / `unreadable` / `ready`, plus the
71
+ * `duplicated` set that answers no absence). */
64
72
  get kind() {
65
73
  return this.#state.kind;
66
74
  }
67
- /** The plan row's fact (§2.1): `undeclared` → null; `unreadable` and `ready` →
68
- * the path (unreadable does not mean pathless). An empty string would disguise
69
- * "no document" as "an empty path" and render half a plan row. */
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. */
70
79
  path() {
71
80
  const state = this.#state;
72
- return state.kind === "undeclared" ? null : state.path;
81
+ if (state.kind === "undeclared" || state.kind === "duplicated")
82
+ return null;
83
+ return state.path;
73
84
  }
74
85
  /** The frontier's path (§2.1 · §2.5): the document reads out (its front matter
75
- * parsed), NOT "it parses into a graph". `undeclared` → null (no document);
76
- * `io` → null (no slug key, so no face is assemblable); `syntax` → the path (the
77
- * front matter read out, the plan face assembles, and its doc-contract refusal
78
- * is exactly the next face to point at); `ready` → the path. This is today's
79
- * per-cause distribution, now a value behaviour. */
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. */
80
92
  stationPath() {
81
93
  const state = this.#state;
82
94
  if (state.kind === "ready")
@@ -126,6 +138,13 @@ export class PlanRead {
126
138
  const state = this.#state;
127
139
  return state.kind === "ready" ? state.orphan : null;
128
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
+ }
129
148
  /** The board's wave data; the empty set when not ready (an empty set is NOT a
130
149
  * render signal — `degradedWaveRow` / `cell` own the literals). */
131
150
  waves() {
@@ -133,7 +152,9 @@ export class PlanRead {
133
152
  return state.kind === "ready" ? state.graph.batches() : [];
134
153
  }
135
154
  /** The doc-face wave row's degradation literal (§2.4 + the §2.7 fold); null means
136
- * "the healthy row is the assembler's", never "nothing to show". */
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. */
137
158
  degradedWaveRow(words) {
138
159
  return this.#degradedWord(words, UNDECLARED_WAVE);
139
160
  }
@@ -143,11 +164,11 @@ export class PlanRead {
143
164
  return this.#degradedWord(words, words.cellEmpty);
144
165
  }
145
166
  /** The plan row's cell content (§2.1): the degraded shapes carry the path plus
146
- * the mark; a healthy `ready` is the bare path; `undeclared` / `slug-absent`
147
- * return null (the row falls back to the existing identity bookkeeping). */
167
+ * the mark; a healthy `ready` is the bare path; `undeclared` / `slug-absent` /
168
+ * `duplicated` return null (the identity bookkeeping owns those rows). */
148
169
  planLine(words) {
149
170
  const state = this.#state;
150
- if (state.kind === "undeclared")
171
+ if (state.kind === "undeclared" || state.kind === "duplicated")
151
172
  return null;
152
173
  if (state.kind === "unreadable")
153
174
  return `${state.path}${MARK_SEPARATOR}${words.planReadWord(state.cause)}`;
@@ -159,20 +180,25 @@ export class PlanRead {
159
180
  return state.path;
160
181
  }
161
182
  /** The spec row's cell content — the spec-absent orphan only; every other state
162
- * (healthy, non-ready, `slug-absent`, undecided) returns null. */
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. */
163
186
  specLine(words) {
164
187
  return this.#orphanCause() === "spec-absent" ? words.planOrphanWord() : null;
165
188
  }
166
189
  /** The board's `CDD_WARN:` line (stderr): the two unreadable causes, the
167
- * `spec-absent` orphan and the `slug-absent` fact each produce one; `undeclared`
168
- * and a healthy `ready` produce null ("no plan yet" is normal, not a failure). */
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). */
169
194
  warnLine(words) {
170
- const diagnostic = this.#diagnostic(words);
195
+ const diagnostic = this.#diagnostic(words) ?? this.#undecidedWords(words);
171
196
  return diagnostic === null ? null : `${words.warnPrefix} ${diagnostic}`;
172
197
  }
173
198
  /** The pre-flight refusal (§2.3): the two unreadable causes and the spec-absent
174
- * orphan; `slug-absent` is stopped earlier by the identity channel and the
175
- * healthy / undeclared states have nothing to refuse. */
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. */
176
202
  refusal(words) {
177
203
  const state = this.#state;
178
204
  const message = state.kind === "unreadable"
@@ -189,7 +215,7 @@ export class PlanRead {
189
215
  * the two faces spell differently (`(none)` vs the empty program cell). */
190
216
  #degradedWord(words, undeclared) {
191
217
  const state = this.#state;
192
- if (state.kind === "undeclared")
218
+ if (state.kind === "undeclared" || state.kind === "duplicated")
193
219
  return undeclared;
194
220
  if (state.kind === "unreadable")
195
221
  return words.planReadWord(state.cause);
@@ -220,8 +246,8 @@ export class PlanRead {
220
246
  const head = `${words.planReadWord(state.cause)} ${state.path}`;
221
247
  return state.field === null ? head : `${head}: ${state.field}`;
222
248
  }
223
- /** The orphan diagnostic of the ready state — the `spec-absent` sentence (slug +
224
- * derived path) or the `slug-absent` one; null when neither applies. */
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. */
225
251
  #orphanWords(words) {
226
252
  const orphan = this.orphan();
227
253
  if (orphan === null)
@@ -229,10 +255,22 @@ export class PlanRead {
229
255
  if (orphan.cause === "slug-absent")
230
256
  return words.planSlugMissing();
231
257
  const slug = this.#slugOf();
232
- const specPath = orphan.specPath;
233
- if (slug === null || specPath === null)
234
- return null;
235
- return words.planOrphanSpec(slug, specPath);
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);
236
274
  }
237
275
  /** The one diagnostic source `warnLine` and `refusal` share. */
238
276
  #diagnostic(words) {
@@ -244,39 +282,53 @@ export class PlanRead {
244
282
  }
245
283
  /**
246
284
  * PlanSource — the plan read seam: one instance per command, constructed in the
247
- * command preamble (after the repo root resolves) and passed down as a parameter.
248
- * It owns the read + parse + classify path both entries share; the reverse lookup
249
- * rides the argv entry only.
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.
250
291
  */
251
292
  export class PlanSource {
252
293
  /** The path basis — the injected repo root (required: the root is a per-command fact). */
253
294
  #root;
295
+ /** The command's ONE identity index — both legs ask it (zero self-built scan). */
296
+ #index;
254
297
  /** The filesystem seam (defaults to node:fs). */
255
298
  #fs;
256
299
  /** The ONE plan parser this source reads through (the plan doc type's single
257
300
  * read point, beside the `docTypeParsers` registry row). */
258
301
  #parser = new PlanDocType("plan");
259
- constructor(root, fs = new NodeFs()) {
302
+ constructor(root, index, fs = new NodeFs()) {
260
303
  this.#root = root;
304
+ this.#index = index;
261
305
  this.#fs = fs;
262
306
  }
263
- /** The derived face: `entry.slug` is the whole identity, the path is derived from
264
- * it. An absent derived path is `undeclared` (this phase has no plan yet); an
265
- * existing path whose bytes do not read is `unreadable`/`io`. No reverse lookup
266
- * and no index: the entry IS the identity document. A null entry (an identity the
267
- * index did not register) carries no slug, so it reads exactly like a slug-less
268
- * entry: `undeclared` — never a minted value. */
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. */
269
314
  readFor(entry) {
270
315
  const slug = entry?.slug ?? null;
271
- if (slug === null)
272
- return new PlanRead({ kind: "undeclared", [READ_STATE_BRAND]: true });
273
- const rel = `${ENGINE_RUNTIME.docRoots.plans}/${slug}.md`;
274
- if (!this.#fs.exists(this.#abs(rel)))
275
- return new PlanRead({ kind: "undeclared", [READ_STATE_BRAND]: true });
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;
276
328
  const content = this.#fs.read(this.#abs(rel));
277
329
  if (content === null)
278
330
  return this.#ioFailure(rel);
279
- return this.#classify(rel, content, null);
331
+ return this.#classify(rel, content, null, null);
280
332
  }
281
333
  /** The argv face: the caller names the path, so a failed read is NEVER
282
334
  * `undeclared` — the dispatch face keeps today's usage bytes. The reverse
@@ -288,7 +340,8 @@ export class PlanSource {
288
340
  if (content === null)
289
341
  return this.#ioFailure(path);
290
342
  const { head } = FrontMatterExtractor.split(content);
291
- return this.#classify(path, content, this.#orphanOf(head));
343
+ const lookup = this.#lookupOf(head);
344
+ return this.#classify(path, content, lookup.orphan, lookup.undecided);
292
345
  }
293
346
  // -------------------------------------------------------------------------
294
347
  // the private read chain
@@ -298,6 +351,30 @@ export class PlanSource {
298
351
  #abs(rel) {
299
352
  return this.#root.resolve(this.#root.relativize(rel));
300
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
+ }
301
378
  /** The io read failure — the bytes did not read. `DocFs.read` carries no errno,
302
379
  * so the failure records the path and the cause only; the sentence the reader
303
380
  * sees is composed by the diagnostics (`#failureWords`), never stored. */
@@ -311,10 +388,10 @@ export class PlanSource {
311
388
  });
312
389
  }
313
390
  /** The shared read tail: front-matter split, ONE parse, the eager graph. The
314
- * reverse-lookup result arrives as a parameter (`null` on the derived face), so
391
+ * reverse-lookup result arrives as parameters (`null` on the derived face), so
315
392
  * this tail contains no probe. A grammar break is the typed `DocSyntaxError` and
316
393
  * becomes the `syntax` failure; any other throw is a programming break. */
317
- #classify(path, content, orphan) {
394
+ #classify(path, content, orphan, undecided) {
318
395
  const { head } = FrontMatterExtractor.split(content);
319
396
  try {
320
397
  const doc = this.#parser.parse(content.split("\n"), head);
@@ -326,6 +403,7 @@ export class PlanSource {
326
403
  doc,
327
404
  graph,
328
405
  orphan,
406
+ undecided,
329
407
  [READ_STATE_BRAND]: true,
330
408
  });
331
409
  }
@@ -341,19 +419,43 @@ export class PlanSource {
341
419
  });
342
420
  }
343
421
  }
344
- /** The reverse lookup (§2.7) — existence only. A legal slug derives
345
- * `<slug>-design.md` and the probe answers "does this plan name a phase"; an
346
- * illegal slug derives nothing (that is an identity break, not an orphan), and
347
- * an absent slug is the `slug-absent` read fact. */
348
- #orphanOf(head) {
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) {
349
428
  const slug = head.slug;
350
429
  if (slug === null)
351
- return { cause: "slug-absent", specPath: null };
430
+ return { orphan: { cause: "slug-absent" }, undecided: null };
352
431
  if (!SlugIndex.isLegalSlug(slug))
353
- return null;
354
- const specRel = `${ENGINE_RUNTIME.docRoots.specs}/${slug}-design.md`;
355
- if (this.#fs.exists(this.#abs(specRel)))
356
- return null;
357
- return { cause: "spec-absent", specPath: specRel };
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 };
358
459
  }
359
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