@oscaner-skills/cdd-engine 3.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 (143) hide show
  1. package/{src-next/bin.ts → dist/bin.js} +18 -21
  2. package/dist/contract/declare.js +998 -0
  3. package/dist/contract/doc.js +565 -0
  4. package/dist/contract/frontmatter.js +209 -0
  5. package/dist/contract/home-extractors.js +379 -0
  6. package/dist/contract/invariants.js +1030 -0
  7. package/dist/contract/judge.js +109 -0
  8. package/dist/contract/lint.js +206 -0
  9. package/dist/contract/project.js +371 -0
  10. package/dist/contract/skill-anatomy.js +156 -0
  11. package/dist/contract/translate.js +85 -0
  12. package/dist/face/artifacts.js +189 -0
  13. package/dist/face/board-view.js +522 -0
  14. package/dist/face/capsule.js +141 -0
  15. package/dist/face/cli.js +891 -0
  16. package/dist/face/declare.js +241 -0
  17. package/dist/face/gate.js +158 -0
  18. package/dist/face/graph-view.js +66 -0
  19. package/dist/face/host.js +211 -0
  20. package/dist/face/lifecycle.js +603 -0
  21. package/dist/face/preview.js +136 -0
  22. package/dist/face/projection.js +259 -0
  23. package/dist/face/route-render.js +162 -0
  24. package/dist/face/termination.js +482 -0
  25. package/dist/face/words.js +220 -0
  26. package/{src-next/infra/config.ts → dist/infra/config.js} +19 -24
  27. package/{src-next/infra/doc-roots.ts → dist/infra/doc-roots.js} +3 -13
  28. package/dist/infra/git.js +37 -0
  29. package/dist/infra/process.js +22 -0
  30. package/{src-next/infra/root.ts → dist/infra/root.js} +25 -36
  31. package/dist/infra/runtime.js +85 -0
  32. package/dist/infra/workspace.js +276 -0
  33. package/dist/render/brief.js +82 -0
  34. package/dist/render/issue-body.js +129 -0
  35. package/dist/render/skeleton.js +434 -0
  36. package/dist/render/templates.js +520 -0
  37. package/dist/session/faces.js +38 -0
  38. package/dist/session/graph.js +309 -0
  39. package/dist/session/handoff-schema.js +295 -0
  40. package/dist/session/ledger.js +762 -0
  41. package/dist/session/next.js +211 -0
  42. package/dist/session/preflight.js +194 -0
  43. package/dist/session/round-naming.js +73 -0
  44. package/dist/session/run.js +441 -0
  45. package/dist/session/state.js +8 -0
  46. package/dist/session/wave.js +92 -0
  47. package/package.json +5 -5
  48. package/src-next/__tests__/bin.test.ts +0 -128
  49. package/src-next/__tests__/dead-decl.guard.test.ts +0 -39
  50. package/src-next/__tests__/floor.guard.test.ts +0 -69
  51. package/src-next/__tests__/issue-body.guard.test.ts +0 -66
  52. package/src-next/__tests__/phase-suffix.guard.test.ts +0 -72
  53. package/src-next/__tests__/smoke.integration.test.ts +0 -185
  54. package/src-next/__tests__/support/strip-comments.ts +0 -99
  55. package/src-next/__tests__/zero-dep.test.ts +0 -94
  56. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +0 -256
  57. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +0 -165
  58. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +0 -190
  59. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +0 -106
  60. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +0 -240
  61. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +0 -165
  62. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +0 -190
  63. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +0 -100
  64. package/src-next/contract/__tests__/declare.test.ts +0 -481
  65. package/src-next/contract/__tests__/doc.test.ts +0 -527
  66. package/src-next/contract/__tests__/dockey.guard.test.ts +0 -58
  67. package/src-next/contract/__tests__/edge-conditions.guard.test.ts +0 -81
  68. package/src-next/contract/__tests__/frontmatter.test.ts +0 -164
  69. package/src-next/contract/__tests__/judge.test.ts +0 -1111
  70. package/src-next/contract/__tests__/lint.test.ts +0 -324
  71. package/src-next/contract/__tests__/project.test.ts +0 -460
  72. package/src-next/contract/__tests__/structure-pin.test.ts +0 -186
  73. package/src-next/contract/__tests__/translate.test.ts +0 -96
  74. package/src-next/contract/declare.ts +0 -1071
  75. package/src-next/contract/doc.ts +0 -816
  76. package/src-next/contract/frontmatter.ts +0 -233
  77. package/src-next/contract/home-extractors.ts +0 -397
  78. package/src-next/contract/invariants.ts +0 -1413
  79. package/src-next/contract/judge.ts +0 -151
  80. package/src-next/contract/lint.ts +0 -239
  81. package/src-next/contract/project.ts +0 -656
  82. package/src-next/contract/skill-anatomy.ts +0 -301
  83. package/src-next/contract/translate.ts +0 -113
  84. package/src-next/face/__tests__/board-view.test.ts +0 -1151
  85. package/src-next/face/__tests__/capsule.test.ts +0 -300
  86. package/src-next/face/__tests__/channel-closure.guard.test.ts +0 -129
  87. package/src-next/face/__tests__/cli.test.ts +0 -4897
  88. package/src-next/face/__tests__/face.test.ts +0 -289
  89. package/src-next/face/__tests__/graph-view.test.ts +0 -61
  90. package/src-next/face/__tests__/host.test.ts +0 -24
  91. package/src-next/face/__tests__/install-rows.guard.test.ts +0 -58
  92. package/src-next/face/__tests__/negation.ts +0 -6
  93. package/src-next/face/__tests__/preview.test.ts +0 -374
  94. package/src-next/face/__tests__/projection.test.ts +0 -303
  95. package/src-next/face/__tests__/repo-root.guard.test.ts +0 -120
  96. package/src-next/face/__tests__/termination.test.ts +0 -650
  97. package/src-next/face/__tests__/words.guard.test.ts +0 -93
  98. package/src-next/face/artifacts.ts +0 -248
  99. package/src-next/face/board-view.ts +0 -652
  100. package/src-next/face/capsule.ts +0 -163
  101. package/src-next/face/cli.ts +0 -1028
  102. package/src-next/face/declare.ts +0 -323
  103. package/src-next/face/gate.ts +0 -171
  104. package/src-next/face/graph-view.ts +0 -74
  105. package/src-next/face/host.ts +0 -302
  106. package/src-next/face/lifecycle.ts +0 -725
  107. package/src-next/face/preview.ts +0 -151
  108. package/src-next/face/projection.ts +0 -285
  109. package/src-next/face/route-render.ts +0 -185
  110. package/src-next/face/termination.ts +0 -573
  111. package/src-next/face/words.ts +0 -314
  112. package/src-next/infra/__tests__/infra.test.ts +0 -333
  113. package/src-next/infra/__tests__/root.test.ts +0 -56
  114. package/src-next/infra/git.ts +0 -39
  115. package/src-next/infra/process.ts +0 -34
  116. package/src-next/infra/runtime.ts +0 -132
  117. package/src-next/infra/workspace.ts +0 -322
  118. package/src-next/render/__tests__/render.test.ts +0 -550
  119. package/src-next/render/__tests__/skeleton.test.ts +0 -684
  120. package/src-next/render/brief.ts +0 -121
  121. package/src-next/render/issue-body.ts +0 -162
  122. package/src-next/render/skeleton.ts +0 -502
  123. package/src-next/render/templates.ts +0 -645
  124. package/src-next/session/__tests__/graph.test.ts +0 -277
  125. package/src-next/session/__tests__/handoff-plane.guard.test.ts +0 -48
  126. package/src-next/session/__tests__/handoff-schema.test.ts +0 -310
  127. package/src-next/session/__tests__/ledger.test.ts +0 -745
  128. package/src-next/session/__tests__/next.test.ts +0 -460
  129. package/src-next/session/__tests__/preflight.test.ts +0 -545
  130. package/src-next/session/__tests__/round-naming.test.ts +0 -142
  131. package/src-next/session/__tests__/run.test.ts +0 -1026
  132. package/src-next/session/__tests__/wave-line-phase.guard.test.ts +0 -49
  133. package/src-next/session/__tests__/wave.test.ts +0 -476
  134. package/src-next/session/faces.ts +0 -110
  135. package/src-next/session/graph.ts +0 -411
  136. package/src-next/session/handoff-schema.ts +0 -373
  137. package/src-next/session/ledger.ts +0 -1076
  138. package/src-next/session/next.ts +0 -293
  139. package/src-next/session/preflight.ts +0 -271
  140. package/src-next/session/round-naming.ts +0 -84
  141. package/src-next/session/run.ts +0 -610
  142. package/src-next/session/state.ts +0 -30
  143. package/src-next/session/wave.ts +0 -139
