@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
@@ -1,753 +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). Nothing is decided here — parse
12
- // extracts, the invariant family judges.
13
- // · projection — each class consumes the derived projection face (project.ts):
14
- // the slices (parse regexes) and the shape (section skeleton) of
15
- // its own doc type are the locating data every extraction walks.
16
- // · chain root — the Class-A/B anchors of the document (the plan's `**Spec:**`
17
- // link, the `**Parent program**` link + its version tokens, the
18
- // overall's Phase-inventory rows as the chain's anchor set) are
19
- // extracted into a ChainRoot and LEFT as an interface — the
20
- // resolution judgment belongs to the cross-doc-chain invariant,
21
- // never to a DocType method.
22
- //
23
- // Module-level exports are types / the class family / one composition root — zero
24
- // behavior-carrying bare functions (the plan's zero-bare-function discipline).
25
-
26
- import { declaredRegistries } from "./declare.ts";
27
- import type { DocKey, DocShape, DocSlices, ElementSlice } from "./project.ts";
28
- import { Projector } from "./project.ts";
29
-
30
- /** The projection carrier — one Projector instance over the declared registries,
31
- * shared by the four parser classes (each binds its own doc-type faces). */
32
- const projector = new Projector(declaredRegistries);
33
-
34
- // ---------------------------------------------------------------------------
35
- // shared structural types
36
- // ---------------------------------------------------------------------------
37
-
38
- /** The markdown heading rank (the count of leading `#`s). */
39
- type HeadingRank = 1 | 2 | 3 | 4;
40
-
41
- /** One heading block of the document — a heading line and the lines up to the next heading. */
42
- export interface HeadingBlock {
43
- /** The heading line verbatim, leading `#`s included. */
44
- heading: string;
45
- /** The heading's markdown rank. */
46
- rank: HeadingRank;
47
- /** The block's body lines (excluding the heading line). */
48
- body: readonly string[];
49
- }
50
-
51
- /** One `##`-ranked section of the document. */
52
- export interface SectionBlock {
53
- /** The section's heading line verbatim (e.g. "## Document scope"). */
54
- heading: string;
55
- /** The section's body lines (up to the next `##`-ranked heading). */
56
- lines: readonly string[];
57
- }
58
-
59
- /** A markdown table parsed from a section: the column header plus its data rows. */
60
- export interface ParsedTable {
61
- /** The table's section heading line (e.g. "## Phase inventory"). */
62
- heading: string;
63
- /** The column-header row (the first non-separator table line), when present. */
64
- headerRow: readonly string[] | null;
65
- /** The data rows — every non-separator table line after the header row. */
66
- rows: readonly string[][];
67
- }
68
-
69
- // ---------------------------------------------------------------------------
70
- // the root-level parse records
71
- // ---------------------------------------------------------------------------
72
-
73
- /** One dependency-graph edge line (`P<n> -> P<m>`) parsed verbatim. */
74
- export interface GraphEdge {
75
- /** The edge line verbatim. */
76
- text: string;
77
- /** The edge's from-phase token (the leading `P<n>` — a `.digits` suffix included). */
78
- from: string;
79
- /** The edge's to-phase token. */
80
- to: string;
81
- }
82
-
83
- /** One parsed phase-inventory row of the overall (the chain-root anchor set). */
84
- export interface ChainPhase {
85
- /** The registered phase id (e.g. "P2.1"). */
86
- id: string;
87
- /** The Design-spec cell text (link tokens, e.g. `[P2-design](docs/kairos/specs/x-design.md)`). */
88
- designCell: string;
89
- /** The Implementation-plan cell text (link tokens, e.g. `[plan](docs/kairos/plans/x.md)`). */
90
- planCell: string;
91
- /** The Dependency cell text (e.g. "P1 -> P2"). */
92
- dependencyCell: string;
93
- }
94
-
95
- /** A `[label](target)` link parsed from a line. */
96
- export interface ChainLink {
97
- /** The link's label text. */
98
- label: string;
99
- /** The link's target path. */
100
- target: string;
101
- }
102
-
103
- /**
104
- * The cross-doc chain root — the Class-A/B anchors a document carries, extracted
105
- * verbatim and left unresolved. Every resolution judgment (target existence, label
106
- * vs. basename drift, version-token lineage membership) belongs to the
107
- * cross-doc-chain / file-existence / sibling-scan invariants.
108
- */
109
- export interface ChainRoot {
110
- /** The doc-type identity of the chain root's document. */
111
- docType: "overall-spec" | "plan" | "phase-spec" | "single-spec";
112
- /** The `**Parent program**` link (Class-B) — the parent overall reference of a
113
- * plan/spec document; null for the overall (the chain root itself). */
114
- parentLink: ChainLink | null;
115
- /** The `**Spec:**` link (Class-A) — the plan's design-spec reference; null for the
116
- * overall (no spec to reference) and for a spec (the document IS the design spec). */
117
- specLink: ChainLink | null;
118
- /** The version tokens carried on the `**Parent program**` line (Class-B lineage). */
119
- parentTokens: readonly string[];
120
- /** The overall's phase-inventory rows — the chain's anchor set (overall only). */
121
- phases: readonly ChainPhase[];
122
- /** The `**Depends on**` header value (plan/spec), verbatim, when the line is present. */
123
- dependsOn: string | null;
124
- }
125
-
126
- /** The overall parse record — the four tables, the graph edges and the chain root. */
127
- export interface OverallParsed {
128
- docType: "overall-spec";
129
- /** The `# Title` line verbatim. */
130
- title: string;
131
- /** The header bullet lines (between the title and the first section heading). */
132
- headerLines: readonly string[];
133
- /** The `##`-ranked sections in document order. */
134
- sections: readonly SectionBlock[];
135
- /** The parsed overall tables (each present only when its section was found). */
136
- tables: {
137
- "File paths": ParsedTable;
138
- "Issue inventory": ParsedTable;
139
- "Phase inventory": ParsedTable;
140
- "Change history": ParsedTable;
141
- };
142
- /** The dependency-graph edge lines under `## Dependency graph`. */
143
- graphEdges: readonly GraphEdge[];
144
- /** The overall's cross-doc chain root (its Phase-inventory rows are the anchor set). */
145
- chain: ChainRoot;
146
- }
147
-
148
- /** One parsed `- **Key**:` field of a task block. */
149
- export interface TaskField {
150
- /** The field key (Objective / Files / Consumes / Produces / Steps / Acceptance / DependsOn). */
151
- key: string;
152
- /** The field's value lines — the marker line's remainder plus its continuation lines. */
153
- lines: readonly string[];
154
- }
155
-
156
- /** One parsed step line of a task block's `**Steps**` field. */
157
- export interface TaskStep {
158
- /** The step's action text (after the leading `- `). */
159
- action: string;
160
- /** The step's `— checkable:` clause text, when the line carries one. */
161
- checkable: string | null;
162
- }
163
-
164
- /** One parsed `### Task N:` block. */
165
- export interface TaskBlock {
166
- /** The task number N. */
167
- id: number;
168
- /** The `### Task N: …` heading line verbatim. */
169
- heading: string;
170
- /** The block's keyed fields in document order. */
171
- fields: readonly TaskField[];
172
- /** The parsed `**Steps**` bullets. */
173
- steps: readonly TaskStep[];
174
- }
175
-
176
- /** The plan parse record — the header, the constraints section and the task blocks. */
177
- export interface PlanParsed {
178
- docType: "plan";
179
- title: string;
180
- headerLines: readonly string[];
181
- sections: readonly SectionBlock[];
182
- /** The `### Task N:` blocks in document order. */
183
- taskBlocks: readonly TaskBlock[];
184
- chain: ChainRoot;
185
- }
186
-
187
- /** One `### N.` design group and its `#### N.M` items (the phase-spec skeleton). */
188
- export interface DesignGroup {
189
- /** The group's leading number token (`1` for `### 1. …`). */
190
- number: string;
191
- /** The group's heading text (after the number token). */
192
- heading: string;
193
- /** The group's items in document order. */
194
- items: readonly DesignItem[];
195
- }
196
-
197
- /** One `#### N.M` design item. */
198
- export interface DesignItem {
199
- /** The item's number token (`1.2` for `#### 1.2 …`). */
200
- number: string;
201
- /** The item's heading text. */
202
- heading: string;
203
- }
204
-
205
- /** The phase-spec parse record — the header tuple and the design-body skeleton. */
206
- export interface PhaseSpecParsed {
207
- docType: "phase-spec";
208
- title: string;
209
- headerLines: readonly string[];
210
- sections: readonly SectionBlock[];
211
- /** The `## Design` double-layer skeleton (groups + items), when the section is present. */
212
- design: readonly DesignGroup[];
213
- chain: ChainRoot;
214
- }
215
-
216
- /** The single-spec parse record — the header five-tuple and the prose section surface. */
217
- export interface SingleSpecParsed {
218
- docType: "single-spec";
219
- title: string;
220
- headerLines: readonly string[];
221
- sections: readonly SectionBlock[];
222
- chain: ChainRoot;
223
- }
224
-
225
- /** The parsed-document union — one record per doc type. */
226
- export type ParsedDoc = OverallParsed | PlanParsed | PhaseSpecParsed | SingleSpecParsed;
227
-
228
- // ---------------------------------------------------------------------------
229
- // the shared markdown primitives — one home for the link/token/table-row parsers
230
- // ---------------------------------------------------------------------------
231
-
232
- /**
233
- * The shared extraction primitives: `[label](target)` links, `v<n>.<m>` version
234
- * tokens and `|…|` table-row parsing. Both the parse face (DocType) and the
235
- * judgment face (the Invariant base in invariants.ts) extend this base — the
236
- * link/token/table parse logic lives in exactly one place of the new tree. The
237
- * version-token grammar additionally exposes the public static `versionTokensOf`
238
- * — the face plane's doc-line BLOCK reads the SAME grammar through it (one home,
239
- * zero dual-write).
240
- */
241
- export abstract class MarkdownPrimitives {
242
- /** The `[label](target)` pairs parsed from one line. */
243
- protected linksOnLine(line: string): readonly ChainLink[] {
244
- const links: ChainLink[] = [];
245
- const linkPattern = /\[([^\]]*)\]\(([^)]+)\)/g;
246
- for (const match of line.matchAll(linkPattern)) {
247
- links.push({ label: match[1], target: match[2] });
248
- }
249
- return links;
250
- }
251
-
252
- /** The `v<major>.<minor>` tokens on one line — the version-token grammar's ONE
253
- * home of the tree: the face plane's doc-line BLOCK token reads this public
254
- * static; the subclasses keep the protected accessor below (a thin delegation,
255
- * zero second grammar). */
256
- static versionTokensOf(line: string): readonly string[] {
257
- const tokens: string[] = [];
258
- const tokenPattern = /v\d+\.\d+/g;
259
- for (const match of line.matchAll(tokenPattern)) tokens.push(match[0]);
260
- return tokens;
261
- }
262
-
263
- /** The `v<major>.<minor>` tokens on one line — the class-family accessor
264
- * (the grammar itself is the static — one home). */
265
- protected versionTokens(line: string): readonly string[] {
266
- return MarkdownPrimitives.versionTokensOf(line);
267
- }
268
-
269
- /** The cells of one `|…|` table line (trimmed, wrapper bars excluded); null for a
270
- * non-table line or a separator row. */
271
- protected tableRowCells(line: string): readonly string[] | null {
272
- const trimmed = line.trim();
273
- if (!trimmed.startsWith("|") || !trimmed.endsWith("|")) return null;
274
- if (/^\|[\s:|-]+\|$/.test(trimmed)) return null; // separator row
275
- return trimmed
276
- .split("|")
277
- .slice(1, -1)
278
- .map((cell) => cell.trim());
279
- }
280
-
281
- /** The non-separator `|…|` rows of a line run (the first row is the column header). */
282
- protected tableRows(lines: readonly string[]): readonly string[][] {
283
- const rows: string[][] = [];
284
- for (const line of lines) {
285
- const cells = this.tableRowCells(line);
286
- if (cells !== null) rows.push([...cells]);
287
- }
288
- return rows;
289
- }
290
- }
291
-
292
- // ---------------------------------------------------------------------------
293
- // the DocType base — parse + projection consumption + chain root
294
- // ---------------------------------------------------------------------------
295
-
296
- /**
297
- * The abstract doc-type base. Each subclass binds its registry-derived projection
298
- * face (slices + shape) and implements parse — pure structural extraction into a
299
- * typed record. The base carries the shared extraction primitives (heading blocks,
300
- * table rows, header lines, `[label](target)` link parsing) as class methods: the
301
- * class face stays judgment-free (zero validate/audit/detect methods).
302
- */
303
- export abstract class DocType<P extends ParsedDoc> extends MarkdownPrimitives {
304
- /** The doc-type record key — the projection-face identity. */
305
- readonly key: DocKey;
306
- /** The derived parse face (per-element anchor slices) of this doc type. */
307
- readonly slices: DocSlices;
308
- /** The derived section skeleton (shape projection) of this doc type. */
309
- readonly shape: DocShape;
310
- /** The doc-type name as carried by a conforming document's parse record. */
311
- abstract readonly docTypeName: "overall-spec" | "plan" | "phase-spec" | "single-spec";
312
-
313
- /** The per-anchor slice lookup — the parse face's locating patterns. */
314
- readonly #slicesByAnchor: ReadonlyMap<string, ElementSlice>;
315
-
316
- constructor(key: DocKey) {
317
- super();
318
- this.key = key;
319
- this.slices = projector.slices()[key];
320
- this.shape = projector.shape()[key];
321
- this.#slicesByAnchor = new Map(this.slices.slices.map((slice) => [slice.anchor, slice]));
322
- }
323
-
324
- /** The pure structural parse — what the invariants and the graph read. */
325
- abstract parse(lines: readonly string[]): P;
326
-
327
- // -------------------------------------------------------------------------
328
- // shared extraction primitives (parse-only, never judgment)
329
- // -------------------------------------------------------------------------
330
-
331
- /** Split lines into heading blocks — a heading line plus its body up to the next heading. */
332
- protected headingBlocks(lines: readonly string[]): HeadingBlock[] {
333
- const blocks: HeadingBlock[] = [];
334
- let openHeading: string | null = null;
335
- let openRank: HeadingRank | null = null;
336
- let openBody: string[] = [];
337
- const close = (): void => {
338
- if (openHeading !== null && openRank !== null)
339
- blocks.push({ heading: openHeading, rank: openRank, body: openBody });
340
- openHeading = null;
341
- openRank = null;
342
- openBody = [];
343
- };
344
- for (const line of lines) {
345
- const rank = this.headingRank(line);
346
- if (rank !== null) {
347
- close();
348
- openHeading = line;
349
- openRank = rank;
350
- } else if (openHeading !== null) {
351
- openBody.push(line);
352
- }
353
- }
354
- close();
355
- return blocks;
356
- }
357
-
358
- /** The header lines — the `# Title` block's body (metadata lines before the first
359
- * rank-2/rank-3 heading block; heading blocks split at every heading, so the title
360
- * block body already ends where the sections/task blocks begin). */
361
- protected headerLines(blocks: readonly HeadingBlock[]): readonly string[] {
362
- if (blocks.length === 0) return [];
363
- return blocks[0].body;
364
- }
365
-
366
- /** The rank-2 section blocks in document order. */
367
- protected sections(blocks: readonly HeadingBlock[]): SectionBlock[] {
368
- const out: SectionBlock[] = [];
369
- for (const block of blocks) {
370
- if (this.headingRank(block.heading) === 2)
371
- out.push({ heading: block.heading, lines: block.body });
372
- }
373
- return out;
374
- }
375
-
376
- /** The `### Task N:` blocks in document order, with their field + step surfaces. */
377
- protected taskBlocks(blocks: readonly HeadingBlock[]): TaskBlock[] {
378
- const out: TaskBlock[] = [];
379
- for (const block of blocks) {
380
- const match = block.heading.match(/^### Task (\d+):/);
381
- if (match === null) continue;
382
- const fields = this.parseTaskFields(block.body);
383
- const stepsField = fields.find((field) => field.key === "Steps");
384
- out.push({
385
- id: Number(match[1]),
386
- heading: block.heading,
387
- fields,
388
- steps: this.parseSteps(stepsField),
389
- });
390
- }
391
- return out;
392
- }
393
-
394
- /** Parse a task block's body into keyed fields. */
395
- protected parseTaskFields(body: readonly string[]): TaskField[] {
396
- const fields: TaskField[] = [];
397
- let openKey: string | null = null;
398
- let openLines: string[] = [];
399
- const close = (): void => {
400
- if (openKey !== null) fields.push({ key: openKey, lines: openLines });
401
- openKey = null;
402
- openLines = [];
403
- };
404
- for (const line of body) {
405
- const fieldMarker = line.match(/^-\s+\*\*([A-Za-z ]+)\*\*:\s*(.*)$/);
406
- if (fieldMarker !== null) {
407
- close();
408
- openKey = fieldMarker[1];
409
- openLines = [fieldMarker[2].trim()];
410
- } else if (openKey !== null && line.trim().length > 0) {
411
- openLines.push(line.trim());
412
- }
413
- }
414
- close();
415
- return fields;
416
- }
417
-
418
- /** Parse a `**Steps**` field's value lines into step records. */
419
- protected parseSteps(field: TaskField | undefined): TaskStep[] {
420
- if (field === undefined) return [];
421
- const steps: TaskStep[] = [];
422
- for (const line of field.lines) {
423
- const bullet = line.match(/^-\s+(.*)$/);
424
- if (bullet === null) continue;
425
- const text = bullet[1];
426
- const checkableMarker = text.indexOf("— checkable:");
427
- if (checkableMarker === -1) {
428
- steps.push({ action: text, checkable: null });
429
- } else {
430
- steps.push({
431
- action: text.slice(0, checkableMarker).trim(),
432
- checkable: text.slice(checkableMarker + "— checkable:".length).trim(),
433
- });
434
- }
435
- }
436
- return steps;
437
- }
438
-
439
- /** Parse a section's table: the column-header row + the data rows. */
440
- protected parseTable(lines: readonly string[]): ParsedTable {
441
- const rows = this.tableRows(lines);
442
- const headerRow = rows.length > 0 ? rows[0] : null;
443
- return { heading: "", headerRow, rows: rows.slice(1) };
444
- }
445
-
446
- /** The first `**Marker**:`-style header line by its literal marker. */
447
- protected markerLine(lines: readonly string[], marker: string): string | null {
448
- for (const line of lines) if (line.includes(marker)) return line;
449
- return null;
450
- }
451
-
452
- /** The value token of a `- **Key**: <value>` header line (the text after the marker). */
453
- protected markerValue(line: string, marker: string): string {
454
- const markerIndex = line.indexOf(marker);
455
- if (markerIndex === -1) return "";
456
- const payload = line.slice(markerIndex + marker.length).trim();
457
- return payload.replace(/^:\s*/, "").trim();
458
- }
459
-
460
- /** The line number (1-indexed) the anchor first occurs on, or -1. */
461
- protected indexOfLine(lines: readonly string[], text: string): number {
462
- const index = lines.findIndex((line) => line.includes(text));
463
- return index === -1 ? -1 : index + 1;
464
- }
465
-
466
- /** The slice of one registered anchor (undefined when the anchor is not registered here). */
467
- protected sliceOf(anchor: string): ElementSlice | undefined {
468
- return this.#slicesByAnchor.get(anchor);
469
- }
470
-
471
- /** Whether a heading line conforms to a declared heading anchor's value shape. */
472
- protected sectionConforms(heading: string, anchor: string): boolean {
473
- const slice = this.#slicesByAnchor.get(anchor);
474
- if (slice?.valuePattern !== undefined) return slice.valuePattern.test(heading);
475
- return heading.startsWith(anchor);
476
- }
477
-
478
- protected headingRank(line: string): HeadingRank | null {
479
- const match = line.match(/^(#+)\s/);
480
- if (match === null) return null;
481
- const rank = match[1].length as HeadingRank;
482
- return rank <= 4 ? rank : null;
483
- }
484
- }
485
-
486
- // ---------------------------------------------------------------------------
487
- // the four concrete doc types
488
- // ---------------------------------------------------------------------------
489
-
490
- /**
491
- * The overall doc type — parses the header, the four tables and the dependency
492
- * graph, and exposes the Phase-inventory rows as the chain's anchor set.
493
- */
494
- export class OverallDocType extends DocType<OverallParsed> {
495
- readonly docTypeName = "overall-spec" as const;
496
-
497
- parse(lines: readonly string[]): OverallParsed {
498
- const title = lines[0] ?? "";
499
- const blocks = this.headingBlocks(lines);
500
- const headerLines = this.headerLines(blocks);
501
- const sections = this.sections(blocks);
502
-
503
- const tables: OverallParsed["tables"] = {
504
- "File paths": this.#tableSection(sections, "## File paths"),
505
- "Issue inventory": this.#tableSection(sections, "## Issue inventory"),
506
- "Phase inventory": this.#tableSection(sections, "## Phase inventory"),
507
- "Change history": this.#tableSection(sections, "## Change history"),
508
- };
509
- const graphEdges = this.#graphEdges(sections);
510
- const phases = this.#phaseRows(tables["Phase inventory"]);
511
- return {
512
- docType: "overall-spec",
513
- title,
514
- headerLines,
515
- sections,
516
- tables,
517
- graphEdges,
518
- chain: {
519
- docType: "overall-spec",
520
- parentLink: null,
521
- specLink: null,
522
- parentTokens: [],
523
- phases,
524
- dependsOn: null,
525
- },
526
- };
527
- }
528
-
529
- /** The `## Dependency graph` edge lines, parsed into from/to tokens. */
530
- #graphEdges(sections: readonly SectionBlock[]): GraphEdge[] {
531
- for (const section of sections) {
532
- if (!this.sectionConforms(section.heading, "## Dependency graph")) continue;
533
- const edges: GraphEdge[] = [];
534
- const edgePattern = /^P(\d+(?:\.\d+)*)\s*->\s*P(\d+(?:\.\d+)*)$/;
535
- for (const line of section.lines) {
536
- const trimmed = line.trim();
537
- const match = trimmed.match(edgePattern);
538
- if (match !== null) edges.push({ text: trimmed, from: `P${match[1]}`, to: `P${match[2]}` });
539
- }
540
- return edges;
541
- }
542
- return [];
543
- }
544
-
545
- /** The Phase-inventory rows as chain phases — header-driven column mapping. */
546
- #phaseRows(table: ParsedTable): ChainPhase[] {
547
- if (table.headerRow === null) return [];
548
- const columns = new Map<string, number>();
549
- for (let index = 0; index < table.headerRow.length; index++) {
550
- columns.set(table.headerRow[index].toLowerCase(), index);
551
- }
552
- const designIdx = columns.get("design spec");
553
- const planIdx = columns.get("implementation plan");
554
- const dependencyIdx = columns.get("dependency");
555
- if (columns.get("phase") === undefined) return [];
556
- const phases: ChainPhase[] = [];
557
- for (const row of table.rows) {
558
- const id = this.#phaseId(row);
559
- if (id === "") continue;
560
- phases.push({
561
- id,
562
- designCell: designIdx !== undefined ? (row[designIdx] ?? "") : "",
563
- planCell: planIdx !== undefined ? (row[planIdx] ?? "") : "",
564
- dependencyCell: dependencyIdx !== undefined ? (row[dependencyIdx] ?? "") : "",
565
- });
566
- }
567
- return phases;
568
- }
569
-
570
- /** The phase id of a Phase-inventory data row — the cell carrying a phase-id token
571
- * (the first `#` column cell in the canonical repo row form, where the `Phase`
572
- * column holds the phase name). A numeric-led row falls back to its `Phase` cell. */
573
- #phaseId(row: readonly string[]): string {
574
- const idCell = row.find((cell) => /^P\d+(\.\d+)*$/.test(cell.trim()));
575
- return idCell === undefined ? "" : idCell.trim();
576
- }
577
-
578
- /** The parsed table of one overall table section (empty when the section is absent). */
579
- #tableSection(sections: readonly SectionBlock[], heading: string): ParsedTable {
580
- for (const section of sections) {
581
- if (this.sectionConforms(section.heading, heading)) {
582
- const table = this.parseTable(section.lines);
583
- return { heading: section.heading, headerRow: table.headerRow, rows: table.rows };
584
- }
585
- }
586
- return { heading: "", headerRow: null, rows: [] };
587
- }
588
- }
589
-
590
- /**
591
- * The plan doc type — parses the header (Class-A `**Spec:**` + Class-B parent
592
- * lineage) and the `### Task N:` task blocks.
593
- */
594
- export class PlanDocType extends DocType<PlanParsed> {
595
- readonly docTypeName = "plan" as const;
596
-
597
- parse(lines: readonly string[]): PlanParsed {
598
- const title = lines[0] ?? "";
599
- const blocks = this.headingBlocks(lines);
600
- const headerLines = this.headerLines(blocks);
601
- return {
602
- docType: "plan",
603
- title,
604
- headerLines,
605
- sections: this.sections(blocks),
606
- taskBlocks: this.taskBlocks(blocks),
607
- chain: this.chainRoot(headerLines),
608
- };
609
- }
610
-
611
- /** The plan's cross-doc chain root: Class-A `**Spec:**` + Class-B `**Parent program**`. */
612
- chainRoot(headerLines: readonly string[]): ChainRoot {
613
- const specLine = this.markerLine(headerLines, "**Spec:**");
614
- const specLinks = specLine === null ? [] : this.linksOnLine(specLine);
615
- const parentLine = this.markerLine(headerLines, "**Parent program**");
616
- const parentLinks = parentLine === null ? [] : this.linksOnLine(parentLine);
617
- const dependsOnLine = this.markerLine(headerLines, "**Depends on**");
618
- return {
619
- docType: "plan",
620
- parentLink: parentLinks.length > 0 ? parentLinks[0] : null,
621
- specLink: specLinks.length > 0 ? specLinks[0] : null,
622
- parentTokens: parentLine === null ? [] : this.versionTokens(parentLine),
623
- phases: [],
624
- dependsOn: dependsOnLine === null ? null : this.markerValue(dependsOnLine, "**Depends on**"),
625
- };
626
- }
627
- }
628
-
629
- /**
630
- * The phase-spec doc type — parses the header five-tuple surface and the
631
- * `## Design` double-layer skeleton (groups + items).
632
- */
633
- export class PhaseSpecDocType extends DocType<PhaseSpecParsed> {
634
- readonly docTypeName = "phase-spec" as const;
635
-
636
- parse(lines: readonly string[]): PhaseSpecParsed {
637
- const title = lines[0] ?? "";
638
- const blocks = this.headingBlocks(lines);
639
- const headerLines = this.headerLines(blocks);
640
- return {
641
- docType: "phase-spec",
642
- title,
643
- headerLines,
644
- sections: this.sections(blocks),
645
- design: this.designFromBlocks(blocks),
646
- chain: this.chainRoot(headerLines),
647
- };
648
- }
649
-
650
- /** The design double-layer skeleton — the `### N.` groups + their `#### N.M` items
651
- * between the `## Design` section and the next rank-2 heading. */
652
- designFromBlocks(blocks: readonly HeadingBlock[]): DesignGroup[] {
653
- const groups: DesignGroup[] = [];
654
- let openNumber: string | null = null;
655
- let openHeading = "";
656
- let openItems: DesignItem[] = [];
657
- let inDesign = false;
658
- const close = (): void => {
659
- if (openNumber !== null) {
660
- groups.push({ number: openNumber, heading: openHeading, items: openItems });
661
- }
662
- openNumber = null;
663
- openHeading = "";
664
- openItems = [];
665
- };
666
- for (const block of blocks) {
667
- const rank = this.headingRank(block.heading);
668
- if (rank === 2) {
669
- if (inDesign) break;
670
- if (this.sectionConforms(block.heading, "## Design")) inDesign = true;
671
- continue;
672
- }
673
- if (!inDesign || (rank !== 3 && rank !== 4)) continue;
674
- const groupMatch = block.heading.match(/^### (\d+)\.\s+(.*)$/);
675
- if (groupMatch !== null) {
676
- close();
677
- openNumber = groupMatch[1];
678
- openHeading = groupMatch[2];
679
- continue;
680
- }
681
- const itemMatch = block.heading.match(/^#### (\d+)\.(\d+)\s+(.*)$/);
682
- if (itemMatch !== null && openNumber !== null) {
683
- openItems.push({ number: `${itemMatch[1]}.${itemMatch[2]}`, heading: itemMatch[3] });
684
- }
685
- }
686
- close();
687
- return groups;
688
- }
689
-
690
- /** The phase-spec's cross-doc chain root: the Class-B `**Parent program**` lineage. */
691
- chainRoot(headerLines: readonly string[]): ChainRoot {
692
- const parentLine = this.markerLine(headerLines, "**Parent program**");
693
- const parentLinks = parentLine === null ? [] : this.linksOnLine(parentLine);
694
- const dependsOnLine = this.markerLine(headerLines, "**Depends on**");
695
- return {
696
- docType: "phase-spec",
697
- parentLink: parentLinks.length > 0 ? parentLinks[0] : null,
698
- specLink: null,
699
- parentTokens: parentLine === null ? [] : this.versionTokens(parentLine),
700
- phases: [],
701
- dependsOn: dependsOnLine === null ? null : this.markerValue(dependsOnLine, "**Depends on**"),
702
- };
703
- }
704
- }
705
-
706
- /**
707
- * The single-spec doc type — parses the header five-tuple surface and the prose
708
- * section surface. A single-spec carries no parent overall and no `### N.`
709
- * design outline, so the parse degrades the chain root to its null-link face
710
- * (the `**Depends on**` header value is the only chain fact carried).
711
- */
712
- export class SingleSpecDocType extends DocType<SingleSpecParsed> {
713
- readonly docTypeName = "single-spec" as const;
714
-
715
- parse(lines: readonly string[]): SingleSpecParsed {
716
- const title = lines[0] ?? "";
717
- const blocks = this.headingBlocks(lines);
718
- const headerLines = this.headerLines(blocks);
719
- return {
720
- docType: "single-spec",
721
- title,
722
- headerLines,
723
- sections: this.sections(blocks),
724
- chain: this.chainRoot(headerLines),
725
- };
726
- }
727
-
728
- /** The single-spec chain root — the degraded face: no parent link / no spec
729
- * link (the independent-program shape), the `**Depends on**` value only. */
730
- chainRoot(headerLines: readonly string[]): ChainRoot {
731
- const dependsOnLine = this.markerLine(headerLines, "**Depends on**");
732
- return {
733
- docType: "single-spec",
734
- parentLink: null,
735
- specLink: null,
736
- parentTokens: [],
737
- phases: [],
738
- dependsOn: dependsOnLine === null ? null : this.markerValue(dependsOnLine, "**Depends on**"),
739
- };
740
- }
741
- }
742
-
743
- // ---------------------------------------------------------------------------
744
- // composition root — the four parsers by doc-key
745
- // ---------------------------------------------------------------------------
746
-
747
- /** The composed doc-type parsers — the judge's ctx-loading parsers (one per doc key). */
748
- export const docTypeParsers: Record<DocKey, DocType<ParsedDoc>> = {
749
- "overall-spec": new OverallDocType("overall-spec"),
750
- plan: new PlanDocType("plan"),
751
- "phase-spec": new PhaseSpecDocType("phase-spec"),
752
- "single-spec": new SingleSpecDocType("single-spec"),
753
- };