@oscaner-skills/cdd-engine 2.0.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/{src-next/bin.ts → dist/bin.js} +18 -21
  4. package/dist/contract/declare.js +998 -0
  5. package/dist/contract/doc.js +565 -0
  6. package/dist/contract/frontmatter.js +209 -0
  7. package/dist/contract/home-extractors.js +379 -0
  8. package/dist/contract/invariants.js +1030 -0
  9. package/dist/contract/judge.js +109 -0
  10. package/dist/contract/lint.js +206 -0
  11. package/dist/contract/project.js +371 -0
  12. package/dist/contract/skill-anatomy.js +156 -0
  13. package/dist/contract/translate.js +85 -0
  14. package/dist/face/artifacts.js +189 -0
  15. package/dist/face/board-view.js +522 -0
  16. package/dist/face/capsule.js +141 -0
  17. package/dist/face/cli.js +891 -0
  18. package/dist/face/declare.js +241 -0
  19. package/dist/face/gate.js +158 -0
  20. package/dist/face/graph-view.js +66 -0
  21. package/dist/face/host.js +211 -0
  22. package/dist/face/lifecycle.js +603 -0
  23. package/dist/face/preview.js +136 -0
  24. package/dist/face/projection.js +259 -0
  25. package/dist/face/route-render.js +162 -0
  26. package/dist/face/termination.js +482 -0
  27. package/dist/face/words.js +220 -0
  28. package/{src-next/infra/config.ts → dist/infra/config.js} +19 -24
  29. package/dist/infra/doc-roots.js +19 -0
  30. package/dist/infra/git.js +37 -0
  31. package/dist/infra/process.js +22 -0
  32. package/dist/infra/root.js +62 -0
  33. package/dist/infra/runtime.js +85 -0
  34. package/dist/infra/workspace.js +276 -0
  35. package/dist/render/brief.js +82 -0
  36. package/dist/render/issue-body.js +129 -0
  37. package/dist/render/skeleton.js +434 -0
  38. package/dist/render/templates.js +520 -0
  39. package/dist/session/faces.js +38 -0
  40. package/dist/session/graph.js +309 -0
  41. package/dist/session/handoff-schema.js +295 -0
  42. package/dist/session/ledger.js +762 -0
  43. package/dist/session/next.js +211 -0
  44. package/dist/session/preflight.js +194 -0
  45. package/dist/session/round-naming.js +73 -0
  46. package/dist/session/run.js +441 -0
  47. package/dist/session/state.js +8 -0
  48. package/dist/session/wave.js +92 -0
  49. package/package.json +8 -7
  50. package/templates/report/issue-body.json +0 -46
  51. package/src-next/__tests__/bin.test.ts +0 -128
  52. package/src-next/__tests__/smoke.integration.test.ts +0 -202
  53. package/src-next/__tests__/zero-dep.test.ts +0 -134
  54. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +0 -238
  55. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +0 -153
  56. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +0 -173
  57. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +0 -89
  58. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +0 -225
  59. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +0 -155
  60. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +0 -175
  61. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +0 -85
  62. package/src-next/contract/__tests__/declare.test.ts +0 -242
  63. package/src-next/contract/__tests__/doc.test.ts +0 -358
  64. package/src-next/contract/__tests__/judge.test.ts +0 -873
  65. package/src-next/contract/__tests__/lint.test.ts +0 -314
  66. package/src-next/contract/__tests__/project.test.ts +0 -419
  67. package/src-next/contract/__tests__/translate.test.ts +0 -96
  68. package/src-next/contract/declare.ts +0 -983
  69. package/src-next/contract/doc.ts +0 -753
  70. package/src-next/contract/invariants.ts +0 -1268
  71. package/src-next/contract/judge.ts +0 -142
  72. package/src-next/contract/lint.ts +0 -275
  73. package/src-next/contract/project.ts +0 -596
  74. package/src-next/contract/skill-anatomy.ts +0 -273
  75. package/src-next/contract/translate.ts +0 -113
  76. package/src-next/face/__tests__/board-view.test.ts +0 -948
  77. package/src-next/face/__tests__/capsule.test.ts +0 -276
  78. package/src-next/face/__tests__/channel-closure.guard.test.ts +0 -102
  79. package/src-next/face/__tests__/cli.test.ts +0 -4643
  80. package/src-next/face/__tests__/face.test.ts +0 -289
  81. package/src-next/face/__tests__/graph-view.test.ts +0 -61
  82. package/src-next/face/__tests__/host.test.ts +0 -24
  83. package/src-next/face/__tests__/negation.ts +0 -6
  84. package/src-next/face/__tests__/projection.test.ts +0 -301
  85. package/src-next/face/__tests__/sync-runner.test.ts +0 -70
  86. package/src-next/face/__tests__/words.guard.test.ts +0 -93
  87. package/src-next/face/artifacts.ts +0 -195
  88. package/src-next/face/board-view.ts +0 -662
  89. package/src-next/face/capsule.ts +0 -149
  90. package/src-next/face/cli.ts +0 -819
  91. package/src-next/face/declare.ts +0 -326
  92. package/src-next/face/gate.ts +0 -170
  93. package/src-next/face/graph-view.ts +0 -74
  94. package/src-next/face/host.ts +0 -326
  95. package/src-next/face/lifecycle.ts +0 -700
  96. package/src-next/face/projection.ts +0 -282
  97. package/src-next/face/route-render.ts +0 -160
  98. package/src-next/face/words.ts +0 -296
  99. package/src-next/infra/__tests__/infra.test.ts +0 -287
  100. package/src-next/infra/git.ts +0 -39
  101. package/src-next/infra/process.ts +0 -34
  102. package/src-next/infra/runtime.ts +0 -185
  103. package/src-next/infra/workspace.ts +0 -232
  104. package/src-next/render/__tests__/render.test.ts +0 -499
  105. package/src-next/render/__tests__/skeleton.test.ts +0 -466
  106. package/src-next/render/brief.ts +0 -121
  107. package/src-next/render/issue-body.ts +0 -159
  108. package/src-next/render/skeleton.ts +0 -437
  109. package/src-next/render/templates.ts +0 -650
  110. package/src-next/session/__tests__/graph.test.ts +0 -270
  111. package/src-next/session/__tests__/handoff-plane.guard.test.ts +0 -48
  112. package/src-next/session/__tests__/handoff-schema.test.ts +0 -310
  113. package/src-next/session/__tests__/ledger.test.ts +0 -744
  114. package/src-next/session/__tests__/next.test.ts +0 -368
  115. package/src-next/session/__tests__/preflight.test.ts +0 -491
  116. package/src-next/session/__tests__/run.test.ts +0 -1014
  117. package/src-next/session/__tests__/wave-line-phase.guard.test.ts +0 -49
  118. package/src-next/session/__tests__/wave.test.ts +0 -469
  119. package/src-next/session/faces.ts +0 -110
  120. package/src-next/session/graph.ts +0 -411
  121. package/src-next/session/handoff-schema.ts +0 -373
  122. package/src-next/session/ledger.ts +0 -1004
  123. package/src-next/session/next.ts +0 -192
  124. package/src-next/session/preflight.ts +0 -240
  125. package/src-next/session/run.ts +0 -606
  126. package/src-next/session/state.ts +0 -30
  127. package/src-next/session/wave.ts +0 -139