@@ -1,816 +0,0 @@
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
-
30
- import type { ElementRegistry } from "./declare.ts";
31
- import { declaredRegistries } from "./declare.ts";
32
- import type { FrontMatterHead } from "./frontmatter.ts";
33
- import type { ExtractionMap } from "./home-extractors.ts";
34
- import {
35
- DesignBodyExtractor,
36
- GraphExtractor,
37
- HeadingScanner,
38
- TableExtractor,
39
- TaskExtractor,
40
- } from "./home-extractors.ts";
41
- import type { DocKey, DocShape, DocSlices, ElementSlice } from "./project.ts";
42
- import { Projector } from "./project.ts";
43
-
44
- /** The projection carrier — one Projector instance over the declared registries,
45
- * shared by the four parser classes (each binds its own doc-type faces). */
46
- const projector = new Projector(declaredRegistries);
47
-
48
- /** The home-driven extractors — the fixed structure rules of the task / design /
49
- * graph / table / section homes (spec §3.2), shared by the parsers that read
50
- * those surfaces. */
51
- const taskExtractor = new TaskExtractor();
52
- const designExtractor = new DesignBodyExtractor();
53
- const graphExtractor = new GraphExtractor();
54
- const tableExtractor = new TableExtractor();
55
- const headingScanner = new HeadingScanner();
56
-
57
- // ---------------------------------------------------------------------------
58
- // shared structural types
59
- // ---------------------------------------------------------------------------
60
-
61
- /** The markdown heading rank (the count of leading `#`s). */
62
- type HeadingRank = 1 | 2 | 3 | 4;
63
-
64
- /** One heading block of the document — a heading line and the lines up to the next heading. */
65
- export interface HeadingBlock {
66
- /** The heading line verbatim, leading `#`s included. */
67
- heading: string;
68
- /** The heading's markdown rank. */
69
- rank: HeadingRank;
70
- /** The block's body lines (excluding the heading line). */
71
- body: readonly string[];
72
- }
73
-
74
- /** One `##`-ranked section of the document. */
75
- export interface SectionBlock {
76
- /** The section's heading line verbatim (e.g. "## Document scope"). */
77
- heading: string;
78
- /** The section's body lines (up to the next `##`-ranked heading). */
79
- lines: readonly string[];
80
- }
81
-
82
- /** A markdown table parsed from a section: the column header plus its data rows. */
83
- export interface ParsedTable {
84
- /** The table's section heading line (e.g. "## Phase inventory"). */
85
- heading: string;
86
- /** The column-header row (the first non-separator table line), when present. */
87
- headerRow: readonly string[] | null;
88
- /** The data rows — every non-separator table line after the header row. */
89
- rows: readonly string[][];
90
- }
91
-
92
- // ---------------------------------------------------------------------------
93
- // the root-level parse records
94
- // ---------------------------------------------------------------------------
95
-
96
- /** One dependency-graph edge line (`P<n> -> P<m>`) parsed verbatim. */
97
- export interface GraphEdge {
98
- /** The edge line verbatim. */
99
- text: string;
100
- /** The edge's from-phase token (the leading `P<n>` — a `.digits` suffix included). */
101
- from: string;
102
- /** The edge's to-phase token. */
103
- to: string;
104
- }
105
-
106
- /** One parsed phase-inventory row of the overall (the chain-root anchor set). */
107
- export interface ChainPhase {
108
- /** The registered phase id (e.g. "P2.1"). */
109
- id: string;
110
- /** The Design-spec cell text (link tokens, e.g. a spec-root link under the
111
- * declared spec doc root — `[P2-design](<spec-root>/x-design.md)`). */
112
- designCell: string;
113
- /** The Implementation-plan cell text (link tokens, e.g. a plan-root link under
114
- * the declared plan doc root — `[plan](<plan-root>/x.md)`). */
115
- planCell: string;
116
- /** The Dependency cell text (e.g. "P1 -> P2"). */
117
- dependencyCell: string;
118
- }
119
-
120
- /** A `[text](target)` link parsed from a line — only the target surfaces: the
121
- * link-text face retired with the front-matter flip (the chain root reads the
122
- * head scalars, and the drift judgments are gone — zero consumer ever reads the
123
- * text part). */
124
- export interface ChainLink {
125
- /** The link's target path. */
126
- target: string;
127
- }
128
-
129
- /**
130
- * The cross-doc chain root — the Class-A/B anchors a document carries, read from
131
- * the front-matter head scalars (the §2.3 key set: `spec:` · `parent-program:` ·
132
- * `parent-version:` · `depends-on:`), plus the overall's Phase-inventory rows.
133
- * Extracted and LEFT as an interface — every resolution judgment (target
134
- * existence, version-token lineage membership) belongs to the cross-doc-chain /
135
- * file-existence / sibling-scan invariants, never to a DocType method.
136
- */
137
- export interface ChainRoot {
138
- /** The doc-type identity of the chain root's document. */
139
- docType: DocKey;
140
- /** The `parent-program:` link (Class-B) — the parent overall reference of a
141
- * plan/spec document; null for the overall (the chain root itself). */
142
- parentLink: ChainLink | null;
143
- /** The `spec:` link (Class-A) — the plan's design-spec reference; null for the
144
- * overall (no spec to reference) and for a spec (the document IS the design spec). */
145
- specLink: ChainLink | null;
146
- /** The version tokens carried on the `parent-program:` key (Class-B lineage). */
147
- parentTokens: readonly string[];
148
- /** The overall's phase-inventory rows — the chain's anchor set (overall only). */
149
- phases: readonly ChainPhase[];
150
- /** The `depends-on:` front-matter value (plan/spec), verbatim, when the key is present. */
151
- dependsOn: string | null;
152
- }
153
-
154
- /** The overall parse record — the four tables, the graph edges and the chain root. */
155
- export interface OverallParsed {
156
- docType: "overall-spec";
157
- /** The document's front-matter head — the typed head record (the §2.3 key set),
158
- * or null when parsed without one (the chainDocs producers MUST parse
159
- * dual-param — a head-less plan/spec parse reads a null chain face). */
160
- head: FrontMatterHead | null;
161
- /** The document title — the front-matter `title:` scalar ("" without a head). */
162
- title: string;
163
- /** The `##`-ranked sections in document order. */
164
- sections: readonly SectionBlock[];
165
- /** The parsed overall tables (each present only when its section was found). */
166
- tables: {
167
- "File paths": ParsedTable;
168
- "Issue inventory": ParsedTable;
169
- "Phase inventory": ParsedTable;
170
- "Change history": ParsedTable;
171
- };
172
- /** The dependency-graph edge lines under `## Dependency graph`. */
173
- graphEdges: readonly GraphEdge[];
174
- /** The overall's cross-doc chain root (its Phase-inventory rows are the anchor set). */
175
- chain: ChainRoot;
176
- }
177
-
178
- /** One parsed `- **Key**:` field of a task block. */
179
- export interface TaskField {
180
- /** The field key (Objective / Files / Consumes / Produces / Steps / Acceptance / DependsOn). */
181
- key: string;
182
- /** The field's value lines — the marker line's remainder plus its continuation lines. */
183
- lines: readonly string[];
184
- }
185
-
186
- /** One parsed step line of a task block's `**Steps**` field. */
187
- export interface TaskStep {
188
- /** The step's action text (after the leading `- `). */
189
- action: string;
190
- /** The step's `— checkable:` clause text, when the line carries one. */
191
- checkable: string | null;
192
- }
193
-
194
- /** One parsed `### Task N:` block. */
195
- export interface TaskBlock {
196
- /** The task number N. */
197
- id: number;
198
- /** The `### Task N: …` heading line verbatim. */
199
- heading: string;
200
- /** The block's keyed fields in document order. */
201
- fields: readonly TaskField[];
202
- /** The parsed `**Steps**` bullets. */
203
- steps: readonly TaskStep[];
204
- }
205
-
206
- /** The plan parse record — the header, the constraints section and the task blocks. */
207
- export interface PlanParsed {
208
- docType: "plan";
209
- /** The document's front-matter head, or null when parsed without one. */
210
- head: FrontMatterHead | null;
211
- /** The document title — the front-matter `title:` scalar ("" without a head). */
212
- title: string;
213
- sections: readonly SectionBlock[];
214
- /** The `### Task N:` blocks in document order. */
215
- taskBlocks: readonly TaskBlock[];
216
- chain: ChainRoot;
217
- }
218
-
219
- /** One `### N.` design group and its `#### N.M` items (the phase-spec skeleton). */
220
- export interface DesignGroup {
221
- /** The group's leading number token (`1` for `### 1. …`). */
222
- number: string;
223
- /** The group's heading text (after the number token). */
224
- heading: string;
225
- /** The group's items in document order. */
226
- items: readonly DesignItem[];
227
- }
228
-
229
- /** One `#### N.M` design item. */
230
- export interface DesignItem {
231
- /** The item's number token (`1.2` for `#### 1.2 …`). */
232
- number: string;
233
- /** The item's heading text. */
234
- heading: string;
235
- }
236
-
237
- /** The phase-spec parse record — the header tuple and the design-body skeleton. */
238
- export interface PhaseSpecParsed {
239
- docType: "phase-spec";
240
- /** The document's front-matter head, or null when parsed without one. */
241
- head: FrontMatterHead | null;
242
- /** The document title — the front-matter `title:` scalar ("" without a head). */
243
- title: string;
244
- sections: readonly SectionBlock[];
245
- /** The `## Design` double-layer skeleton (groups + items), when the section is present. */
246
- design: readonly DesignGroup[];
247
- chain: ChainRoot;
248
- }
249
-
250
- /** The single-spec parse record — the header five-tuple and the prose section surface. */
251
- export interface SingleSpecParsed {
252
- docType: "single-spec";
253
- /** The document's front-matter head, or null when parsed without one. */
254
- head: FrontMatterHead | null;
255
- /** The document title — the front-matter `title:` scalar ("" without a head). */
256
- title: string;
257
- sections: readonly SectionBlock[];
258
- chain: ChainRoot;
259
- }
260
-
261
- /** The parsed-document union — one record per doc type. */
262
- export type ParsedDoc = OverallParsed | PlanParsed | PhaseSpecParsed | SingleSpecParsed;
263
-
264
- // ---------------------------------------------------------------------------
265
- // the shared markdown primitives — one home for the link/token/table-row parsers
266
- // ---------------------------------------------------------------------------
267
-
268
- /**
269
- * The shared extraction primitives: `[text](target)` links, `v<n>.<m>` version
270
- * tokens and `|…|` table-row parsing. Both the parse face (DocType) and the
271
- * judgment face (the Invariant base in invariants.ts) extend this base — the
272
- * link/token/table parse logic lives in exactly one place of the new tree. The
273
- * version-token grammar additionally exposes the public static `versionTokensOf`
274
- * — the board's header-fact read (face/board-view.ts) reads the SAME grammar
275
- * through it (one home, zero dual-write).
276
- */
277
- export abstract class MarkdownPrimitives {
278
- /** The `[text](target)` pairs parsed from one line — the target only (the
279
- * retired link-text face; the remaining consumers — the overall's phase-cell
280
- * links — resolve targets, never the text). */
281
- protected linksOnLine(line: string): readonly ChainLink[] {
282
- const links: ChainLink[] = [];
283
- const linkPattern = /\[([^\]]*)\]\(([^)]+)\)/g;
284
- for (const match of line.matchAll(linkPattern)) {
285
- links.push({ target: match[2] });
286
- }
287
- return links;
288
- }
289
-
290
- /** The `v<major>.<minor>` tokens on one line — the version-token grammar's ONE
291
- * home of the tree: the face plane's doc-line BLOCK token reads this public
292
- * static; the subclasses keep the protected accessor below (a thin delegation,
293
- * zero second grammar). */
294
- static versionTokensOf(line: string): readonly string[] {
295
- const tokens: string[] = [];
296
- const tokenPattern = /v\d+\.\d+/g;
297
- for (const match of line.matchAll(tokenPattern)) tokens.push(match[0]);
298
- return tokens;
299
- }
300
-
301
- /** The `v<major>.<minor>` tokens on one line — the class-family accessor
302
- * (the grammar itself is the static — one home). */
303
- protected versionTokens(line: string): readonly string[] {
304
- return MarkdownPrimitives.versionTokensOf(line);
305
- }
306
-
307
- /** The cells of one `|…|` table line (trimmed, wrapper bars excluded); null for a
308
- * non-table line or a separator row. The separator-row rule is the
309
- * TableExtractor's (the table home's fixed structure rule — one home). */
310
- protected tableRowCells(line: string): readonly string[] | null {
311
- const trimmed = line.trim();
312
- if (!trimmed.startsWith("|") || !trimmed.endsWith("|")) return null;
313
- if (TableExtractor.isSeparatorRow(trimmed)) return null;
314
- return trimmed
315
- .split("|")
316
- .slice(1, -1)
317
- .map((cell) => cell.trim());
318
- }
319
-
320
- /** The non-separator `|…|` rows of a line run (the first row is the column
321
- * header). The table-line / separator recognition is the TableExtractor's
322
- * table-home rule; this method only splits the recognized rows into cells. */
323
- protected tableRows(lines: readonly string[]): readonly string[][] {
324
- const rows: string[][] = [];
325
- for (const line of tableExtractor.tableLinesOf(lines)) {
326
- const cells = this.tableRowCells(line);
327
- if (cells !== null) rows.push([...cells]);
328
- }
329
- return rows;
330
- }
331
- }
332
-
333
- // ---------------------------------------------------------------------------
334
- // the DocType base — parse + projection consumption + chain root
335
- // ---------------------------------------------------------------------------
336
-
337
- /**
338
- * The abstract doc-type base. Each subclass binds its registry-derived projection
339
- * face (slices + shape) and implements parse — pure structural extraction into a
340
- * typed record. The base carries the shared extraction primitives (heading blocks,
341
- * table rows, header lines, `[text](target)` link parsing) as class methods: the
342
- * class face stays judgment-free (zero validate/audit/detect methods).
343
- */
344
- export abstract class DocType<P extends ParsedDoc> extends MarkdownPrimitives {
345
- /** The doc-type record key — the projection-face identity. */
346
- readonly key: DocKey;
347
- /** The declared registry of this doc type — the extractors read their anchor
348
- * rosters from it (the registry stays the single knowledge source). */
349
- readonly registry: ElementRegistry;
350
- /** The derived parse face (per-element anchor slices) of this doc type. */
351
- readonly slices: DocSlices;
352
- /** The derived section skeleton (shape projection) of this doc type. */
353
- readonly shape: DocShape;
354
- /** The doc-type name as carried by a conforming document's parse record. */
355
- abstract readonly docTypeName: DocKey;
356
-
357
- /** The per-anchor slice lookup — the parse face's locating patterns. */
358
- readonly #slicesByAnchor: ReadonlyMap<string, ElementSlice>;
359
-
360
- constructor(key: DocKey) {
361
- super();
362
- this.key = key;
363
- this.registry = declaredRegistries[key];
364
- this.slices = projector.slices()[key];
365
- this.shape = projector.shape()[key];
366
- this.#slicesByAnchor = new Map(this.slices.slices.map((slice) => [slice.anchor, slice]));
367
- }
368
-
369
- /** The pure structural parse — what the invariants and the graph read. The head
370
- * is the typed front-matter head (the §2.2 delivery seam: the chain-docs
371
- * producers MUST parse dual-param, so the chain root reads the head scalars — a
372
- * single-param parse yields the null-head face: title "" and a null chain). */
373
- abstract parse(lines: readonly string[], head?: FrontMatterHead | null): P;
374
-
375
- // -------------------------------------------------------------------------
376
- // shared extraction primitives (parse-only, never judgment)
377
- // -------------------------------------------------------------------------
378
-
379
- /** Split lines into heading blocks — a heading line plus its body up to the next heading. */
380
- protected headingBlocks(lines: readonly string[]): HeadingBlock[] {
381
- const blocks: HeadingBlock[] = [];
382
- let openHeading: string | null = null;
383
- let openRank: HeadingRank | null = null;
384
- let openBody: string[] = [];
385
- const close = (): void => {
386
- if (openHeading !== null && openRank !== null)
387
- blocks.push({ heading: openHeading, rank: openRank, body: openBody });
388
- openHeading = null;
389
- openRank = null;
390
- openBody = [];
391
- };
392
- for (const line of lines) {
393
- const rank = this.headingRank(line);
394
- if (rank !== null) {
395
- close();
396
- openHeading = line;
397
- openRank = rank;
398
- } else if (openHeading !== null) {
399
- openBody.push(line);
400
- }
401
- }
402
- close();
403
- return blocks;
404
- }
405
-
406
- /** The rank-2 section blocks in document order — the HeadingScanner's section
407
- * walk over the registry's declared section anchors (spec §3.2: WHICH rank-2
408
- * headings are sections comes from the registry, never a second hand-written
409
- * filter here). An undeclared prose rank-2 heading is not a section, and a
410
- * declared conditional `##` heading is one. */
411
- protected sections(lines: readonly string[]): SectionBlock[] {
412
- return headingScanner.sectionsOf(this.registry, lines);
413
- }
414
-
415
- /** The `### Task N:` blocks in document order, with their field + step surfaces.
416
- * The block-head / field-marker / step-line grammars live in the TaskExtractor
417
- * (the task home's fixed structure rules over the registry's declared anchors):
418
- * each block is extracted over its own lines, so the extractor's own scoping
419
- * (the fields, and the steps riding inside the `**Steps**` field) yields that
420
- * block's occurrence buckets directly — step recognition never re-appears here. */
421
- protected taskBlocks(blocks: readonly HeadingBlock[]): TaskBlock[] {
422
- const out: TaskBlock[] = [];
423
- for (const block of blocks) {
424
- const lines = [block.heading, ...block.body];
425
- const extracted = taskExtractor.extract(this.registry, lines);
426
- const headings = extracted["### Task N:"] ?? [];
427
- if (headings.length === 0) continue;
428
- const ids = extracted["Task id token"] ?? [];
429
- const id = Number(ids[0] ?? "");
430
- if (Number.isNaN(id)) continue;
431
- const fields = this.#taskFieldsOf(block.body, this.#taskFieldMarkers(extracted));
432
- out.push({
433
- id,
434
- heading: block.heading,
435
- fields,
436
- steps: this.#taskStepsOf(
437
- extracted["Step action"] ?? [],
438
- new Set(extracted["Step checkable"] ?? []),
439
- ),
440
- });
441
- }
442
- return out;
443
- }
444
-
445
- /** The task-field anchor lookup — each declared field anchor's marker line maps
446
- * to its anchor (the retired per-anchor field grammar collapses to one map). */
447
- #taskFieldMarkers(extracted: ExtractionMap): ReadonlyMap<string, string> {
448
- const markers = new Map<string, string>();
449
- for (const [anchor, lines] of Object.entries(extracted)) {
450
- if (!anchor.startsWith("**")) continue;
451
- for (const line of lines) markers.set(line, anchor);
452
- }
453
- return markers;
454
- }
455
-
456
- /** Parse a task block's body into keyed fields — the marker membership comes
457
- * from the extractor's field-anchor map; the remainder and continuation
458
- * handling mirror the retired grammar's behavior exactly. */
459
- #taskFieldsOf(body: readonly string[], markers: ReadonlyMap<string, string>): TaskField[] {
460
- const fields: TaskField[] = [];
461
- let openKey: string | null = null;
462
- let openLines: string[] = [];
463
- const close = (): void => {
464
- if (openKey !== null) fields.push({ key: openKey, lines: openLines });
465
- openKey = null;
466
- openLines = [];
467
- };
468
- for (const line of body) {
469
- const anchor = markers.get(line);
470
- if (anchor !== undefined) {
471
- close();
472
- openKey = anchor.slice(2, -2);
473
- openLines = [line.slice(`- ${anchor}:`.length).trim()];
474
- } else if (openKey !== null && line.trim().length > 0) {
475
- openLines.push(line.trim());
476
- }
477
- }
478
- close();
479
- return fields;
480
- }
481
-
482
- /** Parse a block's recognized step lines into step records — the lines come
483
- * from the extractor's `Step action` bucket (the registry's `^- ` shape, so
484
- * no `- `-bullet re-recognition here); the action cell is a value read after
485
- * the anchor's bullet prefix (mirroring the `#taskIdOf` slot read), and
486
- * membership in the `Step checkable` bucket marks which lines carry a
487
- * verbatim `— checkable:` clause that the split then reads off. */
488
- #taskStepsOf(stepLines: readonly string[], checkableLines: ReadonlySet<string>): TaskStep[] {
489
- const steps: TaskStep[] = [];
490
- for (const line of stepLines) {
491
- const text = line.trim().slice(2).trim();
492
- const checkableMarker = checkableLines.has(line) ? text.indexOf("— checkable:") : -1;
493
- if (checkableMarker === -1) {
494
- steps.push({ action: text, checkable: null });
495
- } else {
496
- steps.push({
497
- action: text.slice(0, checkableMarker).trim(),
498
- checkable: text.slice(checkableMarker + "— checkable:".length).trim(),
499
- });
500
- }
501
- }
502
- return steps;
503
- }
504
-
505
- /** Parse a section's table: the column-header row + the data rows. The header
506
- * row is the one the registry's `… columns` anchors claim (the TableExtractor's
507
- * declared-home set); a table with no registered column anchor falls back to
508
- * the first row, the shape's positional default. The data rows are every
509
- * remaining row plus any leading row ahead of the declared header — a
510
- * mispositioned header never silently drops a data row. */
511
- protected parseTable(lines: readonly string[]): ParsedTable {
512
- const rows = this.tableRows(lines);
513
- const declaredHeader = tableExtractor.headerLineOf(this.registry, lines);
514
- if (declaredHeader === null) {
515
- const headerRow = rows.length > 0 ? rows[0] : null;
516
- return { heading: "", headerRow, rows: rows.slice(1) };
517
- }
518
- const headerCells = this.tableRowCells(declaredHeader);
519
- const dataRows = rows.filter((row) => row.join("|") !== (headerCells ?? []).join("|"));
520
- return { heading: "", headerRow: headerCells, rows: dataRows };
521
- }
522
-
523
- /** The slice of one registered anchor (undefined when the anchor is not registered here). */
524
- protected sliceOf(anchor: string): ElementSlice | undefined {
525
- return this.#slicesByAnchor.get(anchor);
526
- }
527
-
528
- /** Whether a heading line conforms to a declared heading anchor's value shape. */
529
- protected sectionConforms(heading: string, anchor: string): boolean {
530
- const slice = this.#slicesByAnchor.get(anchor);
531
- if (slice?.valuePattern !== undefined) return slice.valuePattern.test(heading);
532
- return heading.startsWith(anchor);
533
- }
534
-
535
- protected headingRank(line: string): HeadingRank | null {
536
- const match = line.match(/^(#+)\s/);
537
- if (match === null) return null;
538
- const rank = match[1].length as HeadingRank;
539
- return rank <= 4 ? rank : null;
540
- }
541
- }
542
-
543
- // ---------------------------------------------------------------------------
544
- // the four concrete doc types
545
- // ---------------------------------------------------------------------------
546
-
547
- /**
548
- * The overall doc type — parses the header, the four tables and the dependency
549
- * graph, and exposes the Phase-inventory rows as the chain's anchor set.
550
- */
551
- export class OverallDocType extends DocType<OverallParsed> {
552
- readonly docTypeName = "overall-spec" as const;
553
-
554
- parse(lines: readonly string[], head: FrontMatterHead | null = null): OverallParsed {
555
- const title = head?.title ?? "";
556
- const sections = this.sections(lines);
557
-
558
- const tables: OverallParsed["tables"] = {
559
- "File paths": this.#tableSection(sections, "## File paths"),
560
- "Issue inventory": this.#tableSection(sections, "## Issue inventory"),
561
- "Phase inventory": this.#tableSection(sections, "## Phase inventory"),
562
- "Change history": this.#tableSection(sections, "## Change history"),
563
- };
564
- const graphEdges = this.#graphEdges(sections);
565
- const phases = this.#phaseRows(tables["Phase inventory"]);
566
- return {
567
- docType: "overall-spec",
568
- head,
569
- title,
570
- sections,
571
- tables,
572
- graphEdges,
573
- chain: {
574
- docType: "overall-spec",
575
- parentLink: null,
576
- specLink: null,
577
- parentTokens: [],
578
- phases,
579
- dependsOn: null,
580
- },
581
- };
582
- }
583
-
584
- /** The `## Dependency graph` edge lines — the graph-home occurrence map (the
585
- * declared Hard/Soft edge anchors) identified by the extractor; the from/to
586
- * token grammar stays the preserved graph-edge primitive. */
587
- #graphEdges(sections: readonly SectionBlock[]): GraphEdge[] {
588
- for (const section of sections) {
589
- if (!this.sectionConforms(section.heading, "## Dependency graph")) continue;
590
- const extracted = graphExtractor.extract(this.registry, section.lines);
591
- const edgeLines = new Set<string>([
592
- ...(extracted["Hard edge"] ?? []),
593
- ...(extracted["Soft edge"] ?? []),
594
- ]);
595
- const edges: GraphEdge[] = [];
596
- const edgePattern = /^P(\d+(?:\.\d+)*)\s*->\s*P(\d+(?:\.\d+)*)$/;
597
- for (const line of section.lines) {
598
- const trimmed = line.trim();
599
- if (!edgeLines.has(trimmed)) continue;
600
- const match = trimmed.match(edgePattern);
601
- if (match !== null) edges.push({ text: trimmed, from: `P${match[1]}`, to: `P${match[2]}` });
602
- }
603
- return edges;
604
- }
605
- return [];
606
- }
607
-
608
- /** The Phase-inventory rows as chain phases — header-driven column mapping. */
609
- #phaseRows(table: ParsedTable): ChainPhase[] {
610
- if (table.headerRow === null) return [];
611
- const columns = new Map<string, number>();
612
- for (let index = 0; index < table.headerRow.length; index++) {
613
- columns.set(table.headerRow[index].toLowerCase(), index);
614
- }
615
- const designIdx = columns.get("design spec");
616
- const planIdx = columns.get("implementation plan");
617
- const dependencyIdx = columns.get("dependency");
618
- if (columns.get("phase") === undefined) return [];
619
- const phases: ChainPhase[] = [];
620
- for (const row of table.rows) {
621
- const id = this.#phaseId(row);
622
- if (id === "") continue;
623
- phases.push({
624
- id,
625
- designCell: designIdx !== undefined ? (row[designIdx] ?? "") : "",
626
- planCell: planIdx !== undefined ? (row[planIdx] ?? "") : "",
627
- dependencyCell: dependencyIdx !== undefined ? (row[dependencyIdx] ?? "") : "",
628
- });
629
- }
630
- return phases;
631
- }
632
-
633
- /** The phase id of a Phase-inventory data row — the cell carrying a phase-id
634
- * token (the token shape judged through the declared `Phase id token` value
635
- * pattern — the retired literal grammar now sourced from the registry). */
636
- #phaseId(row: readonly string[]): string {
637
- const pattern = this.sliceOf("Phase id token")?.valuePattern;
638
- const idCell = row.find((cell) => pattern?.test(cell.trim()) === true);
639
- return idCell === undefined ? "" : idCell.trim();
640
- }
641
-
642
- /** The parsed table of one overall table section (empty when the section is absent). */
643
- #tableSection(sections: readonly SectionBlock[], heading: string): ParsedTable {
644
- for (const section of sections) {
645
- if (this.sectionConforms(section.heading, heading)) {
646
- const table = this.parseTable(section.lines);
647
- return { heading: section.heading, headerRow: table.headerRow, rows: table.rows };
648
- }
649
- }
650
- return { heading: "", headerRow: null, rows: [] };
651
- }
652
- }
653
-
654
- /**
655
- * The plan doc type — parses the head (Class-A `spec:` + Class-B parent
656
- * lineage) and the `### Task N:` task blocks.
657
- */
658
- export class PlanDocType extends DocType<PlanParsed> {
659
- readonly docTypeName = "plan" as const;
660
-
661
- parse(lines: readonly string[], head: FrontMatterHead | null = null): PlanParsed {
662
- const title = head?.title ?? "";
663
- const blocks = this.headingBlocks(lines);
664
- return {
665
- docType: "plan",
666
- head,
667
- title,
668
- sections: this.sections(lines),
669
- taskBlocks: this.taskBlocks(blocks),
670
- chain: this.chainRoot(head),
671
- };
672
- }
673
-
674
- /** The plan's cross-doc chain root — the Class-A `spec:` + Class-B
675
- * `parent-program:`/`parent-version:` head scalars (the §2.2 delivery seam:
676
- * the chain facts ride the typed head, never a body line scan). */
677
- chainRoot(head: FrontMatterHead | null): ChainRoot {
678
- return {
679
- docType: "plan",
680
- parentLink:
681
- head === null || head.parentProgram === null ? null : { target: head.parentProgram },
682
- specLink: head === null || head.spec === null ? null : { target: head.spec },
683
- parentTokens: head === null || head.parentVersion === null ? [] : [head.parentVersion],
684
- phases: [],
685
- dependsOn: head?.dependsOn ?? null,
686
- };
687
- }
688
- }
689
-
690
- /**
691
- * The phase-spec doc type — parses the header five-tuple surface and the
692
- * `## Design` double-layer skeleton (groups + items).
693
- */
694
- export class PhaseSpecDocType extends DocType<PhaseSpecParsed> {
695
- readonly docTypeName = "phase-spec" as const;
696
-
697
- parse(lines: readonly string[], head: FrontMatterHead | null = null): PhaseSpecParsed {
698
- const title = head?.title ?? "";
699
- const blocks = this.headingBlocks(lines);
700
- return {
701
- docType: "phase-spec",
702
- head,
703
- title,
704
- sections: this.sections(lines),
705
- design: this.designFromBlocks(blocks),
706
- chain: this.chainRoot(head),
707
- };
708
- }
709
-
710
- /** The design double-layer skeleton — the `### N.` groups + their `#### N.M`
711
- * items between the `## Design` section and the next rank-2 heading. The
712
- * numbered-heading grammars (and their number/text decomposition) live in the
713
- * DesignBodyExtractor; this method walks the declared groups/items from its
714
- * occurrence map. */
715
- designFromBlocks(blocks: readonly HeadingBlock[]): DesignGroup[] {
716
- const lines = blocks.flatMap((block) => [block.heading, ...block.body]);
717
- const extracted = designExtractor.extract(this.registry, lines);
718
- const designHeadings = new Set(extracted["## Design"] ?? []);
719
- const groupHeadings = new Set(extracted["### N. group heading"] ?? []);
720
- const itemHeadings = new Set(extracted["#### N.M item heading"] ?? []);
721
- const groups: DesignGroup[] = [];
722
- let openNumber: string | null = null;
723
- let openHeading = "";
724
- let openItems: DesignItem[] = [];
725
- let inDesign = false;
726
- const close = (): void => {
727
- if (openNumber !== null) {
728
- groups.push({ number: openNumber, heading: openHeading, items: openItems });
729
- }
730
- openNumber = null;
731
- openHeading = "";
732
- openItems = [];
733
- };
734
- for (const block of blocks) {
735
- const rank = this.headingRank(block.heading);
736
- if (rank === 2) {
737
- if (inDesign) break;
738
- if (designHeadings.has(block.heading)) inDesign = true;
739
- continue;
740
- }
741
- if (!inDesign || (rank !== 3 && rank !== 4)) continue;
742
- if (groupHeadings.has(block.heading)) {
743
- close();
744
- const group = designExtractor.groupOf(block.heading);
745
- openNumber = group.number;
746
- openHeading = group.heading;
747
- continue;
748
- }
749
- if (openNumber !== null && itemHeadings.has(block.heading)) {
750
- openItems.push(designExtractor.itemOf(block.heading));
751
- }
752
- }
753
- close();
754
- return groups;
755
- }
756
-
757
- /** The phase-spec's cross-doc chain root: the Class-B `parent-program:`
758
- * `parent-version:` head scalars. */
759
- chainRoot(head: FrontMatterHead | null): ChainRoot {
760
- return {
761
- docType: "phase-spec",
762
- parentLink:
763
- head === null || head.parentProgram === null ? null : { target: head.parentProgram },
764
- specLink: null,
765
- parentTokens: head === null || head.parentVersion === null ? [] : [head.parentVersion],
766
- phases: [],
767
- dependsOn: head?.dependsOn ?? null,
768
- };
769
- }
770
- }
771
-
772
- /**
773
- * The single-spec doc type — parses the header five-tuple surface and the prose
774
- * section surface. A single-spec carries no parent overall and no `### N.`
775
- * design outline, so the parse degrades the chain root to its null-link face
776
- * (the `depends-on:` front-matter value is the only chain fact carried).
777
- */
778
- export class SingleSpecDocType extends DocType<SingleSpecParsed> {
779
- readonly docTypeName = "single-spec" as const;
780
-
781
- parse(lines: readonly string[], head: FrontMatterHead | null = null): SingleSpecParsed {
782
- const title = head?.title ?? "";
783
- return {
784
- docType: "single-spec",
785
- head,
786
- title,
787
- sections: this.sections(lines),
788
- chain: this.chainRoot(head),
789
- };
790
- }
791
-
792
- /** The single-spec chain root — the degraded face: no parent link / no spec
793
- * link (the independent-program shape), the `depends-on:` value only. */
794
- chainRoot(head: FrontMatterHead | null): ChainRoot {
795
- return {
796
- docType: "single-spec",
797
- parentLink: null,
798
- specLink: null,
799
- parentTokens: [],
800
- phases: [],
801
- dependsOn: head?.dependsOn ?? null,
802
- };
803
- }
804
- }
805
-
806
- // ---------------------------------------------------------------------------
807
- // composition root — the four parsers by doc-key
808
- // ---------------------------------------------------------------------------
809
-
810
- /** The composed doc-type parsers — the judge's ctx-loading parsers (one per doc key). */
811
- export const docTypeParsers: Record<DocKey, DocType<ParsedDoc>> = {
812
- "overall-spec": new OverallDocType("overall-spec"),
813
- plan: new PlanDocType("plan"),
814
- "phase-spec": new PhaseSpecDocType("phase-spec"),
815
- "single-spec": new SingleSpecDocType("single-spec"),
816
- };