@oscaner-skills/cdd-engine 4.2.0 → 4.4.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 (58) hide show
  1. package/README.md +38 -9
  2. package/README.zh-CN.md +44 -10
  3. package/dist/contract/completion-criterion.js +351 -0
  4. package/dist/contract/declare.js +181 -43
  5. package/dist/contract/doc.js +84 -271
  6. package/dist/contract/frontmatter.js +2 -1
  7. package/dist/contract/home-extractors.js +49 -316
  8. package/dist/contract/invariants.js +400 -296
  9. package/dist/contract/judge.js +74 -49
  10. package/dist/contract/lint.js +3 -2
  11. package/dist/contract/liveness-signal.js +103 -0
  12. package/dist/contract/markdown-document.js +410 -0
  13. package/dist/contract/markdown-tree-types.js +6 -0
  14. package/dist/contract/markdown-tree.js +137 -0
  15. package/dist/contract/project.js +1 -1
  16. package/dist/contract/rules.js +106 -0
  17. package/dist/contract/selector-engine.js +332 -0
  18. package/dist/contract/selector-spec.js +74 -0
  19. package/dist/contract/skill-anatomy.js +29 -1
  20. package/dist/contract/task-block-grammar.js +285 -0
  21. package/dist/contract/task-blocks.js +65 -0
  22. package/dist/contract/translate.js +21 -0
  23. package/dist/contract/wave-width.js +15 -0
  24. package/dist/face/board-view.js +382 -172
  25. package/dist/face/capsule.js +73 -88
  26. package/dist/face/cli.js +152 -38
  27. package/dist/face/declare.js +42 -19
  28. package/dist/face/gate.js +119 -40
  29. package/dist/face/init.js +84 -25
  30. package/dist/face/lifecycle.js +540 -123
  31. package/dist/face/plugins.js +70 -2
  32. package/dist/face/preview.js +69 -18
  33. package/dist/face/route-render.js +60 -21
  34. package/dist/face/termination.js +135 -261
  35. package/dist/face/words.js +139 -13
  36. package/dist/infra/atomic.js +15 -0
  37. package/dist/infra/git.js +25 -0
  38. package/dist/infra/proc.js +150 -0
  39. package/dist/infra/round-log.js +104 -0
  40. package/dist/infra/runtime.js +16 -4
  41. package/dist/infra/workspace.js +7 -2
  42. package/dist/render/brief.js +15 -17
  43. package/dist/render/skeleton.js +41 -28
  44. package/dist/render/templates.js +128 -84
  45. package/dist/session/faces.js +47 -20
  46. package/dist/session/graph.js +13 -37
  47. package/dist/session/handoff-schema.js +16 -8
  48. package/dist/session/inflight.js +282 -0
  49. package/dist/session/ledger.js +603 -145
  50. package/dist/session/line-identity.js +33 -0
  51. package/dist/session/next.js +140 -80
  52. package/dist/session/pipeline.js +247 -0
  53. package/dist/session/preflight.js +276 -68
  54. package/dist/session/reviewed-identity.js +54 -0
  55. package/dist/session/round-naming.js +56 -8
  56. package/dist/session/run.js +364 -80
  57. package/dist/session/wave.js +94 -14
  58. package/package.json +13 -3
@@ -1,24 +1,32 @@
1
1
  // packages/cdd-engine/src-next/contract/invariants.ts
2
- // T4 — the invariant strategy class family (design spec §2.1): the single
3
- // judgment face. Every structural judgment of the contract plane is one strategy:
4
- // base nine — presence / uniqueness / domain / crosslink / order / continuity /
5
- // residue / hollow / selfBounded;
6
- // context — file-existence / sibling-scan / link-shape / slug-ref /
7
- // cross-doc-chain / section-scoped-domain (the six seam strategies
8
- // that absorb the old doctype classes' contextual judgment —
9
- // fourTableAudit, deviations, the identity chain, effectiveWaves).
10
- // Each strategy is one subclass of `abstract Invariant { evaluate(ctx) }`; the
11
- // judgment data is always the declared registries + the derived parse face (never
12
- // a hand-written structure prose). Judgment dispatch is the coordinator's
13
- // data-driven per-doc-key composition (judge.ts) — zero switch-case here and zero
14
- // exported behavior-carrying bare functions.
2
+ // T4/P21 — the invariant strategy class family (design spec §2.1 · P21 §3.1): the
3
+ // single judgment face. Every structural judgment is ONE strategy class, and the
4
+ // declaration surface (`contract/rules.ts`) is the rule list: each declared row
5
+ // names exactly one class here, and its `name` is verbatim the row id. The family:
6
+ // doc scope — presence (with the registration-uniqueness leg) · domain ·
7
+ // crosslink · section-order · continuity · residue · hollow ·
8
+ // file-existence · sibling-scan · link-shape · slug-ref ·
9
+ // cross-doc-chain · section-scoped-domain;
10
+ // the change-history family — change-history-version-unique ·
11
+ // front-matter-version-in-lineage ·
12
+ // change-history-row-not-in-other-table · list-marker-not-doubled;
13
+ // the identity legs — task-id-unique · phase-id-unique;
14
+ // ledger scope — closed-wave-fits-depends-on-layers · planned-tasks-vs-recorded-
15
+ // tasks (a `LedgerRule`, judged with the ledger fact bundle).
16
+ // Each doc strategy is one subclass of `abstract Invariant { evaluate(ctx) }`; each
17
+ // ledger rule extends `LedgerRuleBase` (`evaluate(ctx, ledger)`) — two scopes, two
18
+ // entry shapes. The judgment data is always the declared registries + the derived
19
+ // parse face (never hand-written structure prose). Judgment dispatch is the
20
+ // coordinator's data-driven per-doc-key composition (judge.ts) — zero switch-case
21
+ // here and zero exported behavior-carrying bare functions.
15
22
  var _a;
16
23
  import { existsSync, readdirSync, readFileSync } from "node:fs";
17
24
  import path from "node:path";
18
25
  import { ENGINE_DOC_ROOTS } from "../infra/doc-roots.js";
19
26
  import { SlugIndex } from "../infra/slug-index.js";
20
27
  import { docTypeParsers, MarkdownPrimitives } from "./doc.js";
21
- import { FrontMatterExtractor } from "./frontmatter.js";
28
+ import { RowSource } from "./translate.js";
29
+ import { MAX_TASKS_PER_WAVE } from "./wave-width.js";
22
30
  // ---------------------------------------------------------------------------
23
31
  // judgment records + the context
24
32
  // ---------------------------------------------------------------------------
