@oscaner-skills/cdd-engine 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/package.json +4 -3
  4. package/src-next/__tests__/dead-decl.guard.test.ts +39 -0
  5. package/src-next/__tests__/floor.guard.test.ts +69 -0
  6. package/src-next/__tests__/issue-body.guard.test.ts +66 -0
  7. package/src-next/__tests__/phase-suffix.guard.test.ts +72 -0
  8. package/src-next/__tests__/smoke.integration.test.ts +60 -77
  9. package/src-next/__tests__/support/strip-comments.ts +99 -0
  10. package/src-next/__tests__/zero-dep.test.ts +6 -46
  11. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +39 -21
  12. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +40 -28
  13. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +40 -23
  14. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +38 -21
  15. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +21 -6
  16. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +22 -12
  17. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +23 -8
  18. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +21 -6
  19. package/src-next/contract/__tests__/declare.test.ts +251 -12
  20. package/src-next/contract/__tests__/doc.test.ts +214 -45
  21. package/src-next/contract/__tests__/dockey.guard.test.ts +58 -0
  22. package/src-next/contract/__tests__/edge-conditions.guard.test.ts +81 -0
  23. package/src-next/contract/__tests__/frontmatter.test.ts +164 -0
  24. package/src-next/contract/__tests__/judge.test.ts +410 -172
  25. package/src-next/contract/__tests__/lint.test.ts +49 -39
  26. package/src-next/contract/__tests__/project.test.ts +60 -19
  27. package/src-next/contract/__tests__/structure-pin.test.ts +186 -0
  28. package/src-next/contract/declare.ts +179 -91
  29. package/src-next/contract/doc.ts +227 -164
  30. package/src-next/contract/frontmatter.ts +233 -0
  31. package/src-next/contract/home-extractors.ts +397 -0
  32. package/src-next/contract/invariants.ts +214 -69
  33. package/src-next/contract/judge.ts +28 -19
  34. package/src-next/contract/lint.ts +5 -41
  35. package/src-next/contract/project.ts +103 -43
  36. package/src-next/contract/skill-anatomy.ts +39 -11
  37. package/src-next/face/__tests__/board-view.test.ts +318 -115
  38. package/src-next/face/__tests__/capsule.test.ts +49 -25
  39. package/src-next/face/__tests__/channel-closure.guard.test.ts +28 -1
  40. package/src-next/face/__tests__/cli.test.ts +1091 -837
  41. package/src-next/face/__tests__/face.test.ts +5 -5
  42. package/src-next/face/__tests__/install-rows.guard.test.ts +58 -0
  43. package/src-next/face/__tests__/preview.test.ts +374 -0
  44. package/src-next/face/__tests__/projection.test.ts +5 -3
  45. package/src-next/face/__tests__/repo-root.guard.test.ts +120 -0
  46. package/src-next/face/__tests__/termination.test.ts +650 -0
  47. package/src-next/face/artifacts.ts +90 -37
  48. package/src-next/face/board-view.ts +128 -138
  49. package/src-next/face/capsule.ts +30 -16
  50. package/src-next/face/cli.ts +306 -97
  51. package/src-next/face/declare.ts +15 -18
  52. package/src-next/face/gate.ts +19 -18
  53. package/src-next/face/host.ts +6 -30
  54. package/src-next/face/lifecycle.ts +213 -188
  55. package/src-next/face/preview.ts +151 -0
  56. package/src-next/face/projection.ts +4 -1
  57. package/src-next/face/route-render.ts +39 -14
  58. package/src-next/face/termination.ts +573 -0
  59. package/src-next/face/words.ts +20 -2
  60. package/src-next/infra/__tests__/infra.test.ts +49 -3
  61. package/src-next/infra/__tests__/root.test.ts +56 -0
  62. package/src-next/infra/doc-roots.ts +29 -0
  63. package/src-next/infra/root.ts +73 -0
  64. package/src-next/infra/runtime.ts +12 -65
  65. package/src-next/infra/workspace.ts +95 -5
  66. package/src-next/render/__tests__/render.test.ts +92 -41
  67. package/src-next/render/__tests__/skeleton.test.ts +282 -64
  68. package/src-next/render/issue-body.ts +5 -2
  69. package/src-next/render/skeleton.ts +155 -90
  70. package/src-next/render/templates.ts +51 -56
  71. package/src-next/session/__tests__/graph.test.ts +11 -4
  72. package/src-next/session/__tests__/ledger.test.ts +3 -2
  73. package/src-next/session/__tests__/next.test.ts +100 -8
  74. package/src-next/session/__tests__/preflight.test.ts +79 -25
  75. package/src-next/session/__tests__/round-naming.test.ts +142 -0
  76. package/src-next/session/__tests__/run.test.ts +140 -128
  77. package/src-next/session/__tests__/wave.test.ts +11 -4
  78. package/src-next/session/ledger.ts +96 -24
  79. package/src-next/session/next.ts +116 -15
  80. package/src-next/session/preflight.ts +41 -10
  81. package/src-next/session/round-naming.ts +84 -0
  82. package/src-next/session/run.ts +24 -20
  83. package/templates/report/issue-body.json +0 -46
  84. package/src-next/face/__tests__/sync-runner.test.ts +0 -70