@@ -0,0 +1,565 @@
1
+ // packages/cdd-engine/src-next/contract/doc.ts
2
+ // T4 — the contract plane's parse face (design spec §2.2: the DocType classes are
3
+ // pared down to parse + projection consumption + the cross-doc chain root; zero
4
+ // judgment methods on the class face).
5
+ //
6
+ // The four DocType classes own exactly three surfaces:
7
+ // · parse — structural extraction: overall → the four tables (File paths /
8
+ // Issue inventory / Phase inventory / Change history) + the
9
+ // dependency-graph edge lines; plan → the `### Task N:` blocks
10
+ // and their fields; phase-spec → the `## Design` double-layer
11
+ // skeleton (groups + items). The WHICH — which headings are
12
+ // sections, which lines are table rows, which lines are the
13
+ // declared column header — comes from the home extractors over
14
+ // the registry's declared anchors (home-extractors.ts, spec
15
+ // §3.2); this face only walks the resulting structure. Nothing
16
+ // is decided here — parse extracts, the invariant family judges.
17
+ // · projection — each class consumes the derived projection face (project.ts):
18
+ // the slices (parse regexes) and the shape (section skeleton) of
19
+ // its own doc type are the locating data every extraction walks.
20
+ // · chain root — the Class-A/B anchors of the document (the plan/spec head
21
+ // scalars `spec:` / `parent-program:` / `parent-version:` and
22
+ // the overall's Phase-inventory rows as the chain's anchor set)
23
+ // are extracted into a ChainRoot and LEFT as an interface — the
24
+ // resolution judgment belongs to the cross-doc-chain invariant,
25
+ // never to a DocType method.
26
+ //
27
+ // Module-level exports are types / the class family / one composition root — zero
28
+ // behavior-carrying bare functions (the plan's zero-bare-function discipline).
29
+ import { declaredRegistries } from "./declare.js";
30
+ import { DesignBodyExtractor, GraphExtractor, HeadingScanner, TableExtractor, TaskExtractor, } from "./home-extractors.js";
31
+ import { Projector } from "./project.js";
32
+ /** The projection carrier — one Projector instance over the declared registries,
33
+ * shared by the four parser classes (each binds its own doc-type faces). */
34
+ const projector = new Projector(declaredRegistries);
35
+ /** The home-driven extractors — the fixed structure rules of the task / design /
36
+ * graph / table / section homes (spec §3.2), shared by the parsers that read
37
+ * those surfaces. */
38
+ const taskExtractor = new TaskExtractor();
39
+ const designExtractor = new DesignBodyExtractor();
40
+ const graphExtractor = new GraphExtractor();
41
+ const tableExtractor = new TableExtractor();
42
+ const headingScanner = new HeadingScanner();
43
+ // ---------------------------------------------------------------------------
44
+ // the shared markdown primitives — one home for the link/token/table-row parsers
45
+ // ---------------------------------------------------------------------------
46
+ /**
47
+ * The shared extraction primitives: `[text](target)` links, `v<n>.<m>` version
48
+ * tokens and `|…|` table-row parsing. Both the parse face (DocType) and the
49
+ * judgment face (the Invariant base in invariants.ts) extend this base — the
50
+ * link/token/table parse logic lives in exactly one place of the new tree. The
51
+ * version-token grammar additionally exposes the public static `versionTokensOf`
52
+ * — the board's header-fact read (face/board-view.ts) reads the SAME grammar
53
+ * through it (one home, zero dual-write).
54
+ */
55
+ export class MarkdownPrimitives {
56
+ /** The `[text](target)` pairs parsed from one line — the target only (the
57
+ * retired link-text face; the remaining consumers — the overall's phase-cell
58
+ * links — resolve targets, never the text). */
59
+ linksOnLine(line) {
60
+ const links = [];
61
+ const linkPattern = /\[([^\]]*)\]\(([^)]+)\)/g;
62
+ for (const match of line.matchAll(linkPattern)) {
63
+ links.push({ target: match[2] });
64
+ }
65
+ return links;
66
+ }
67
+ /** The `v<major>.<minor>` tokens on one line — the version-token grammar's ONE
68
+ * home of the tree: the face plane's doc-line BLOCK token reads this public
69
+ * static; the subclasses keep the protected accessor below (a thin delegation,
70
+ * zero second grammar). */
71
+ static versionTokensOf(line) {
72
+ const tokens = [];
73
+ const tokenPattern = /v\d+\.\d+/g;
74
+ for (const match of line.matchAll(tokenPattern))
75
+ tokens.push(match[0]);
76
+ return tokens;
77
+ }
78
+ /** The `v<major>.<minor>` tokens on one line — the class-family accessor
79
+ * (the grammar itself is the static — one home). */
80
+ versionTokens(line) {
81
+ return MarkdownPrimitives.versionTokensOf(line);
82
+ }
83
+ /** The cells of one `|…|` table line (trimmed, wrapper bars excluded); null for a
84
+ * non-table line or a separator row. The separator-row rule is the
85
+ * TableExtractor's (the table home's fixed structure rule — one home). */
86
+ tableRowCells(line) {
87
+ const trimmed = line.trim();
88
+ if (!trimmed.startsWith("|") || !trimmed.endsWith("|"))
89
+ return null;
90
+ if (TableExtractor.isSeparatorRow(trimmed))
91
+ return null;
92
+ return trimmed
93
+ .split("|")
94
+ .slice(1, -1)
95
+ .map((cell) => cell.trim());
96
+ }
97
+ /** The non-separator `|…|` rows of a line run (the first row is the column
98
+ * header). The table-line / separator recognition is the TableExtractor's
99
+ * table-home rule; this method only splits the recognized rows into cells. */
100
+ tableRows(lines) {
101
+ const rows = [];
102
+ for (const line of tableExtractor.tableLinesOf(lines)) {
103
+ const cells = this.tableRowCells(line);
104
+ if (cells !== null)
105
+ rows.push([...cells]);
106
+ }
107
+ return rows;
108
+ }
109
+ }
110
+ // ---------------------------------------------------------------------------
111
+ // the DocType base — parse + projection consumption + chain root
112
+ // ---------------------------------------------------------------------------
113
+ /**
114
+ * The abstract doc-type base. Each subclass binds its registry-derived projection
115
+ * face (slices + shape) and implements parse — pure structural extraction into a
116
+ * typed record. The base carries the shared extraction primitives (heading blocks,
117
+ * table rows, header lines, `[text](target)` link parsing) as class methods: the
118
+ * class face stays judgment-free (zero validate/audit/detect methods).
119
+ */
120
+ export class DocType extends MarkdownPrimitives {
121
+ /** The doc-type record key — the projection-face identity. */
122
+ key;
123
+ /** The declared registry of this doc type — the extractors read their anchor
124
+ * rosters from it (the registry stays the single knowledge source). */
125
+ registry;
126
+ /** The derived parse face (per-element anchor slices) of this doc type. */
127
+ slices;
128
+ /** The derived section skeleton (shape projection) of this doc type. */
129
+ shape;
130
+ /** The per-anchor slice lookup — the parse face's locating patterns. */
131
+ #slicesByAnchor;
132
+ constructor(key) {
133
+ super();
134
+ this.key = key;
135
+ this.registry = declaredRegistries[key];
136
+ this.slices = projector.slices()[key];
137
+ this.shape = projector.shape()[key];
138
+ this.#slicesByAnchor = new Map(this.slices.slices.map((slice) => [slice.anchor, slice]));
139
+ }
140
+ // -------------------------------------------------------------------------
141
+ // shared extraction primitives (parse-only, never judgment)
142
+ // -------------------------------------------------------------------------
143
+ /** Split lines into heading blocks — a heading line plus its body up to the next heading. */
144
+ headingBlocks(lines) {
145
+ const blocks = [];
146
+ let openHeading = null;
147
+ let openRank = null;
148
+ let openBody = [];
149
+ const close = () => {
150
+ if (openHeading !== null && openRank !== null)
151
+ blocks.push({ heading: openHeading, rank: openRank, body: openBody });
152
+ openHeading = null;
153
+ openRank = null;
154
+ openBody = [];
155
+ };
156
+ for (const line of lines) {
157
+ const rank = this.headingRank(line);
158
+ if (rank !== null) {
159
+ close();
160
+ openHeading = line;
161
+ openRank = rank;
162
+ }
163
+ else if (openHeading !== null) {
164
+ openBody.push(line);
165
+ }
166
+ }
167
+ close();
168
+ return blocks;
169
+ }
170
+ /** The rank-2 section blocks in document order — the HeadingScanner's section
171
+ * walk over the registry's declared section anchors (spec §3.2: WHICH rank-2
172
+ * headings are sections comes from the registry, never a second hand-written
173
+ * filter here). An undeclared prose rank-2 heading is not a section, and a
174
+ * declared conditional `##` heading is one. */
175
+ sections(lines) {
176
+ return headingScanner.sectionsOf(this.registry, lines);
177
+ }
178
+ /** The `### Task N:` blocks in document order, with their field + step surfaces.
179
+ * The block-head / field-marker / step-line grammars live in the TaskExtractor
180
+ * (the task home's fixed structure rules over the registry's declared anchors):
181
+ * each block is extracted over its own lines, so the extractor's own scoping
182
+ * (the fields, and the steps riding inside the `**Steps**` field) yields that
183
+ * block's occurrence buckets directly — step recognition never re-appears here. */
184
+ taskBlocks(blocks) {
185
+ const out = [];
186
+ for (const block of blocks) {
187
+ const lines = [block.heading, ...block.body];
188
+ const extracted = taskExtractor.extract(this.registry, lines);
189
+ const headings = extracted["### Task N:"] ?? [];
190
+ if (headings.length === 0)
191
+ continue;
192
+ const ids = extracted["Task id token"] ?? [];
193
+ const id = Number(ids[0] ?? "");
194
+ if (Number.isNaN(id))
195
+ continue;
196
+ const fields = this.#taskFieldsOf(block.body, this.#taskFieldMarkers(extracted));
197
+ out.push({
198
+ id,
199
+ heading: block.heading,
200
+ fields,
201
+ steps: this.#taskStepsOf(extracted["Step action"] ?? [], new Set(extracted["Step checkable"] ?? [])),
202
+ });
203
+ }
204
+ return out;
205
+ }
206
+ /** The task-field anchor lookup — each declared field anchor's marker line maps
207
+ * to its anchor (the retired per-anchor field grammar collapses to one map). */
208
+ #taskFieldMarkers(extracted) {
209
+ const markers = new Map();
210
+ for (const [anchor, lines] of Object.entries(extracted)) {
211
+ if (!anchor.startsWith("**"))
212
+ continue;
213
+ for (const line of lines)
214
+ markers.set(line, anchor);
215
+ }
216
+ return markers;
217
+ }
218
+ /** Parse a task block's body into keyed fields — the marker membership comes
219
+ * from the extractor's field-anchor map; the remainder and continuation
220
+ * handling mirror the retired grammar's behavior exactly. */
221
+ #taskFieldsOf(body, markers) {
222
+ const fields = [];
223
+ let openKey = null;
224
+ let openLines = [];
225
+ const close = () => {
226
+ if (openKey !== null)
227
+ fields.push({ key: openKey, lines: openLines });
228
+ openKey = null;
229
+ openLines = [];
230
+ };
231
+ for (const line of body) {
232
+ const anchor = markers.get(line);
233
+ if (anchor !== undefined) {
234
+ close();
235
+ openKey = anchor.slice(2, -2);
236
+ openLines = [line.slice(`- ${anchor}:`.length).trim()];
237
+ }
238
+ else if (openKey !== null && line.trim().length > 0) {
239
+ openLines.push(line.trim());
240
+ }
241
+ }
242
+ close();
243
+ return fields;
244
+ }
245
+ /** Parse a block's recognized step lines into step records — the lines come
246
+ * from the extractor's `Step action` bucket (the registry's `^- ` shape, so
247
+ * no `- `-bullet re-recognition here); the action cell is a value read after
248
+ * the anchor's bullet prefix (mirroring the `#taskIdOf` slot read), and
249
+ * membership in the `Step checkable` bucket marks which lines carry a
250
+ * verbatim `— checkable:` clause that the split then reads off. */
251
+ #taskStepsOf(stepLines, checkableLines) {
252
+ const steps = [];
253
+ for (const line of stepLines) {
254
+ const text = line.trim().slice(2).trim();
255
+ const checkableMarker = checkableLines.has(line) ? text.indexOf("— checkable:") : -1;
256
+ if (checkableMarker === -1) {
257
+ steps.push({ action: text, checkable: null });
258
+ }
259
+ else {
260
+ steps.push({
261
+ action: text.slice(0, checkableMarker).trim(),
262
+ checkable: text.slice(checkableMarker + "— checkable:".length).trim(),
263
+ });
264
+ }
265
+ }
266
+ return steps;
267
+ }
268
+ /** Parse a section's table: the column-header row + the data rows. The header
269
+ * row is the one the registry's `… columns` anchors claim (the TableExtractor's
270
+ * declared-home set); a table with no registered column anchor falls back to
271
+ * the first row, the shape's positional default. The data rows are every
272
+ * remaining row plus any leading row ahead of the declared header — a
273
+ * mispositioned header never silently drops a data row. */
274
+ parseTable(lines) {
275
+ const rows = this.tableRows(lines);
276
+ const declaredHeader = tableExtractor.headerLineOf(this.registry, lines);
277
+ if (declaredHeader === null) {
278
+ const headerRow = rows.length > 0 ? rows[0] : null;
279
+ return { heading: "", headerRow, rows: rows.slice(1) };
280
+ }
281
+ const headerCells = this.tableRowCells(declaredHeader);
282
+ const dataRows = rows.filter((row) => row.join("|") !== (headerCells ?? []).join("|"));
283
+ return { heading: "", headerRow: headerCells, rows: dataRows };
284
+ }
285
+ /** The slice of one registered anchor (undefined when the anchor is not registered here). */
286
+ sliceOf(anchor) {
287
+ return this.#slicesByAnchor.get(anchor);
288
+ }
289
+ /** Whether a heading line conforms to a declared heading anchor's value shape. */
290
+ sectionConforms(heading, anchor) {
291
+ const slice = this.#slicesByAnchor.get(anchor);
292
+ if (slice?.valuePattern !== undefined)
293
+ return slice.valuePattern.test(heading);
294
+ return heading.startsWith(anchor);
295
+ }
296
+ headingRank(line) {
297
+ const match = line.match(/^(#+)\s/);
298
+ if (match === null)
299
+ return null;
300
+ const rank = match[1].length;
301
+ return rank <= 4 ? rank : null;
302
+ }
303
+ }
304
+ // ---------------------------------------------------------------------------
305
+ // the four concrete doc types
306
+ // ---------------------------------------------------------------------------
307
+ /**
308
+ * The overall doc type — parses the header, the four tables and the dependency
309
+ * graph, and exposes the Phase-inventory rows as the chain's anchor set.
310
+ */
311
+ export class OverallDocType extends DocType {
312
+ docTypeName = "overall-spec";
313
+ parse(lines, head = null) {
314
+ const title = head?.title ?? "";
315
+ const sections = this.sections(lines);
316
+ const tables = {
317
+ "File paths": this.#tableSection(sections, "## File paths"),
318
+ "Issue inventory": this.#tableSection(sections, "## Issue inventory"),
319
+ "Phase inventory": this.#tableSection(sections, "## Phase inventory"),
320
+ "Change history": this.#tableSection(sections, "## Change history"),
321
+ };
322
+ const graphEdges = this.#graphEdges(sections);
323
+ const phases = this.#phaseRows(tables["Phase inventory"]);
324
+ return {
325
+ docType: "overall-spec",
326
+ head,
327
+ title,
328
+ sections,
329
+ tables,
330
+ graphEdges,
331
+ chain: {
332
+ docType: "overall-spec",
333
+ parentLink: null,
334
+ specLink: null,
335
+ parentTokens: [],
336
+ phases,
337
+ dependsOn: null,
338
+ },
339
+ };
340
+ }
341
+ /** The `## Dependency graph` edge lines — the graph-home occurrence map (the
342
+ * declared Hard/Soft edge anchors) identified by the extractor; the from/to
343
+ * token grammar stays the preserved graph-edge primitive. */
344
+ #graphEdges(sections) {
345
+ for (const section of sections) {
346
+ if (!this.sectionConforms(section.heading, "## Dependency graph"))
347
+ continue;
348
+ const extracted = graphExtractor.extract(this.registry, section.lines);
349
+ const edgeLines = new Set([
350
+ ...(extracted["Hard edge"] ?? []),
351
+ ...(extracted["Soft edge"] ?? []),
352
+ ]);
353
+ const edges = [];
354
+ const edgePattern = /^P(\d+(?:\.\d+)*)\s*->\s*P(\d+(?:\.\d+)*)$/;
355
+ for (const line of section.lines) {
356
+ const trimmed = line.trim();
357
+ if (!edgeLines.has(trimmed))
358
+ continue;
359
+ const match = trimmed.match(edgePattern);
360
+ if (match !== null)
361
+ edges.push({ text: trimmed, from: `P${match[1]}`, to: `P${match[2]}` });
362
+ }
363
+ return edges;
364
+ }
365
+ return [];
366
+ }
367
+ /** The Phase-inventory rows as chain phases — header-driven column mapping. */
368
+ #phaseRows(table) {
369
+ if (table.headerRow === null)
370
+ return [];
371
+ const columns = new Map();
372
+ for (let index = 0; index < table.headerRow.length; index++) {
373
+ columns.set(table.headerRow[index].toLowerCase(), index);
374
+ }
375
+ const designIdx = columns.get("design spec");
376
+ const planIdx = columns.get("implementation plan");
377
+ const dependencyIdx = columns.get("dependency");
378
+ if (columns.get("phase") === undefined)
379
+ return [];
380
+ const phases = [];
381
+ for (const row of table.rows) {
382
+ const id = this.#phaseId(row);
383
+ if (id === "")
384
+ continue;
385
+ phases.push({
386
+ id,
387
+ designCell: designIdx !== undefined ? (row[designIdx] ?? "") : "",
388
+ planCell: planIdx !== undefined ? (row[planIdx] ?? "") : "",
389
+ dependencyCell: dependencyIdx !== undefined ? (row[dependencyIdx] ?? "") : "",
390
+ });
391
+ }
392
+ return phases;
393
+ }
394
+ /** The phase id of a Phase-inventory data row — the cell carrying a phase-id
395
+ * token (the token shape judged through the declared `Phase id token` value
396
+ * pattern — the retired literal grammar now sourced from the registry). */
397
+ #phaseId(row) {
398
+ const pattern = this.sliceOf("Phase id token")?.valuePattern;
399
+ const idCell = row.find((cell) => pattern?.test(cell.trim()) === true);
400
+ return idCell === undefined ? "" : idCell.trim();
401
+ }
402
+ /** The parsed table of one overall table section (empty when the section is absent). */
403
+ #tableSection(sections, heading) {
404
+ for (const section of sections) {
405
+ if (this.sectionConforms(section.heading, heading)) {
406
+ const table = this.parseTable(section.lines);
407
+ return { heading: section.heading, headerRow: table.headerRow, rows: table.rows };
408
+ }
409
+ }
410
+ return { heading: "", headerRow: null, rows: [] };
411
+ }
412
+ }
413
+ /**
414
+ * The plan doc type — parses the head (Class-A `spec:` + Class-B parent
415
+ * lineage) and the `### Task N:` task blocks.
416
+ */
417
+ export class PlanDocType extends DocType {
418
+ docTypeName = "plan";
419
+ parse(lines, head = null) {
420
+ const title = head?.title ?? "";
421
+ const blocks = this.headingBlocks(lines);
422
+ return {
423
+ docType: "plan",
424
+ head,
425
+ title,
426
+ sections: this.sections(lines),
427
+ taskBlocks: this.taskBlocks(blocks),
428
+ chain: this.chainRoot(head),
429
+ };
430
+ }
431
+ /** The plan's cross-doc chain root — the Class-A `spec:` + Class-B
432
+ * `parent-program:`/`parent-version:` head scalars (the §2.2 delivery seam:
433
+ * the chain facts ride the typed head, never a body line scan). */
434
+ chainRoot(head) {
435
+ return {
436
+ docType: "plan",
437
+ parentLink: head === null || head.parentProgram === null ? null : { target: head.parentProgram },
438
+ specLink: head === null || head.spec === null ? null : { target: head.spec },
439
+ parentTokens: head === null || head.parentVersion === null ? [] : [head.parentVersion],
440
+ phases: [],
441
+ dependsOn: head?.dependsOn ?? null,
442
+ };
443
+ }
444
+ }
445
+ /**
446
+ * The phase-spec doc type — parses the header five-tuple surface and the
447
+ * `## Design` double-layer skeleton (groups + items).
448
+ */
449
+ export class PhaseSpecDocType extends DocType {
450
+ docTypeName = "phase-spec";
451
+ parse(lines, head = null) {
452
+ const title = head?.title ?? "";
453
+ const blocks = this.headingBlocks(lines);
454
+ return {
455
+ docType: "phase-spec",
456
+ head,
457
+ title,
458
+ sections: this.sections(lines),
459
+ design: this.designFromBlocks(blocks),
460
+ chain: this.chainRoot(head),
461
+ };
462
+ }
463
+ /** The design double-layer skeleton — the `### N.` groups + their `#### N.M`
464
+ * items between the `## Design` section and the next rank-2 heading. The
465
+ * numbered-heading grammars (and their number/text decomposition) live in the
466
+ * DesignBodyExtractor; this method walks the declared groups/items from its
467
+ * occurrence map. */
468
+ designFromBlocks(blocks) {
469
+ const lines = blocks.flatMap((block) => [block.heading, ...block.body]);
470
+ const extracted = designExtractor.extract(this.registry, lines);
471
+ const designHeadings = new Set(extracted["## Design"] ?? []);
472
+ const groupHeadings = new Set(extracted["### N. group heading"] ?? []);
473
+ const itemHeadings = new Set(extracted["#### N.M item heading"] ?? []);
474
+ const groups = [];
475
+ let openNumber = null;
476
+ let openHeading = "";
477
+ let openItems = [];
478
+ let inDesign = false;
479
+ const close = () => {
480
+ if (openNumber !== null) {
481
+ groups.push({ number: openNumber, heading: openHeading, items: openItems });
482
+ }
483
+ openNumber = null;
484
+ openHeading = "";
485
+ openItems = [];
486
+ };
487
+ for (const block of blocks) {
488
+ const rank = this.headingRank(block.heading);
489
+ if (rank === 2) {
490
+ if (inDesign)
491
+ break;
492
+ if (designHeadings.has(block.heading))
493
+ inDesign = true;
494
+ continue;
495
+ }
496
+ if (!inDesign || (rank !== 3 && rank !== 4))
497
+ continue;
498
+ if (groupHeadings.has(block.heading)) {
499
+ close();
500
+ const group = designExtractor.groupOf(block.heading);
501
+ openNumber = group.number;
502
+ openHeading = group.heading;
503
+ continue;
504
+ }
505
+ if (openNumber !== null && itemHeadings.has(block.heading)) {
506
+ openItems.push(designExtractor.itemOf(block.heading));
507
+ }
508
+ }
509
+ close();
510
+ return groups;
511
+ }
512
+ /** The phase-spec's cross-doc chain root: the Class-B `parent-program:`
513
+ * `parent-version:` head scalars. */
514
+ chainRoot(head) {
515
+ return {
516
+ docType: "phase-spec",
517
+ parentLink: head === null || head.parentProgram === null ? null : { target: head.parentProgram },
518
+ specLink: null,
519
+ parentTokens: head === null || head.parentVersion === null ? [] : [head.parentVersion],
520
+ phases: [],
521
+ dependsOn: head?.dependsOn ?? null,
522
+ };
523
+ }
524
+ }
525
+ /**
526
+ * The single-spec doc type — parses the header five-tuple surface and the prose
527
+ * section surface. A single-spec carries no parent overall and no `### N.`
528
+ * design outline, so the parse degrades the chain root to its null-link face
529
+ * (the `depends-on:` front-matter value is the only chain fact carried).
530
+ */
531
+ export class SingleSpecDocType extends DocType {
532
+ docTypeName = "single-spec";
533
+ parse(lines, head = null) {
534
+ const title = head?.title ?? "";
535
+ return {
536
+ docType: "single-spec",
537
+ head,
538
+ title,
539
+ sections: this.sections(lines),
540
+ chain: this.chainRoot(head),
541
+ };
542
+ }
543
+ /** The single-spec chain root — the degraded face: no parent link / no spec
544
+ * link (the independent-program shape), the `depends-on:` value only. */
545
+ chainRoot(head) {
546
+ return {
547
+ docType: "single-spec",
548
+ parentLink: null,
549
+ specLink: null,
550
+ parentTokens: [],
551
+ phases: [],
552
+ dependsOn: head?.dependsOn ?? null,
553
+ };
554
+ }
555
+ }
556
+ // ---------------------------------------------------------------------------
557
+ // composition root — the four parsers by doc-key
558
+ // ---------------------------------------------------------------------------
559
+ /** The composed doc-type parsers — the judge's ctx-loading parsers (one per doc key). */
560
+ export const docTypeParsers = {
561
+ "overall-spec": new OverallDocType("overall-spec"),
562
+ plan: new PlanDocType("plan"),
563
+ "phase-spec": new PhaseSpecDocType("phase-spec"),
564
+ "single-spec": new SingleSpecDocType("single-spec"),
565
+ };