@@ -96,7 +104,6 @@ export class Invariant extends MarkdownPrimitives {
96
104
  elementsOf(ctx) {
97
105
  return this.registry(ctx).elements;
98
106
  }
99
- /** The slice of one registered anchor (undefined when the anchor is not registered here). */
100
107
  sliceOf(ctx, anchor) {
101
108
  return ctx.slices.slices.find((slice) => slice.anchor === anchor);
102
109
  }
@@ -104,68 +111,62 @@ export class Invariant extends MarkdownPrimitives {
104
111
  lineCarries(slice, line) {
105
112
  return line.includes(slice.anchor) || (slice.valuePattern?.test(line) ?? false);
106
113
  }
107
- /** The lines carrying the element's anchor token literal. */
108
- anchorLines(ctx, anchor) {
109
- return ctx.lines.filter((line) => line.includes(anchor));
110
- }
111
- /** The lines carrying the element (literal anchor or declared value shape). */
112
- occurrenceLines(ctx, slice) {
113
- return ctx.lines.filter((line) => this.lineCarries(slice, line));
114
+ /** The judged document's declared element of one anchor (undefined when the
115
+ * anchor is not registered in this doc type). */
116
+ elementOf(ctx, anchor) {
117
+ return this.elementsOf(ctx).find((element) => element.anchor === anchor);
118
+ }
119
+ /** The occurrences of one element's DECLARED selector — the ONE occurrence read of
120
+ * the judgment plane: a node of the tree, never a raw line scan. An unregistered
121
+ * anchor (or an absent surface) resolves to zero nodes. */
122
+ occurrenceNodes(ctx, anchor) {
123
+ const element = this.elementOf(ctx, anchor);
124
+ if (element === undefined)
125
+ return [];
126
+ return ctx.tree.occurrences(element.selector);
127
+ }
128
+ /** The occurrence texts of one element's declared selector. */
129
+ occurrenceTexts(ctx, anchor) {
130
+ return this.occurrenceNodes(ctx, anchor).map((node) => node.text);
131
+ }
132
+ /** The value-CARRYING occurrences of an element — a node whose literal anchor
133
+ * mention stays entirely inside an inline-code span cites the token, it does not
134
+ * carry its value (the code-span boundary is read off the tree's own inline-code
135
+ * node spans, never a first/last-backtick guess). */
136
+ carrierNodes(ctx, anchor) {
137
+ return this.occurrenceNodes(ctx, anchor).filter((node) => {
138
+ if (!node.text.includes(anchor))
139
+ return true;
140
+ return node.bare.includes(anchor);
141
+ });
114
142
  }
115
- /** The lines that carry the element as a real structural occurrence — a line whose
116
- * anchor only appears as a citation (a backticked code span, or a table cell of a
117
- * non-table element) is not a carrier and is never judged as a value. */
118
- carrierLines(ctx, slice) {
119
- return ctx.lines.filter((line) => this.lineCarries(slice, line) && this.#isStructuralCarrier(line, slice));
143
+ /** The judged document's typed parse record — the tree-derived record the parse
144
+ * face produces (`doc.ts` reads the tree), narrowed by the doc key. The record is
145
+ * a projection of the tree, not a second scan: every structural read below the
146
+ * parse face is a node read. */
147
+ record(ctx, docType) {
148
+ return ctx.parsed.docType === docType
149
+ ? ctx.parsed
150
+ : null;
151
+ }
152
+ /** The doc's `## Change history` table — the ONE lineage read face all four doc
153
+ * types expose (each parse record carries it, filled by the same table-section
154
+ * read). The change-history strategies read ONLY through this accessor. */
155
+ changeHistory(ctx) {
156
+ return ctx.parsed.tables["Change history"];
157
+ }
158
+ /** The first `vX.Y` version token on a line — the lineage row's identity read. */
159
+ firstVersion(text) {
160
+ const match = text.match(/v\d+\.\d+/);
161
+ return match === null ? null : match[0];
120
162
  }
121
- #isStructuralCarrier(line, slice) {
122
- if (this.#isTableRow(line) && slice.home !== "table")
123
- return false;
124
- if (!line.includes(slice.anchor))
125
- return true;
126
- return !this.#everyAnchorMentionIsCodeSpan(line, slice.anchor);
127
- }
128
- #isTableRow(line) {
129
- const trimmed = line.trim();
130
- return trimmed.startsWith("|") && trimmed.endsWith("|");
131
- }
132
- /** Whether every literal anchor mention on the line stays inside a backtick code span. */
133
- #everyAnchorMentionIsCodeSpan(line, anchor) {
134
- return !this.#withoutCodeSpans(line).includes(anchor);
135
- }
136
- /** The line with its backtick-quoted region removed. A line's quoted content is
137
- * the region between its FIRST and LAST backtick (inclusive) — ONE contiguous
138
- * quoted fragment, the shape the doc prose actually uses: a simple `` `span` ``
139
- * and a quoted command fragment with a NESTED citation (`` `read X + the plan's
140
- * \`## Constraints\` (by the wave brief mirror)` ``) both read as one quoted region (the
141
- * find-#8 gap: the old span-by-span strip left a nested citation naked after its
142
- * opener got consumed by the outer span, judging quoted prose as a value). The
143
- * tradeoff is pinned: a line carrying TWO separate backtick spans (`` `x` … `y` ``)
144
- * also reads as ONE quoted region, so the mid-span prose between the spans is not
145
- * judged (judge.test.ts pins this — an anchor quoted only between two adjacent
146
- * spans stays invisible to the presence/domain rules; no enforced doc carries that
147
- * shape). A zero- or one-tick line carries no quoted region (unbalanced — nothing
148
- * to strip). */
149
- #withoutCodeSpans(line) {
150
- const first = line.indexOf("`");
151
- if (first === -1)
152
- return line;
153
- const last = line.lastIndexOf("`");
154
- if (first === last)
155
- return line;
156
- return line.slice(0, first) + line.slice(last + 1);
157
- }
158
- /** The parsed overall record — when the judged doc is an overall. */
159
- overall(ctx) {
160
- return ctx.docKey === "overall" ? ctx.parsed : null;
161
- }
162
- /** The parsed plan record — when the judged doc is a plan. */
163
- plan(ctx) {
164
- return ctx.docKey === "plan" ? ctx.parsed : null;
165
- }
166
- /** The parsed phase-spec record — when the judged doc is a phase-spec. */
167
- phaseSpec(ctx) {
168
- return ctx.docKey === "phase-spec" ? ctx.parsed : null;
163
+ /** The doc's Change-history row versions, in row order — the ONE lineage identity
164
+ * read every lineage strategy shares (one copy on the base, zero per-strategy
165
+ * private duplicates). */
166
+ historyVersions(ctx) {
167
+ return this.changeHistory(ctx)
168
+ .rows.map((row) => this.firstVersion(row[0] ?? ""))
169
+ .filter((version) => version !== null);
169
170
  }
170
171
  /** The identity index every slug-keyed strategy looks up through — the caller's
171
172
  * injected index when present, else one scan over the SAME fs seam every other
@@ -176,8 +177,7 @@ export class Invariant extends MarkdownPrimitives {
176
177
  }
177
178
  /** The three-table section heading anchors of the overall (registry-declared). */
178
179
  overallTableHeadings(ctx) {
179
- const headings = this.overall(ctx);
180
- if (headings === null)
180
+ if (ctx.docKey !== "overall")
181
181
  return [];
182
182
  const declared = ctx.registries.overall.elements
183
183
  .filter((element) => element.home === "section" && element.anchor.startsWith("## "))
@@ -201,6 +201,65 @@ const PRESENCE_HOMES = new Set([
201
201
  "design-body",
202
202
  "conditional",
203
203
  ]);
204
+ /** The ledger-scope strategy base — the two cross-ledger rules' shared seam. Kept
205
+ * separate from `Invariant` on purpose: a ledger rule's judgment entry takes the
206
+ * ledger fact bundle as a SECOND argument (`evaluate(ctx, ledger)`), so it can never
207
+ * ride the doc-scope policy composition (two scopes, two gates, two entry shapes). */
208
+ export class LedgerRuleBase {
209
+ /** The single finding-construction point (one home per scope). */
210
+ finding(ctx, field, message, fix) {
211
+ return { path: ctx.path, field, message, fix, kind: this.name };
212
+ }
213
+ }
214
+ /** closed-wave-fits-depends-on-layers — a closed wave stays inside one DependsOn layer.
215
+ * The wave's members must share ONE layer of the plan's topological decomposition;
216
+ * a wave spanning two layers was dispatched against a plan whose edges moved under
217
+ * the closed ledgers. The read is a SUBSET one: a wave whose members all sit in one
218
+ * layer fits even when it does not fill that layer (`{2}` against `[{1},{2,3}]` is
219
+ * green) — the append-wave dispatch relies on the same liberal read. */
220
+ export class LedgerLayeringRule extends LedgerRuleBase {
221
+ name = "closed-wave-fits-depends-on-layers";
222
+ evaluate(ctx, ledger) {
223
+ const findings = [];
224
+ for (const wave of ledger.closedWaves) {
225
+ if (wave.length === 0)
226
+ continue;
227
+ const fits = ledger.layers.some((layer) => wave.every((id) => layer.includes(id)));
228
+ if (fits)
229
+ continue;
230
+ const layers = ledger.layers.map((layer) => `{${layer.join(",")}}`).join(" ");
231
+ findings.push(this.finding(ctx, "closed Waves", `the closed wave {${wave.join(",")}} spans more than one DependsOn layer (${layers})`, "keep a wave on one topological layer — add the missing DependsOn edges so the batch is one layer"));
232
+ }
233
+ return findings;
234
+ }
235
+ }
236
+ /** planned-tasks-vs-recorded-tasks — the ledger's recorded tasks must still exist in
237
+ * the plan. ONE direction only: a plan always LEADS the ledger (every undispatched
238
+ * task sits in the plan), so neither task numbering nor dependency layers can tell
239
+ * "the next wave" from "a stranded task" — the old id-based window flagged the
240
+ * normal next-wave state and locked the whole dispatch chain (the P21 dogfood
241
+ * defect). That direction therefore carries zero judgment (an `info (plan leads
242
+ * ledger by N tasks)` row only). The one real disagreement is a recorded task the
243
+ * plan no longer carries — an executed task rewritten out of the plan. */
244
+ export class LedgerTaskSetRule extends LedgerRuleBase {
245
+ name = "planned-tasks-vs-recorded-tasks";
246
+ evaluate(ctx, ledger) {
247
+ const findings = [];
248
+ const planned = new Set(ledger.planTasks);
249
+ for (const id of ledger.recordedTasks) {
250
+ if (planned.has(id))
251
+ continue;
252
+ findings.push(this.finding(ctx, "Task id", `the ledger records Task ${id}, which the plan no longer carries`, "restore the task block or remove the ledger row"));
253
+ }
254
+ return findings;
255
+ }
256
+ /** How many planned tasks the ledger has not recorded yet — the `plan leads ledger`
257
+ * info count (a prompt, never a finding). */
258
+ static planAhead(ledger) {
259
+ const recorded = new Set(ledger.recordedTasks);
260
+ return ledger.planTasks.filter((id) => !recorded.has(id)).length;
261
+ }
262
+ }
204
263
  /** presence — every required structural element of the declared registry must occur. */
205
264
  export class PresenceInvariant extends Invariant {
206
265
  name = "presence";
@@ -211,10 +270,16 @@ export class PresenceInvariant extends Invariant {
211
270
  continue;
212
271
  if (PRESENCE_HOMES.has(element.home) === false)
213
272
  continue;
273
+ // The task-block sections are judged PER BLOCK below (`taskFieldPresence`), so
274
+ // a legacy-shape plan (whose fields carry no `#### Key` line) is never reported
275
+ // as a whole-document absence — the reader normalized both shapes into the same
276
+ // block record, and that record is the presence basis.
277
+ if (element.home === "task-field" && element.anchor.startsWith("#### "))
278
+ continue;
214
279
  const slice = this.sliceOf(ctx, element.anchor);
215
280
  if (slice === undefined)
216
281
  continue;
217
- if (this.#derivedPresenceHolds(ctx, slice))
282
+ if (this.#derivedPresenceHolds(ctx, element, slice))
218
283
  continue;
219
284
  // The front-matter-home elements judge the typed head record (the §2.2
220
285
  // delivery seam — NEVER the body line scan: front matter is data, and a
@@ -225,40 +290,80 @@ export class PresenceInvariant extends Invariant {
225
290
  findings.push(this.finding(ctx, element.anchor, `missing required element: ${element.anchor}`, `add the "${element.anchor}" key to the document's front matter`));
226
291
  continue;
227
292
  }
228
- if (this.occurrenceLines(ctx, slice).length === 0) {
293
+ if (this.occurrenceNodes(ctx, element.anchor).length === 0) {
229
294
  findings.push(this.finding(ctx, element.anchor, `missing required element: ${element.anchor}`, `add the "${element.anchor}" ${element.home} element to the document`));
230
295
  }
231
296
  }
232
297
  findings.push(...this.taskFieldPresence(ctx));
298
+ // The registration uniqueness leg folded into presence (one rule = one strategy):
299
+ // a required element that registers MORE than once is the duplicate side of the
300
+ // same "registers exactly once" judgment the missing side above reports.
301
+ findings.push(...this.headingUniqueness(ctx));
302
+ return findings;
303
+ }
304
+ /** Heading-style anchors: a duplicated heading line text is a duplicate registration. */
305
+ headingUniqueness(ctx) {
306
+ const findings = [];
307
+ const seenLine = new Set();
308
+ for (const element of this.elementsOf(ctx)) {
309
+ if (!element.anchor.startsWith("#"))
310
+ continue;
311
+ // A task-block section heading repeats once per task block by design — its
312
+ // `#### Key` identity is judged per block, never as a whole-document duplicate.
313
+ if (element.home === "task-field")
314
+ continue;
315
+ const slice = this.sliceOf(ctx, element.anchor);
316
+ if (slice === undefined)
317
+ continue;
318
+ for (const line of this.occurrenceTexts(ctx, element.anchor)) {
319
+ const trimmed = line.trim();
320
+ const key = `${element.anchor}::${trimmed}`;
321
+ if (seenLine.has(key)) {
322
+ findings.push(this.finding(ctx, element.anchor, `duplicate heading registration: ${trimmed}`, `keep "${trimmed}" in exactly one place`));
323
+ }
324
+ seenLine.add(key);
325
+ }
326
+ }
233
327
  return findings;
234
328
  }
235
329
  /** A required surface whose occurrence is established by the parsed structure rather
236
- * than a line scan — the plan's `Task id token` only ever appears inside the
237
- * `### Task N:` headings, so it is present iff a task block exists. */
238
- #derivedPresenceHolds(ctx, slice) {
239
- if (slice.home !== "task-block" || slice.anchor.startsWith("#"))
240
- return false;
241
- return (this.plan(ctx)?.taskBlocks.length ?? 0) > 0;
330
+ * than a token scan — the plan's `Task id token` only ever appears inside the
331
+ * `### Task N:` headings, so it is present iff a task block exists; a token inside
332
+ * a required field (`File path token`) is present iff its owning field carries a
333
+ * value line (the field's own key presence is the block-presence leg, and an
334
+ * unfilled placeholder value is the author's fact, not a missing element). */
335
+ #derivedPresenceHolds(ctx, element, slice) {
336
+ if (slice.home === "task-block" && !slice.anchor.startsWith("#")) {
337
+ return ctx.tree.tasks().length > 0;
338
+ }
339
+ if (slice.home === "task-field" && !slice.anchor.startsWith("#### ")) {
340
+ const parent = element.selector.from;
341
+ if (parent === "root")
342
+ return false;
343
+ return ctx.tree
344
+ .occurrences(parent)
345
+ .some((field) => field.lines.some((line) => line.trim() !== ""));
346
+ }
347
+ return false;
242
348
  }
243
349
  /** The per-task-block required field keys — derived from the plan registry's
244
- * task-field elements (the bold `**Key**` markers; the `File path token` and
245
- * DependsOn-value leaves carry non-key anchors, and `Step action` lives on the
246
- * task-step home). Single-source: a field key added to the registry is enforced
247
- * per task block automatically. */
350
+ * task-field section elements (the `#### Key` headings; the `File path token`,
351
+ * `DependsOn none` / `DependsOn id` leaves carry non-key anchors, and `Step
352
+ * action` lives on the task-step home). The reader normalizes the legacy bullet
353
+ * shape into the same keys, so one declaration enforces both shapes per block.
354
+ * Single-source: a section added to the registry is enforced per task block
355
+ * automatically. */
248
356
  #requiredFieldKeys(ctx) {
249
357
  return this.elementsOf(ctx)
250
- .filter((element) => element.home === "task-field" &&
251
- element.anchor.startsWith("**") &&
252
- element.anchor.endsWith("**"))
253
- .map((element) => element.anchor.slice(2, -2));
358
+ .filter((element) => element.home === "task-field" && element.anchor.startsWith("#### "))
359
+ .map((element) => element.anchor.slice("#### ".length));
254
360
  }
255
361
  /** The per-task-block field surface — every required task-field key of a plan. */
256
362
  taskFieldPresence(ctx) {
257
- const data = this.plan(ctx);
258
- if (data === null)
363
+ if (ctx.docKey !== "plan")
259
364
  return [];
260
365
  const findings = [];
261
- for (const block of data.taskBlocks) {
366
+ for (const block of ctx.tree.tasks()) {
262
367
  const keys = new Set(block.fields.map((field) => field.key));
263
368
  for (const key of this.#requiredFieldKeys(ctx)) {
264
369
  if (!keys.has(key)) {
@@ -269,74 +374,58 @@ export class PresenceInvariant extends Invariant {
269
374
  return findings;
270
375
  }
271
376
  }
272
- /** uniqueness — every identity-carrying surface registers exactly once. */
273
- export class UniquenessInvariant extends Invariant {
274
- name = "uniqueness";
377
+ /** change-history-version-unique — a change-history version label registers once. */
378
+ export class ChangeHistoryVersionUniqueInvariant extends Invariant {
379
+ name = "change-history-version-unique";
275
380
  evaluate(ctx) {
276
- const findings = [...this.headingUniqueness(ctx), ...this.derivedUniqueness(ctx)];
277
- return findings;
278
- }
279
- /** Heading-style anchors: a duplicated heading line text is a duplicate registration. */
280
- headingUniqueness(ctx) {
281
381
  const findings = [];
282
- const seenLine = new Set();
283
- for (const element of this.elementsOf(ctx)) {
284
- if (!element.anchor.startsWith("#"))
285
- continue;
286
- const slice = this.sliceOf(ctx, element.anchor);
287
- if (slice === undefined)
288
- continue;
289
- for (const line of this.occurrenceLines(ctx, slice)) {
290
- const trimmed = line.trim();
291
- const key = `${element.anchor}::${trimmed}`;
292
- if (seenLine.has(key)) {
293
- findings.push(this.finding(ctx, element.anchor, `duplicate heading registration: ${trimmed}`, `keep "${trimmed}" in exactly one place`));
294
- }
295
- seenLine.add(key);
382
+ const seenVersions = new Set();
383
+ for (const row of this.changeHistory(ctx).rows) {
384
+ const version = this.firstVersion(row[0] ?? "");
385
+ if (version !== null && seenVersions.has(version)) {
386
+ findings.push(this.finding(ctx, "Change history", `duplicate change-history version: ${version} registers more than once`, "keep each lineage version in exactly one Change-history row"));
296
387
  }
388
+ if (version !== null)
389
+ seenVersions.add(version);
297
390
  }
298
391
  return findings;
299
392
  }
300
- /** The derived identity rows: task ids, phase ids, change-history versions. */
301
- derivedUniqueness(ctx) {
393
+ }
394
+ /** task-id-unique — every `### Task N:` id registers exactly once (plan). */
395
+ export class TaskIdUniqueInvariant extends Invariant {
396
+ name = "task-id-unique";
397
+ evaluate(ctx) {
398
+ if (ctx.docKey !== "plan")
399
+ return [];
302
400
  const findings = [];
303
- if (ctx.docKey === "plan") {
304
- const seenIds = new Set();
305
- for (const block of this.plan(ctx)?.taskBlocks ?? []) {
306
- if (seenIds.has(block.id)) {
307
- findings.push(this.finding(ctx, "### Task N:", `duplicate task id: Task ${block.id} registers more than once`, "keep each task id in exactly one task block"));
308
- }
309
- seenIds.add(block.id);
401
+ const seenIds = new Set();
402
+ for (const block of ctx.tree.tasks()) {
403
+ if (seenIds.has(block.id)) {
404
+ findings.push(this.finding(ctx, "### Task N:", `duplicate task id: Task ${block.id} registers more than once`, "keep each task id in exactly one task block"));
310
405
  }
406
+ seenIds.add(block.id);
311
407
  }
312
- if (ctx.docKey === "overall") {
313
- const data = this.overall(ctx);
314
- if (data !== null) {
315
- const seenPhases = new Set();
316
- for (const phase of data.chain.phases) {
317
- const lower = phase.id.toLowerCase();
318
- if (seenPhases.has(lower)) {
319
- findings.push(this.finding(ctx, "Phase inventory", `duplicate phase registration: ${phase.id} registers more than once`, "keep each phase id in exactly one Phase-inventory row"));
320
- }
321
- seenPhases.add(lower);
322
- }
323
- const seenVersions = new Set();
324
- for (const row of data.tables["Change history"].rows) {
325
- const version = this.#firstVersion(row[0] ?? "");
326
- if (version !== null && seenVersions.has(version)) {
327
- findings.push(this.finding(ctx, "Change history", `duplicate change-history version: ${version} registers more than once`, "keep each lineage version in exactly one Change-history row"));
328
- }
329
- if (version !== null)
330
- seenVersions.add(version);
331
- }
408
+ return findings;
409
+ }
410
+ }
411
+ /** phase-id-unique — every Phase-inventory phase id registers exactly once (overall). */
412
+ export class PhaseIdUniqueInvariant extends Invariant {
413
+ name = "phase-id-unique";
414
+ evaluate(ctx) {
415
+ const data = this.record(ctx, "overall");
416
+ if (data === null)
417
+ return [];
418
+ const findings = [];
419
+ const seenPhases = new Set();
420
+ for (const phase of data.chain.phases) {
421
+ const lower = phase.id.toLowerCase();
422
+ if (seenPhases.has(lower)) {
423
+ findings.push(this.finding(ctx, "Phase inventory", `duplicate phase registration: ${phase.id} registers more than once`, "keep each phase id in exactly one Phase-inventory row"));
332
424
  }
425
+ seenPhases.add(lower);
333
426
  }
334
427
  return findings;
335
428
  }
336
- #firstVersion(text) {
337
- const match = text.match(/v\d+\.\d+/);
338
- return match === null ? null : match[0];
339
- }
340
429
  }
341
430
  /** domain — every value an anchor literal carries must conform to its declared shape. */
342
431
  export class DomainInvariant extends Invariant {
@@ -378,14 +467,30 @@ export class DomainInvariant extends Invariant {
378
467
  // a table row or a heading must match its declared pattern. A prose citation
379
468
  // (a backticked code-span mention, or a table cell of a non-table element) is
380
469
  // not a carrier and is never judged as a value.
381
- for (const line of this.carrierLines(ctx, slice)) {
382
- if (!slice.valuePattern.test(line)) {
383
- findings.push(this.finding(ctx, element.anchor, `value outside the declared domain: ${line.trim()}`, `make the line match ${slice.valuePattern.source}`));
384
- }
470
+ for (const node of this.carrierNodes(ctx, element.anchor)) {
471
+ if (slice.valuePattern.test(node.text))
472
+ continue;
473
+ // The declared value may sit in a captured sub-span of the located node —
474
+ // the task id inside its `### Task N:` heading. The node is the locator, the
475
+ // capture is the value the declared shape judges.
476
+ if (DomainInvariant.#capturesShape(element.selector.match, node.text, slice.valuePattern))
477
+ continue;
478
+ findings.push(this.finding(ctx, element.anchor, `value outside the declared domain: ${node.text.trim()}`, `make the node match ${slice.valuePattern.source}`));
385
479
  }
386
480
  }
387
481
  return findings;
388
482
  }
483
+ /** Whether the element's locator capture the declared shape accepts — a value
484
+ * that lives inside the located node (the task id in its heading). */
485
+ static #capturesShape(match, text, pattern) {
486
+ if (!(match instanceof RegExp))
487
+ return false;
488
+ const capture = match.exec(text);
489
+ if (capture === null || capture.length < 2)
490
+ return false;
491
+ const value = capture[1];
492
+ return value !== undefined && pattern.test(value);
493
+ }
389
494
  /** Whether the skeleton fills the front-matter anchor with a placeholder — the
390
495
  * projection's own §4.2 slot classification (the link slots' `<…>` scalar and
391
496
  * the content slots' `:::fill`), so the exemption covers exactly the keys that
@@ -410,7 +515,7 @@ export class CrosslinkInvariant extends Invariant {
410
515
  }
411
516
  /** The overall's in-doc reference surfaces: issue rows + graph edges + dependency cells. */
412
517
  overallCrosslinks(ctx) {
413
- const data = this.overall(ctx);
518
+ const data = this.record(ctx, "overall");
414
519
  if (data === null)
415
520
  return [];
416
521
  const findings = [];
@@ -422,8 +527,9 @@ export class CrosslinkInvariant extends Invariant {
422
527
  findings.push(this.finding(ctx, "Issue inventory", `issue row phase ${JSON.stringify(phaseCell)} is not a Phase-inventory id`, "set the Issue-inventory Phase column to a registered phase id"));
423
528
  }
424
529
  }
425
- // Graph edges: every from/to token must be a registered phase id.
426
- for (const edge of data.graphEdges) {
530
+ // Graph edges: every from/to token must be a registered phase id (the tree's
531
+ // edge read — the graph surface's ONE parse).
532
+ for (const edge of ctx.tree.edges()) {
427
533
  if (!ids.has(edge.from.toLowerCase())) {
428
534
  findings.push(this.finding(ctx, "Dependency graph", `graph edge from ${edge.from} is not a Phase-inventory id`, `register ${edge.from} in the Phase inventory or fix the edge`));
429
535
  }
@@ -445,12 +551,12 @@ export class CrosslinkInvariant extends Invariant {
445
551
  * reference gate. Prose task mentions are NOT consumed here (T6): the WARN-only
446
552
  * observation belongs to the reference-lint pass, never a hard finding. */
447
553
  planCrosslinks(ctx) {
448
- const data = this.plan(ctx);
449
- if (data === null)
554
+ if (ctx.docKey !== "plan")
450
555
  return [];
451
556
  const findings = [];
452
- const ids = new Set(data.taskBlocks.map((block) => block.id));
453
- for (const block of data.taskBlocks) {
557
+ const blocks = ctx.tree.tasks();
558
+ const ids = new Set(blocks.map((block) => block.id));
559
+ for (const block of blocks) {
454
560
  const dependsOn = this.#dependsOnOf(block);
455
561
  for (const id of dependsOn) {
456
562
  if (!ids.has(id)) {
@@ -480,21 +586,16 @@ export class CrosslinkInvariant extends Invariant {
480
586
  return tokens;
481
587
  }
482
588
  }
483
- /** order — structural surfaces appear in their declared sequence. */
484
- export class OrderInvariant extends Invariant {
485
- name = "order";
589
+ /** section-order — rank-2 headings follow the declared registry sequence. */
590
+ export class SectionOrderInvariant extends Invariant {
591
+ name = "section-order";
486
592
  evaluate(ctx) {
487
- return [...this.sectionOrder(ctx), ...this.historyOrder(ctx)];
488
- }
489
- /** Rank-2 headings must follow the declared registry order (design before constraints…). */
490
- sectionOrder(ctx) {
491
593
  const findings = [];
492
594
  const anchors = this.elementsOf(ctx)
493
595
  .filter((element) => element.anchor.startsWith("## "))
494
596
  .map((element) => element.anchor);
495
- const docSections = this.#docSections(ctx);
496
597
  let previous = -1;
497
- for (const section of docSections) {
598
+ for (const section of ctx.parsed.sections) {
498
599
  const match = this.#registryAnchorFor(section, anchors, ctx);
499
600
  if (match === null)
500
601
  continue;
@@ -505,35 +606,6 @@ export class OrderInvariant extends Invariant {
505
606
  }
506
607
  return findings;
507
608
  }
508
- /** The overall's change-history rows must be version-ascending — oldest first, the
509
- * latest revision last (the canonical repo format). */
510
- historyOrder(ctx) {
511
- const data = this.overall(ctx);
512
- if (data === null)
513
- return [];
514
- const findings = [];
515
- const versions = data.tables["Change history"].rows
516
- .map((row) => this.#versionPair(row[0] ?? ""))
517
- .filter((pair) => pair !== null);
518
- for (let i = 1; i < versions.length; i++) {
519
- const earlier = versions[i - 1];
520
- const later = versions[i];
521
- if (earlier.major > later.major ||
522
- (earlier.major === later.major && earlier.minor > later.minor)) {
523
- findings.push(this.finding(ctx, "Change history", `change-history rows are not version-ascending (v${earlier.major}.${earlier.minor} above v${later.major}.${later.minor})`, "order the Change-history rows oldest-first"));
524
- break;
525
- }
526
- }
527
- return findings;
528
- }
529
- /** The document's rank-2 section blocks in document order. */
530
- #docSections(ctx) {
531
- if (ctx.docKey === "overall")
532
- return ctx.parsed.sections;
533
- if (ctx.docKey === "plan")
534
- return ctx.parsed.sections;
535
- return ctx.parsed.sections;
536
- }
537
609
  /** The registry anchor a doc section heading conforms to (null when unregistered). */
538
610
  #registryAnchorFor(section, anchors, ctx) {
539
611
  for (let index = 0; index < anchors.length; index++) {
@@ -547,10 +619,6 @@ export class OrderInvariant extends Invariant {
547
619
  }
548
620
  return null;
549
621
  }
550
- #versionPair(text) {
551
- const match = text.match(/v(\d+)\.(\d+)/);
552
- return match === null ? null : { major: Number(match[1]), minor: Number(match[2]) };
553
- }
554
622
  }
555
623
  /** continuity — numbered surfaces are 1-indexed and contiguous. */
556
624
  export class ContinuityInvariant extends Invariant {
@@ -564,11 +632,11 @@ export class ContinuityInvariant extends Invariant {
564
632
  }
565
633
  /** Plan task ids must be exactly 1..N. */
566
634
  taskContinuity(ctx) {
567
- const data = this.plan(ctx);
568
- if (data === null || data.taskBlocks.length === 0)
635
+ const blocks = ctx.tree.tasks();
636
+ if (blocks.length === 0)
569
637
  return [];
570
638
  const findings = [];
571
- data.taskBlocks.forEach((block, index) => {
639
+ blocks.forEach((block, index) => {
572
640
  const expected = index + 1;
573
641
  if (block.id !== expected) {
574
642
  findings.push(this.finding(ctx, `Task ${block.id}`, `task numbering is not contiguous from 1 (task ${block.id} at position ${index + 1})`, "renumber the tasks so they run exactly 1..N without gaps or duplicates"));
@@ -578,7 +646,7 @@ export class ContinuityInvariant extends Invariant {
578
646
  }
579
647
  /** Phase-spec design groups (and their items) must be 1-indexed and contiguous. */
580
648
  groupContinuity(ctx) {
581
- const data = this.phaseSpec(ctx);
649
+ const data = this.record(ctx, "phase-spec");
582
650
  if (data === null || data.design.length === 0)
583
651
  return [];
584
652
  const findings = [];
@@ -615,9 +683,9 @@ export class ResidueInvariant extends Invariant {
615
683
  const slice = this.sliceOf(ctx, element.anchor);
616
684
  if (slice === undefined || slice.valuePattern === undefined)
617
685
  continue;
618
- if (this.anchorLines(ctx, owner).length > 0)
619
- continue; // the condition holds — the section is present
620
- const leaked = this.occurrenceLines(ctx, slice).length;
686
+ if (this.occurrenceNodes(ctx, owner).length > 0)
687
+ continue; // the condition holds
688
+ const leaked = this.occurrenceNodes(ctx, element.anchor).length;
621
689
  if (leaked > 0) {
622
690
  findings.push(this.finding(ctx, element.anchor, `conditional residue: ${element.anchor} content appears while ${owner} is absent`, `remove the ${element.anchor} content or add the ${owner} section`));
623
691
  }
@@ -634,29 +702,29 @@ export class HollowInvariant extends Invariant {
634
702
  }
635
703
  /** The overall's three tables: a present table section with zero data rows is hollow. */
636
704
  tableHollow(ctx) {
637
- const data = this.overall(ctx);
638
- if (data === null)
705
+ if (ctx.docKey !== "overall")
639
706
  return [];
640
707
  const findings = [];
641
708
  for (const anchor of this.overallTableHeadings(ctx)) {
642
- const headingExists = this.anchorLines(ctx, anchor).length > 0;
643
- if (!headingExists)
709
+ const headings = this.occurrenceNodes(ctx, anchor);
710
+ if (headings.length === 0)
644
711
  continue;
645
- const section = data.sections.find((s) => s.heading.includes(anchor.replace(/^## /, "")));
646
- const tableRows = section === undefined ? [] : this.tableRows(section.lines).slice(1);
647
- if (tableRows.length === 0) {
648
- findings.push(this.finding(ctx, anchor, `${anchor} section is hollow — the section heading carries no data rows`, "either add the table's data rows or remove the empty section"));
649
- }
712
+ const section = headings[0];
713
+ if (section === undefined)
714
+ continue;
715
+ const table = ctx.tree.tableUnder(section.text);
716
+ if ((table?.body.length ?? 0) > 0)
717
+ continue;
718
+ findings.push(this.finding(ctx, anchor, `${anchor} section is hollow — the section heading carries no data rows`, "either add the table's data rows or remove the empty section"));
650
719
  }
651
720
  return findings;
652
721
  }
653
722
  /** A task block that carries no keyed fields is a hollow shell. */
654
723
  taskHollow(ctx) {
655
- const data = this.plan(ctx);
656
- if (data === null)
724
+ if (ctx.docKey !== "plan")
657
725
  return [];
658
726
  const findings = [];
659
- for (const block of data.taskBlocks) {
727
+ for (const block of ctx.tree.tasks()) {
660
728
  if (block.fields.length === 0) {
661
729
  findings.push(this.finding(ctx, `Task ${block.id}`, `task ${block.id} is a hollow shell — the block carries no fields`, "fill the task block with its Object/Files/Consumes/Produces/Steps/Acceptance/DependsOn fields or delete it"));
662
730
  }
@@ -665,13 +733,13 @@ export class HollowInvariant extends Invariant {
665
733
  }
666
734
  /** The phase-spec skeleton: a present Design with no groups (or an empty conditional section). */
667
735
  designHollow(ctx) {
668
- const data = this.phaseSpec(ctx);
736
+ const data = this.record(ctx, "phase-spec");
669
737
  if (data === null)
670
738
  return [];
671
739
  const findings = [];
672
740
  const designSlice = this.sliceOf(ctx, "## Design");
673
741
  if (designSlice !== undefined &&
674
- this.anchorLines(ctx, "## Design").length > 0 &&
742
+ this.occurrenceNodes(ctx, "## Design").length > 0 &&
675
743
  data.design.length === 0) {
676
744
  findings.push(this.finding(ctx, "## Design", "the Design section is hollow — the heading carries no design groups", "add the double-layer design outline (### N. groups with #### N.M items) or remove the section"));
677
745
  }
@@ -686,65 +754,68 @@ export class HollowInvariant extends Invariant {
686
754
  return findings;
687
755
  }
688
756
  }
689
- /** selfBounded — the doc's own-scope lineage stays consistent with itself. */
690
- export class SelfBoundedInvariant extends Invariant {
691
- name = "selfBounded";
757
+ /** front-matter-version-in-lineage — the head `version:` appears in the doc's lineage.
758
+ * The ONE lineage judgment (P21 §3.1): the header value must occur somewhere among
759
+ * the Change-history row versions. Absence is the only violation — the direction,
760
+ * the endpoints and the age of the row carrying the value are the author's
761
+ * presentation choice, never a judgment input (a newest-first lineage, a
762
+ * non-monotone frozen history and an ascending one all judge the same). The fix
763
+ * names the header key, never a row to reorder. */
764
+ export class FrontMatterVersionInLineageInvariant extends Invariant {
765
+ name = "front-matter-version-in-lineage";
692
766
  evaluate(ctx) {
693
767
  const headerVersion = ctx.head.version;
694
- const historyVersions = this.#historyVersions(ctx);
695
- if (headerVersion === null || historyVersions.length === 0)
768
+ if (headerVersion === null)
696
769
  return [];
697
- const findings = [];
698
- const newest = this.#newestVersion(historyVersions);
699
- if (headerVersion !== newest) {
700
- findings.push(this.finding(ctx, "version", `the header version ${headerVersion} is not the change-history's newest row (${newest})`, "bump both the version front-matter key and the newest Change-history row together"));
701
- }
702
- if (!historyVersions.includes(headerVersion)) {
703
- findings.push(this.finding(ctx, "version", `the header version ${headerVersion} is outside the document's own lineage`, `the version front-matter key must belong to the Change-history row versions: ${historyVersions.join(", ")}`));
704
- }
705
- return findings;
706
- }
707
- /** The doc's Change-history row versions — the overall reads its parsed table,
708
- * the plan/spec read the `## Change history` section's table rows (the shared
709
- * row primitive — the P4.1 T2 isomorphic lineage: the same lineage judgment rides
710
- * all doc types). */
711
- #historyVersions(ctx) {
712
- if (ctx.docKey === "overall") {
713
- const data = this.overall(ctx);
714
- if (data === null)
715
- return [];
716
- return data.tables["Change history"].rows
717
- .map((row) => this.#firstVersion(row[0] ?? ""))
718
- .filter((version) => version !== null);
719
- }
720
- const section = ctx.docKey === "plan"
721
- ? ctx.parsed.sections.find((s) => s.heading.includes("Change history"))
722
- : ctx.parsed.sections.find((s) => s.heading.includes("Change history"));
723
- if (section === undefined)
770
+ const historyVersions = this.historyVersions(ctx);
771
+ if (historyVersions.length === 0)
724
772
  return [];
725
- return this.tableRows(section.lines)
726
- .map((row) => this.#firstVersion(row[0] ?? ""))
727
- .filter((version) => version !== null);
728
- }
729
- #firstVersion(text) {
730
- const match = text.match(/v\d+\.\d+/);
731
- return match === null ? null : match[0];
773
+ if (historyVersions.includes(headerVersion))
774
+ return [];
775
+ return [
776
+ this.finding(ctx, "version", `the header version ${headerVersion} is outside the document's own lineage`, `the version front-matter key must belong to the Change-history row versions: ${historyVersions.join(", ")}`),
777
+ ];
732
778
  }
733
- /** The newest lineage version — the numerically greatest (major, minor) row. */
734
- #newestVersion(versions) {
735
- let best = versions[0];
736
- for (const version of versions) {
737
- const [bestMajor, bestMinor] = this.#versionNumber(best);
738
- const [currentMajor, currentMinor] = this.#versionNumber(version);
739
- if (currentMajor > bestMajor || (currentMajor === bestMajor && currentMinor > bestMinor)) {
740
- best = version;
779
+ }
780
+ /** change-history-row-not-in-other-table — a change-history row stays in its table.
781
+ * Any table row OUTSIDE `## Change history` whose first cell carries a version
782
+ * token (`v1.2`) is a lineage row parked in the wrong table. */
783
+ export class RowHomeInvariant extends Invariant {
784
+ name = "change-history-row-not-in-other-table";
785
+ evaluate(ctx) {
786
+ const findings = [];
787
+ for (const section of ctx.parsed.sections) {
788
+ const slice = this.sliceOf(ctx, "## Change history");
789
+ if (slice?.valuePattern?.test(section.heading) === true)
790
+ continue;
791
+ const table = ctx.tree.tableUnder(section.heading);
792
+ const rows = [
793
+ ...(table?.header === null || table === null ? [] : [table.header]),
794
+ ...(table?.body ?? []),
795
+ ];
796
+ for (const row of rows) {
797
+ const first = row[0] ?? "";
798
+ if (!/^v\d+\.\d+$/.test(first))
799
+ continue;
800
+ findings.push(this.finding(ctx, section.heading, `a change-history row sits in ${section.heading}: ${first}`, "move the row back into the ## Change history table"));
741
801
  }
742
802
  }
743
- return best;
803
+ return findings;
744
804
  }
745
- #versionNumber(version) {
746
- const match = version.match(/v(\d+)\.(\d+)/);
747
- return match === null ? [0, 0] : [Number(match[1]), Number(match[2])];
805
+ }
806
+ /** list-marker-not-doubled — a list item carries exactly one leading marker.
807
+ * A bullet whose content starts with another bullet marker (`- - x`, `* + y`) is
808
+ * a doubled marker, not nested content. The read is the tree's `listItem` walk:
809
+ * an item whose first child is itself a list. A thematic break (`* * *` /
810
+ * `- - -` — a repeated `*` or `-` run) parses as a separator, never as a list
811
+ * item, so the tree exempts it by construction (`+` is not a thematic-break
812
+ * marker, so `+ + +` stays a doubled marker). */
813
+ export class ListMarkerInvariant extends Invariant {
814
+ name = "list-marker-not-doubled";
815
+ evaluate(ctx) {
816
+ return ctx.tree
817
+ .doubledMarkerItems()
818
+ .map((node) => this.finding(ctx, "list-marker", `the list item carries a doubled marker: ${node.text}`, "merge the doubled list marker into a single marker"));
748
819
  }
749
820
  }
750
821
  // ---------------------------------------------------------------------------
@@ -808,7 +879,7 @@ export class FileExistenceInvariant extends Invariant {
808
879
  chainLinks(ctx) {
809
880
  const links = [];
810
881
  if (ctx.docKey === "overall") {
811
- const data = this.overall(ctx);
882
+ const data = this.record(ctx, "overall");
812
883
  if (data !== null) {
813
884
  for (const phase of data.chain.phases) {
814
885
  for (const link of this.linksOnLine(phase.designCell)) {
@@ -962,7 +1033,7 @@ export class CrossDocChainInvariant extends Invariant {
962
1033
  overallChain(ctx) {
963
1034
  if (ctx.phaseId === undefined || ctx.phaseId === null)
964
1035
  return [];
965
- const data = this.overall(ctx);
1036
+ const data = this.record(ctx, "overall");
966
1037
  if (data === null)
967
1038
  return [];
968
1039
  const registered = new Set(data.chain.phases.map((phase) => phase.id.toLowerCase()));
@@ -980,8 +1051,7 @@ export class CrossDocChainInvariant extends Invariant {
980
1051
  * document (overall / phase-spec / single-spec) carrying the same slug — a
981
1052
  * single-spec pair carries no program, so the chain simply ends there. */
982
1053
  planChain(ctx) {
983
- const data = this.plan(ctx);
984
- if (data === null)
1054
+ if (ctx.docKey !== "plan")
985
1055
  return [];
986
1056
  const slug = ctx.head.slug;
987
1057
  // A placeholder or missing slug is presence's surface, never this arm's.
@@ -998,7 +1068,7 @@ export class CrossDocChainInvariant extends Invariant {
998
1068
  * naming an on-disk overall) is the `slug-ref` strategy's judgment; this arm
999
1069
  * only judges the version facts once the target is resolved. */
1000
1070
  specChain(ctx) {
1001
- const data = this.phaseSpec(ctx);
1071
+ const data = this.record(ctx, "phase-spec");
1002
1072
  if (data === null)
1003
1073
  return [];
1004
1074
  const findings = [];
@@ -1039,8 +1109,7 @@ export class CrossDocChainInvariant extends Invariant {
1039
1109
  const content = ctx.fs.read(entry.path);
1040
1110
  if (content === null)
1041
1111
  return null;
1042
- const { head, body } = FrontMatterExtractor.split(content);
1043
- const lines = body.split("\n").map((line) => ctx.translator.canonicalize(line));
1112
+ const { head, lines } = new RowSource(ctx.translator).read(content);
1044
1113
  const parsed = docTypeParsers.overall.parse(lines, head);
1045
1114
  const lineage = new Set();
1046
1115
  if (head.version !== null)
@@ -1066,14 +1135,15 @@ export class SectionScopedDomainInvariant extends Invariant {
1066
1135
  /** Issue-ref forms are judged only within `## Issue inventory` (a content-wide rule
1067
1136
  * would misfire on legacy `## Requirement inventory` tables whose ref cells are prose). */
1068
1137
  issueScopedRefs(ctx) {
1069
- const data = this.overall(ctx);
1070
- if (data === null)
1138
+ if (ctx.docKey !== "overall")
1071
1139
  return [];
1072
1140
  const slice = this.sliceOf(ctx, "Issue ref cell");
1073
1141
  if (slice?.valuePattern === undefined)
1074
1142
  return [];
1075
1143
  const findings = [];
1076
- for (const row of data.tables["Issue inventory"].rows) {
1144
+ const issueHead = this.occurrenceNodes(ctx, "## Issue inventory")[0];
1145
+ const table = issueHead === undefined ? null : ctx.tree.tableUnder(issueHead.text);
1146
+ for (const row of table?.body ?? []) {
1077
1147
  const ref = row[1]?.trim() ?? "";
1078
1148
  if (ref === "" || ref.toLowerCase() === "none")
1079
1149
  continue;
@@ -1085,21 +1155,55 @@ export class SectionScopedDomainInvariant extends Invariant {
1085
1155
  }
1086
1156
  /** `### N.` design-group headings may appear only inside `## Design`. */
1087
1157
  designScoping(ctx) {
1088
- const data = this.phaseSpec(ctx);
1089
- if (data === null)
1158
+ if (ctx.docKey !== "phase-spec")
1090
1159
  return [];
1091
- const slice = this.sliceOf(ctx, "### N. group heading");
1092
- if (slice?.valuePattern === undefined)
1160
+ const element = this.elementOf(ctx, "### N. group heading");
1161
+ if (element === undefined || element.valuePattern === undefined)
1093
1162
  return [];
1163
+ const design = this.occurrenceNodes(ctx, "## Design")[0];
1164
+ const section = ctx.tree.sections().find((entry) => entry.line === design?.line);
1094
1165
  const findings = [];
1095
- for (const section of data.sections) {
1096
- if (this.sliceOf(ctx, "## Design")?.valuePattern?.test(section.heading) === true)
1166
+ for (const heading of ctx.tree.headings()) {
1167
+ if (!ctx.tree.matches(element.selector, heading.text))
1097
1168
  continue;
1098
- for (const line of section.lines) {
1099
- if (slice.valuePattern.test(line.trim())) {
1100
- findings.push(this.finding(ctx, "### N. group heading", `a design-group heading appears outside ## Design: ${line.trim()}`, "move the group heading under ## Design (design-body surface only)"));
1101
- }
1169
+ // A group heading inside the Design section is the surface's own content; the
1170
+ // finding is the heading that sits OUTSIDE it.
1171
+ if (section !== undefined && heading.line >= section.line) {
1172
+ if (heading.line <= section.line + section.lines.length)
1173
+ continue;
1102
1174
  }
1175
+ findings.push(this.finding(ctx, "### N. group heading", `a design-group heading appears outside ## Design: ${heading.text.trim()}`, "move the group heading under ## Design (design-body surface only)"));
1176
+ }
1177
+ return findings;
1178
+ }
1179
+ }
1180
+ // ---------------------------------------------------------------------------
1181
+ // the wave-width rule (P22 §6)
1182
+ // ---------------------------------------------------------------------------
1183
+ /**
1184
+ * wave-width-at-most-three — the plan-scope preventive rule: no DependsOn layer of the
1185
+ * plan may carry more than `MAX_TASKS_PER_WAVE` tasks (design spec §6, judgment face
1186
+ * one). The layers arrive READY-MADE through `ctx.taskLayers` — the caller injects
1187
+ * `TaskGraph#batches()`, the single derivation authority. This rule therefore never
1188
+ * re-derives batches from `parsed.taskBlocks` and never imports the session plane.
1189
+ *
1190
+ * A missing layer fact (a call site with no plan graph) yields ZERO findings: the
1191
+ * degradation is visible on the caller's checked row, never turned into a refusal (the
1192
+ * same present-facts-only stance as a skipped ledger row). The dispatch path always
1193
+ * runs the graph gate first, so the degraded reading only occurs off the dispatch face.
1194
+ */
1195
+ export class WaveWidthInvariant extends Invariant {
1196
+ name = "wave-width-at-most-three";
1197
+ evaluate(ctx) {
1198
+ const layers = ctx.taskLayers;
1199
+ if (layers === undefined)
1200
+ return [];
1201
+ const findings = [];
1202
+ for (const layer of layers) {
1203
+ if (layer.length <= MAX_TASKS_PER_WAVE)
1204
+ continue;
1205
+ const ids = [...layer].sort((left, right) => left - right);
1206
+ findings.push(this.finding(ctx, "DependsOn", `the DependsOn layer {${ids.join(",")}} carries ${ids.length} tasks, above the ${MAX_TASKS_PER_WAVE}-task limit`, `chain the extra tasks through the plan's **DependsOn** edges so no layer carries more than ${MAX_TASKS_PER_WAVE} tasks`));
1103
1207
  }
1104
1208
  return findings;
1105
1209
  }