@@ -0,0 +1,233 @@
1
+ // packages/cdd-engine/src-next/contract/frontmatter.ts
2
+ // T1 — the front-matter head extraction chain (design spec §2.1/§2.2): a typed
3
+ // head value object plus a thin `---` fence split over the `yaml` engine. The
4
+ // extractor reads the RAW content (never the canonicalize view — front matter is
5
+ // data, not structure; the canonicalized view would silently rewrite registered
6
+ // Chinese aliases inside header values). The registry keeps the declared value
7
+ // shapes (spec §2.3); this file only carries the parse channel (fence split +
8
+ // `yaml.parse`) and the typed accessors.
9
+ //
10
+ // Zero bare functions and zero new regexes are hard guarantees of this module:
11
+ // the line split/join and the parse-error message slices are hand-rolled string
12
+ // walks, and the YAML engine does all value parsing.
13
+
14
+ import { LineCounter, parse } from "yaml";
15
+
16
+ /** A front-matter YAML parse failure — the typed, position-carrying reason a
17
+ * `FrontMatterExtractor.split` did not produce a head (D1, the position-carrying error contract:
18
+ * the extractor never swallows a parse error into a null head — the review gate
19
+ * surfaces the real failure, `yaml`'s `YAMLParseError` fed through a `LineCounter`
20
+ * carries the line/column for free, we only stop throwing it away). */
21
+ export class FrontMatterParseError {
22
+ /** The one-based line of the failure inside the front-matter block. */
23
+ readonly line: number;
24
+ /** The one-based column of the failure on that line. */
25
+ readonly column: number;
26
+ /** The engine's reason, without the position clause (`Unexpected scalar at node
27
+ * end` — the position rides the typed fields, never a re-parse of the message). */
28
+ readonly reason: string;
29
+ /** The offending front-matter source line (the human-facing excerpt). */
30
+ readonly source: string;
31
+
32
+ constructor(line: number, column: number, reason: string, source: string) {
33
+ this.line = line;
34
+ this.column = column;
35
+ this.reason = reason;
36
+ this.source = source;
37
+ }
38
+ }
39
+
40
+ /** A parsed front-matter head — the typed accessor surface over the YAML record.
41
+ * A missing key, a non-scalar value (a list, a mapping, a bare number) and an
42
+ * unparseable block all read as `null`: the head carries only scalar facts. An
43
+ * UNPARSEABLE block additionally carries its `parseError` — the gate distinguishes
44
+ * a genuinely absent key from a malformed block (D1, the false-positive fix). */
45
+ export class FrontMatterHead {
46
+ /** The parsed front-matter record, or null when no head was extracted. */
47
+ readonly #data: Record<string, unknown> | null;
48
+ /** The front-matter parse failure that prevented a head, or null. */
49
+ readonly #parseError: FrontMatterParseError | null;
50
+
51
+ /** Wrap one parsed front-matter record (null for "no head"); the parse error the
52
+ * head carries when the block could not be parsed (null by default). */
53
+ constructor(
54
+ data: Record<string, unknown> | null,
55
+ parseError: FrontMatterParseError | null = null,
56
+ ) {
57
+ this.#data = data;
58
+ this.#parseError = parseError;
59
+ }
60
+
61
+ /** The front-matter parse failure, or null when the block parsed (or no head). */
62
+ get parseError(): FrontMatterParseError | null {
63
+ return this.#parseError;
64
+ }
65
+
66
+ /** The scalar value of one front-matter key — null for a missing key, a
67
+ * non-scalar YAML value (list / mapping / number / boolean) or a null literal. */
68
+ value(key: string): string | null {
69
+ if (this.#data === null) return null;
70
+ const raw = this.#data[key];
71
+ if (typeof raw !== "string") return null;
72
+ return raw;
73
+ }
74
+
75
+ /** The document title (`title:`). */
76
+ get title(): string | null {
77
+ return this.value("title");
78
+ }
79
+
80
+ /** The machine doc-type identity (`doc-type:`) — a `DOC_TYPE_VALUES` member in a conforming document. */
81
+ get docType(): string | null {
82
+ return this.value("doc-type");
83
+ }
84
+
85
+ /** The version token (`version:`, the `v<major>.<minor>` form). */
86
+ get version(): string | null {
87
+ return this.value("version");
88
+ }
89
+
90
+ /** The ISO date (`date:`, the `yyyy-mm-dd` form). */
91
+ get date(): string | null {
92
+ return this.value("date");
93
+ }
94
+
95
+ /** The status literal (`status:`, the declared per-doc-type enum). */
96
+ get status(): string | null {
97
+ return this.value("status");
98
+ }
99
+
100
+ /** The author line (`author:`). */
101
+ get author(): string | null {
102
+ return this.value("author");
103
+ }
104
+
105
+ /** The plan's design-spec target path (`spec:`). */
106
+ get spec(): string | null {
107
+ return this.value("spec");
108
+ }
109
+
110
+ /** The Class-B parent-overall target path (`parent-program:`). */
111
+ get parentProgram(): string | null {
112
+ return this.value("parent-program");
113
+ }
114
+
115
+ /** The Class-B version token (`parent-version:`, the `v<major>.<minor>` form). */
116
+ get parentVersion(): string | null {
117
+ return this.value("parent-version");
118
+ }
119
+
120
+ /** The `depends-on:` front-matter key value. */
121
+ get dependsOn(): string | null {
122
+ return this.value("depends-on");
123
+ }
124
+
125
+ /** The plan base-line value (`base:`). */
126
+ get base(): string | null {
127
+ return this.value("base");
128
+ }
129
+
130
+ /** The single-spec issues line (`issues:`). */
131
+ get issues(): string | null {
132
+ return this.value("issues");
133
+ }
134
+ }
135
+
136
+ /** The front-matter split of a document — the fence split + `yaml.parse` (spec
137
+ * §2.2's selection: one YAML engine for the whole repo, a ~10-line fence split,
138
+ * no front-matter library). Reads the RAW original content verbatim; the body is
139
+ * everything after the second `---` fence. */
140
+ // biome-ignore lint/complexity/noStaticOnlyClass: the plan-mandated static split surface — the zero-bare-function discipline admits no standalone split helpers.
141
+ export class FrontMatterExtractor {
142
+ /** Split one document into its typed head and body. With no opening fence on
143
+ * line zero, no closing fence, an unparseable block or a non-record block,
144
+ * every head value reads null and the body is the original content. An
145
+ * UNPARSEABLE block (D1) additionally carries its `FrontMatterParseError` on
146
+ * the head — the failure is typed and positioned, never a silent null. */
147
+ static split(content: string): { head: FrontMatterHead; body: string } {
148
+ const lines = FrontMatterExtractor.lineSplit(content);
149
+ if (lines.length === 0 || lines[0].trim() !== "---") {
150
+ return { head: new FrontMatterHead(null), body: content };
151
+ }
152
+ const closing = lines.findIndex((line, index) => index > 0 && line.trim() === "---");
153
+ if (closing === -1) return { head: new FrontMatterHead(null), body: content };
154
+ const yamlLines = lines.slice(1, closing);
155
+ const yamlText = FrontMatterExtractor.lineJoin(yamlLines);
156
+ const lineCounter = new LineCounter();
157
+ let parsed: unknown;
158
+ try {
159
+ parsed = parse(yamlText, { lineCounter });
160
+ } catch (err) {
161
+ return {
162
+ // D1: the parse failure travels as a typed, positioned error — the gate
163
+ // reports the real YAML failure, never the "no doc-type" misread a null
164
+ // head would otherwise trigger.
165
+ head: new FrontMatterHead(null, FrontMatterExtractor.#parseErrorOf(err, yamlLines)),
166
+ body: content,
167
+ };
168
+ }
169
+ // A non-record parse (a scalar block, a sequence) is not a head — every
170
+ // value reads null and the body stays the original content. A null parse
171
+ // (an empty front-matter block) yields the empty head with the post-fence
172
+ // body: the fence split itself succeeded.
173
+ if (parsed !== null && (typeof parsed !== "object" || Array.isArray(parsed))) {
174
+ return { head: new FrontMatterHead(null), body: content };
175
+ }
176
+ return {
177
+ head: new FrontMatterHead(parsed as Record<string, unknown> | null),
178
+ body: FrontMatterExtractor.lineJoin(lines.slice(closing + 1)),
179
+ };
180
+ }
181
+
182
+ /** One thrown YAML parse error → the typed failure: the position from the
183
+ * engine's `linePos` (fed by the `LineCounter`), the reason without its
184
+ * position clause (string ops — this module carries zero regexes) and the
185
+ * offending source line from the block itself. */
186
+ static #parseErrorOf(err: unknown, yamlLines: readonly string[]): FrontMatterParseError {
187
+ const message = err instanceof Error ? err.message : "YAML parse error";
188
+ // The engine's message head ends with " at line <n>, column <m>: " — the
189
+ // position is a typed field below, so the reason drops the clause. Both
190
+ // slices are hand-rolled string walks: this module carries zero regexes and
191
+ // the Task 1 checkable also pins the whole `String#split` family to zero.
192
+ const reason = FrontMatterExtractor.#beforeFirst(
193
+ FrontMatterExtractor.#beforeFirst(message, "\n"),
194
+ " at line ",
195
+ ).trim();
196
+ const position = (err as { linePos?: readonly { line: number; col: number }[] }).linePos?.[0];
197
+ const line = position?.line ?? 0;
198
+ const source = line > 0 ? (yamlLines[line - 1] ?? "") : "";
199
+ return new FrontMatterParseError(line, position?.col ?? 0, reason, source);
200
+ }
201
+
202
+ /** The text before the first occurrence of `separator` — the hand-rolled
203
+ * slice (the whole string on no occurrence), the string-walk counterpart of
204
+ * the retired `String#split` calls. */
205
+ static #beforeFirst(text: string, separator: string): string {
206
+ const index = text.indexOf(separator);
207
+ return index === -1 ? text : text.slice(0, index);
208
+ }
209
+
210
+ /** Split a document into its lines — the hand-rolled split (the zero-regex
211
+ * discipline bans `String#split`'s word here). */
212
+ static lineSplit(content: string): string[] {
213
+ const lines: string[] = [];
214
+ let start = 0;
215
+ for (let index = 0; index < content.length; index++) {
216
+ if (content[index] !== "\n") continue;
217
+ lines.push(content.slice(start, index));
218
+ start = index + 1;
219
+ }
220
+ lines.push(content.slice(start));
221
+ return lines;
222
+ }
223
+
224
+ /** Join lines with single `\n` separators — the hand-rolled join. */
225
+ static lineJoin(lines: readonly string[]): string {
226
+ let out = "";
227
+ for (let index = 0; index < lines.length; index++) {
228
+ if (index > 0) out += "\n";
229
+ out += lines[index];
230
+ }
231
+ return out;
232
+ }
233
+ }
@@ -0,0 +1,397 @@
1
+ // packages/cdd-engine/src-next/contract/home-extractors.ts
2
+ // T3 — the home-driven generic extractors (design spec §3.2): one class per home
3
+ // surface. Each class implements the FIXED structural rule of its home (the task
4
+ // block head + `- **Key**:` fields + `- ` steps, the numbered design headings,
5
+ // the graph edge lines, the table rows, the section/facet headings); WHICH
6
+ // anchors belong to the home comes from the injected registry — the registry
7
+ // stays the single knowledge source (D26), and the hand-written per-anchor
8
+ // grammars of the old parse face (contract/doc.ts) are retired.
9
+ //
10
+ // The unified entry — extract(registry, lines) — maps each served anchor to the
11
+ // occurrence lines/segments of that element in the document (document order;
12
+ // graph edges are matched and carried on their trimmed form). Where a home's
13
+ // structure rule further decomposes an occurrence (the design numbered-heading
14
+ // number/text split), the extractor owns the decomposition too.
15
+
16
+ import type { ElementRegistry, Home, RegistryElement } from "./declare.ts";
17
+
18
+ /** The unified extraction record — each served anchor → its occurrence lines. */
19
+ export type ExtractionMap = Record<string, readonly string[]>;
20
+
21
+ /** One decomposed numbered heading — the leading number token and the heading text. */
22
+ export interface NumberedHeading {
23
+ /** The leading number token (`1` for `### 1. …`, `1.1` for `#### 1.1 …`). */
24
+ number: string;
25
+ /** The heading text after the number token. */
26
+ heading: string;
27
+ }
28
+
29
+ /** One scanned section — a rank-2 heading line plus its body lines. */
30
+ export interface ScannedSection {
31
+ /** The section heading line verbatim. */
32
+ heading: string;
33
+ /** The body lines up to the next rank-2 heading. */
34
+ lines: readonly string[];
35
+ }
36
+
37
+ /**
38
+ * The home-extractor base — the shared anchor-roster and the declared-pattern
39
+ * application both classes build on. Stateless by design: `extract` reads the
40
+ * injected registry and lines per call, so one shared instance per home services
41
+ * every consumer.
42
+ */
43
+ export abstract class HomeExtractor {
44
+ /** The home surfaces this extractor serves. */
45
+ abstract readonly homes: readonly Home[];
46
+
47
+ /** The unified extraction entry — the served anchors → their occurrence lines. */
48
+ abstract extract(registry: ElementRegistry, lines: readonly string[]): ExtractionMap;
49
+
50
+ /** The registered elements of one served home surface. */
51
+ protected elementsOf(registry: ElementRegistry, home: Home): readonly RegistryElement[] {
52
+ return registry.elements.filter((element) => element.home === home);
53
+ }
54
+
55
+ /** The element's declared value pattern compiled — the "already-declared
56
+ * value-pattern application" primitive (never a second hand-written grammar). */
57
+ protected patternOf(element: RegistryElement): RegExp | undefined {
58
+ return element.valuePattern === undefined ? undefined : new RegExp(element.valuePattern);
59
+ }
60
+
61
+ /** Append one occurrence line under an anchor — the shared map-bucket push
62
+ * (the `??=` short-hand rewritten to keep assignments out of expressions). */
63
+ protected appendBucket(out: Record<string, string[]>, anchor: string, line: string): void {
64
+ let bucket = out[anchor];
65
+ if (bucket === undefined) {
66
+ bucket = [];
67
+ out[anchor] = bucket;
68
+ }
69
+ bucket.push(line);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * The task extractor — the task home's structure rule: the `### Task N:` block
75
+ * head (with the id token it carries), the `- **Key**:` field markers and the
76
+ * `- ` step bullets / `— checkable:` clauses. The same generic walk serves the
77
+ * task-block / task-field / task-step homes; which anchors belong to each comes
78
+ * from the registry.
79
+ */
80
+ export class TaskExtractor extends HomeExtractor {
81
+ readonly homes = ["task-block", "task-field", "task-step"] as const;
82
+
83
+ extract(registry: ElementRegistry, lines: readonly string[]): ExtractionMap {
84
+ // The task block head — the declared `### Task N:` anchor yields, aligned, the
85
+ // block-head lines and the id tokens they carry (the `Task id token` vocabulary
86
+ // rides on the head; its grammar is the block-head structure — the digit run in
87
+ // the anchor's `N` slot).
88
+ const blockHead = this.elementsOf(registry, "task-block").find(
89
+ (element) => element.anchor === "### Task N:",
90
+ );
91
+ const blockPattern = blockHead === undefined ? undefined : this.patternOf(blockHead);
92
+ // The field markers — each declared `- **Key**:` anchor's own line form. Only
93
+ // the bold-key anchors are markers at the LINE level (the task-field structure
94
+ // rule: a field is a `- **Key**:` bullet); the value-shape anchors of the same
95
+ // home (`File path token` · `DependsOn none` · …) describe CELL content and
96
+ // never occur as whole lines — the judgment plane scopes them to field cells.
97
+ const fieldAnchors = this.elementsOf(registry, "task-field")
98
+ .filter((element) => element.anchor.startsWith("**"))
99
+ .map((element) => ({
100
+ anchor: element.anchor,
101
+ pattern: this.patternOf(element),
102
+ }));
103
+ // The step lines — scoped to the `**Steps**` field's continuation lines (the
104
+ // task home's structure rule: the block head owns the `- **Key**:` fields,
105
+ // the steps ride inside the Steps field), matched on their trimmed form.
106
+ const stepAnchors = this.elementsOf(registry, "task-step").map((element) => ({
107
+ anchor: element.anchor,
108
+ pattern: this.patternOf(element),
109
+ }));
110
+ const out: Record<string, string[]> = {};
111
+ const headings: string[] = [];
112
+ const ids: string[] = [];
113
+ let inStepsField = false;
114
+ for (const line of lines) {
115
+ if (blockPattern?.test(line) === true) {
116
+ headings.push(line);
117
+ const id = blockHead === undefined ? null : this.#taskIdOf(line, blockHead.anchor);
118
+ if (id !== null && ids.length < headings.length) ids.push(id);
119
+ inStepsField = false;
120
+ continue;
121
+ }
122
+ const field = fieldAnchors.find((candidate) => candidate.pattern?.test(line) === true);
123
+ if (field !== undefined) {
124
+ this.appendBucket(out, field.anchor, line);
125
+ inStepsField = field.anchor === "**Steps**";
126
+ continue;
127
+ }
128
+ if (!inStepsField) continue;
129
+ for (const candidate of stepAnchors) {
130
+ if (candidate.pattern?.test(line.trim()) !== true) continue;
131
+ this.appendBucket(out, candidate.anchor, line);
132
+ }
133
+ }
134
+ if (headings.length > 0) {
135
+ out["### Task N:"] = headings;
136
+ out["Task id token"] = ids;
137
+ }
138
+ return out;
139
+ }
140
+
141
+ /** The task number of one `### Task N:` heading — the digit run in the declared
142
+ * block-head anchor's `N` slot (no second grammar: the slot position is the
143
+ * anchor's own structure). */
144
+ #taskIdOf(heading: string, blockHeadAnchor: string): string | null {
145
+ const idSlot = blockHeadAnchor.indexOf("N");
146
+ if (idSlot === -1) return null;
147
+ const prefix = blockHeadAnchor.slice(0, idSlot);
148
+ const rest = heading.slice(prefix.length);
149
+ let end = 0;
150
+ while (end < rest.length && rest[end] >= "0" && rest[end] <= "9") end += 1;
151
+ if (end === 0) return null;
152
+ return rest.slice(0, end);
153
+ }
154
+ }
155
+
156
+ /**
157
+ * The design-body extractor — the double-layer `### N.` group / `#### N.M` item
158
+ * headings and the `## Design` / `### Acceptance criteria` leaves. The
159
+ * numbered-heading structure rule (the number token before the dot/space and the
160
+ * text after) lives here — the parse face consumes the decomposition.
161
+ */
162
+ export class DesignBodyExtractor extends HomeExtractor {
163
+ readonly homes = ["design-body"] as const;
164
+
165
+ extract(registry: ElementRegistry, lines: readonly string[]): ExtractionMap {
166
+ const out: Record<string, string[]> = {};
167
+ for (const element of this.elementsOf(registry, "design-body")) {
168
+ const pattern = this.patternOf(element);
169
+ if (pattern === undefined) continue;
170
+ const hits: string[] = [];
171
+ for (const line of lines) {
172
+ if (pattern.test(line)) hits.push(line);
173
+ }
174
+ if (hits.length > 0) out[element.anchor] = hits;
175
+ }
176
+ return out;
177
+ }
178
+
179
+ /** One `### N.` group heading's number and text (the digit before the dot, the text after). */
180
+ groupOf(heading: string): NumberedHeading {
181
+ return this.#splitHeading(heading, "### ".length, true);
182
+ }
183
+
184
+ /** One `#### N.M` item heading's composite number and text (the token before the first space, the text after). */
185
+ itemOf(heading: string): NumberedHeading {
186
+ return this.#splitHeading(heading, "#### ".length, false);
187
+ }
188
+
189
+ /** The shared numbered-heading split — the number token ends at the first dot
190
+ * (group form) or the first space (item form); the text is the trimmed rest. */
191
+ #splitHeading(heading: string, prefixLength: number, dotTerminated: boolean): NumberedHeading {
192
+ const payload = heading.slice(prefixLength);
193
+ let end = 0;
194
+ while (end < payload.length) {
195
+ const char = payload[end];
196
+ if (dotTerminated && char === ".") break;
197
+ if (!dotTerminated && (char === " " || char === "\t")) break;
198
+ end += 1;
199
+ }
200
+ const number = payload.slice(0, end);
201
+ if (end >= payload.length) return { number, heading: "" };
202
+ let text = payload.slice(end);
203
+ if (dotTerminated && text.startsWith(".")) text = text.slice(1);
204
+ return { number, heading: text.trim() };
205
+ }
206
+ }
207
+
208
+ /**
209
+ * The graph extractor — the `P1 -> P2` edge lines of the `home: "graph"` anchors.
210
+ * The edge/legend line forms are the declared value patterns; the from/to token
211
+ * grammar stays the parse face's preserved graph-edge primitive.
212
+ */
213
+ export class GraphExtractor extends HomeExtractor {
214
+ readonly homes = ["graph"] as const;
215
+
216
+ extract(registry: ElementRegistry, lines: readonly string[]): ExtractionMap {
217
+ const out: Record<string, string[]> = {};
218
+ for (const element of this.elementsOf(registry, "graph")) {
219
+ const pattern = this.patternOf(element);
220
+ if (pattern === undefined) continue;
221
+ const hits: string[] = [];
222
+ // Edge lines are matched and carried on their trimmed form — the graph
223
+ // block's raw lines may carry leading indentation the declared patterns
224
+ // don't allow.
225
+ for (const line of lines) {
226
+ const trimmed = line.trim();
227
+ if (pattern.test(trimmed)) hits.push(trimmed);
228
+ }
229
+ if (hits.length > 0) out[element.anchor] = hits;
230
+ }
231
+ return out;
232
+ }
233
+ }
234
+
235
+ /**
236
+ * The table extractor — the declared table anchors' column-header and data rows.
237
+ * Matching rides the declared row value patterns; the separator-row skip mirrors
238
+ * the parse face's table-split primitive.
239
+ */
240
+ export class TableExtractor extends HomeExtractor {
241
+ readonly homes = ["table"] as const;
242
+
243
+ extract(registry: ElementRegistry, lines: readonly string[]): ExtractionMap {
244
+ const out: Record<string, string[]> = {};
245
+ for (const element of this.elementsOf(registry, "table")) {
246
+ const pattern = this.patternOf(element);
247
+ if (pattern === undefined) continue;
248
+ const hits: string[] = [];
249
+ for (const line of lines) {
250
+ const trimmed = line.trim();
251
+ if (!trimmed.startsWith("|") || !trimmed.endsWith("|")) continue;
252
+ if (TableExtractor.isSeparatorRow(trimmed)) continue;
253
+ if (pattern.test(trimmed)) hits.push(trimmed);
254
+ }
255
+ if (hits.length > 0) out[element.anchor] = hits;
256
+ }
257
+ return out;
258
+ }
259
+
260
+ /** The separator row of a markdown table — `|` and only `-` / `:` / `|` /
261
+ * whitespace between the wrapper bars (same rule as the table-split primitive). */
262
+ static isSeparatorRow(trimmed: string): boolean {
263
+ for (let index = 1; index < trimmed.length - 1; index++) {
264
+ const char = trimmed[index];
265
+ if (char === "-" || char === ":" || char === "|" || char === " " || char === "\t") {
266
+ continue;
267
+ }
268
+ return false;
269
+ }
270
+ return trimmed.length > 2;
271
+ }
272
+
273
+ /** Whether a line is a markdown table line — a `|`-wrapped row. */
274
+ static isTableLine(trimmed: string): boolean {
275
+ return trimmed.startsWith("|") && trimmed.endsWith("|");
276
+ }
277
+
278
+ /** The table lines of a line run in document order — the table home's fixed
279
+ * structural rule (a `|`-wrapped row, the separator row excluded). The parse
280
+ * face's table reader consumes this so the table-line / separator knowledge
281
+ * lives here once, never re-derived at the parse face. */
282
+ tableLinesOf(lines: readonly string[]): readonly string[] {
283
+ const out: string[] = [];
284
+ for (const line of lines) {
285
+ const trimmed = line.trim();
286
+ if (!TableExtractor.isTableLine(trimmed)) continue;
287
+ if (TableExtractor.isSeparatorRow(trimmed)) continue;
288
+ out.push(trimmed);
289
+ }
290
+ return out;
291
+ }
292
+
293
+ /** The declared column-header line of a line run — the first table line the
294
+ * registry's `… columns` anchors claim (their declared column vocabulary), or
295
+ * null when the section's table declares no column anchor. The parse face
296
+ * consumes this so the declared-home set, not a positional guess, identifies
297
+ * the header row. */
298
+ headerLineOf(registry: ElementRegistry, lines: readonly string[]): string | null {
299
+ const tableLines = this.tableLinesOf(lines);
300
+ for (const element of this.elementsOf(registry, "table")) {
301
+ if (!element.anchor.endsWith(" columns")) continue;
302
+ const pattern = this.patternOf(element);
303
+ if (pattern === undefined) continue;
304
+ for (const line of tableLines) {
305
+ if (pattern.test(line)) return line;
306
+ }
307
+ }
308
+ return null;
309
+ }
310
+ }
311
+
312
+ /**
313
+ * The heading scanner — the section/facet home's registered heading anchors.
314
+ * The heading rank derives from the anchor's own leading `#` count and the
315
+ * occurrence must carry the same rank: a line is an occurrence only when it is a
316
+ * heading of the declared rank AND its declared value shape accepts it.
317
+ */
318
+ export class HeadingScanner extends HomeExtractor {
319
+ readonly homes = ["section", "facet"] as const;
320
+
321
+ extract(registry: ElementRegistry, lines: readonly string[]): ExtractionMap {
322
+ const out: Record<string, string[]> = {};
323
+ for (const element of this.elementsOf(registry, "section").concat(
324
+ this.elementsOf(registry, "facet"),
325
+ )) {
326
+ const rank = HeadingScanner.#rankOf(element.anchor);
327
+ if (rank === null) continue;
328
+ const pattern = this.patternOf(element);
329
+ const hits: string[] = [];
330
+ for (const line of lines) {
331
+ if (HeadingScanner.#rankOf(line) !== rank) continue;
332
+ if (pattern === undefined ? line.startsWith(element.anchor) : pattern.test(line)) {
333
+ hits.push(line);
334
+ }
335
+ }
336
+ if (hits.length > 0) out[element.anchor] = hits;
337
+ }
338
+ return out;
339
+ }
340
+
341
+ /** The registered rank-2 section headings of a line run, in document order —
342
+ * the section surface's fixed structure rule (only `##`-ranked headings are
343
+ * sections) over every registry anchor declared at that rank, whichever home
344
+ * owns it (a section-home heading, the conditional-home headings and the
345
+ * design-body `## Design` are all section surfaces). A heading whose text is
346
+ * registered in no home (an undeclared prose section) is not a section. */
347
+ sectionsOf(registry: ElementRegistry, lines: readonly string[]): ScannedSection[] {
348
+ const declared = new Set<string>();
349
+ for (const element of registry.elements) {
350
+ if (HeadingScanner.#rankOf(element.anchor) !== 2) continue;
351
+ const pattern = this.patternOf(element);
352
+ for (const line of lines) {
353
+ if (HeadingScanner.#rankOf(line) !== 2) continue;
354
+ if (pattern === undefined ? line.startsWith(element.anchor) : pattern.test(line)) {
355
+ declared.add(line);
356
+ }
357
+ }
358
+ }
359
+ return HeadingScanner.#sectionBlocks(lines, declared);
360
+ }
361
+
362
+ /** The `##` block walk — a declared rank-2 heading line opens a section that
363
+ * runs to the next rank-2 heading (the shape the parse face hands its
364
+ * consumers); an undeclared rank-2 heading closes the open section without
365
+ * opening one. */
366
+ static #sectionBlocks(lines: readonly string[], declared: ReadonlySet<string>): ScannedSection[] {
367
+ const out: ScannedSection[] = [];
368
+ let openHeading: string | null = null;
369
+ let openLines: string[] = [];
370
+ const close = (): void => {
371
+ if (openHeading !== null) out.push({ heading: openHeading, lines: openLines });
372
+ openHeading = null;
373
+ openLines = [];
374
+ };
375
+ for (const line of lines) {
376
+ if (HeadingScanner.#rankOf(line) === 2) {
377
+ close();
378
+ if (declared.has(line)) openHeading = line;
379
+ continue;
380
+ }
381
+ if (openHeading !== null) openLines.push(line);
382
+ }
383
+ close();
384
+ return out;
385
+ }
386
+
387
+ /** The heading rank of a heading line/anchor literal — the count of leading
388
+ * `#`s followed by whitespace (the heading-rank primitive), or null. */
389
+ static #rankOf(text: string): 1 | 2 | 3 | 4 | null {
390
+ let rank = 0;
391
+ while (rank < text.length && text[rank] === "#") rank += 1;
392
+ if (rank === 0 || rank > 4) return null;
393
+ const next = text[rank];
394
+ if (next !== undefined && next !== " " && next !== "\t") return null;
395
+ return rank as 1 | 2 | 3 | 4;
396
+ }
397
+ }