@oscaner-skills/cdd-engine 2.0.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/{src-next/bin.ts → dist/bin.js} +18 -21
  4. package/dist/contract/declare.js +998 -0
  5. package/dist/contract/doc.js +565 -0
  6. package/dist/contract/frontmatter.js +209 -0
  7. package/dist/contract/home-extractors.js +379 -0
  8. package/dist/contract/invariants.js +1030 -0
  9. package/dist/contract/judge.js +109 -0
  10. package/dist/contract/lint.js +206 -0
  11. package/dist/contract/project.js +371 -0
  12. package/dist/contract/skill-anatomy.js +156 -0
  13. package/dist/contract/translate.js +85 -0
  14. package/dist/face/artifacts.js +189 -0
  15. package/dist/face/board-view.js +522 -0
  16. package/dist/face/capsule.js +141 -0
  17. package/dist/face/cli.js +891 -0
  18. package/dist/face/declare.js +241 -0
  19. package/dist/face/gate.js +158 -0
  20. package/dist/face/graph-view.js +66 -0
  21. package/dist/face/host.js +211 -0
  22. package/dist/face/lifecycle.js +603 -0
  23. package/dist/face/preview.js +136 -0
  24. package/dist/face/projection.js +259 -0
  25. package/dist/face/route-render.js +162 -0
  26. package/dist/face/termination.js +482 -0
  27. package/dist/face/words.js +220 -0
  28. package/{src-next/infra/config.ts → dist/infra/config.js} +19 -24
  29. package/dist/infra/doc-roots.js +19 -0
  30. package/dist/infra/git.js +37 -0
  31. package/dist/infra/process.js +22 -0
  32. package/dist/infra/root.js +62 -0
  33. package/dist/infra/runtime.js +85 -0
  34. package/dist/infra/workspace.js +276 -0
  35. package/dist/render/brief.js +82 -0
  36. package/dist/render/issue-body.js +129 -0
  37. package/dist/render/skeleton.js +434 -0
  38. package/dist/render/templates.js +520 -0
  39. package/dist/session/faces.js +38 -0
  40. package/dist/session/graph.js +309 -0
  41. package/dist/session/handoff-schema.js +295 -0
  42. package/dist/session/ledger.js +762 -0
  43. package/dist/session/next.js +211 -0
  44. package/dist/session/preflight.js +194 -0
  45. package/dist/session/round-naming.js +73 -0
  46. package/dist/session/run.js +441 -0
  47. package/dist/session/state.js +8 -0
  48. package/dist/session/wave.js +92 -0
  49. package/package.json +8 -7
  50. package/templates/report/issue-body.json +0 -46
  51. package/src-next/__tests__/bin.test.ts +0 -128
  52. package/src-next/__tests__/smoke.integration.test.ts +0 -202
  53. package/src-next/__tests__/zero-dep.test.ts +0 -134
  54. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +0 -238
  55. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +0 -153
  56. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +0 -173
  57. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +0 -89
  58. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +0 -225
  59. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +0 -155
  60. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +0 -175
  61. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +0 -85
  62. package/src-next/contract/__tests__/declare.test.ts +0 -242
  63. package/src-next/contract/__tests__/doc.test.ts +0 -358
  64. package/src-next/contract/__tests__/judge.test.ts +0 -873
  65. package/src-next/contract/__tests__/lint.test.ts +0 -314
  66. package/src-next/contract/__tests__/project.test.ts +0 -419
  67. package/src-next/contract/__tests__/translate.test.ts +0 -96
  68. package/src-next/contract/declare.ts +0 -983
  69. package/src-next/contract/doc.ts +0 -753
  70. package/src-next/contract/invariants.ts +0 -1268
  71. package/src-next/contract/judge.ts +0 -142
  72. package/src-next/contract/lint.ts +0 -275
  73. package/src-next/contract/project.ts +0 -596
  74. package/src-next/contract/skill-anatomy.ts +0 -273
  75. package/src-next/contract/translate.ts +0 -113
  76. package/src-next/face/__tests__/board-view.test.ts +0 -948
  77. package/src-next/face/__tests__/capsule.test.ts +0 -276
  78. package/src-next/face/__tests__/channel-closure.guard.test.ts +0 -102
  79. package/src-next/face/__tests__/cli.test.ts +0 -4643
  80. package/src-next/face/__tests__/face.test.ts +0 -289
  81. package/src-next/face/__tests__/graph-view.test.ts +0 -61
  82. package/src-next/face/__tests__/host.test.ts +0 -24
  83. package/src-next/face/__tests__/negation.ts +0 -6
  84. package/src-next/face/__tests__/projection.test.ts +0 -301
  85. package/src-next/face/__tests__/sync-runner.test.ts +0 -70
  86. package/src-next/face/__tests__/words.guard.test.ts +0 -93
  87. package/src-next/face/artifacts.ts +0 -195
  88. package/src-next/face/board-view.ts +0 -662
  89. package/src-next/face/capsule.ts +0 -149
  90. package/src-next/face/cli.ts +0 -819
  91. package/src-next/face/declare.ts +0 -326
  92. package/src-next/face/gate.ts +0 -170
  93. package/src-next/face/graph-view.ts +0 -74
  94. package/src-next/face/host.ts +0 -326
  95. package/src-next/face/lifecycle.ts +0 -700
  96. package/src-next/face/projection.ts +0 -282
  97. package/src-next/face/route-render.ts +0 -160
  98. package/src-next/face/words.ts +0 -296
  99. package/src-next/infra/__tests__/infra.test.ts +0 -287
  100. package/src-next/infra/git.ts +0 -39
  101. package/src-next/infra/process.ts +0 -34
  102. package/src-next/infra/runtime.ts +0 -185
  103. package/src-next/infra/workspace.ts +0 -232
  104. package/src-next/render/__tests__/render.test.ts +0 -499
  105. package/src-next/render/__tests__/skeleton.test.ts +0 -466
  106. package/src-next/render/brief.ts +0 -121
  107. package/src-next/render/issue-body.ts +0 -159
  108. package/src-next/render/skeleton.ts +0 -437
  109. package/src-next/render/templates.ts +0 -650
  110. package/src-next/session/__tests__/graph.test.ts +0 -270
  111. package/src-next/session/__tests__/handoff-plane.guard.test.ts +0 -48
  112. package/src-next/session/__tests__/handoff-schema.test.ts +0 -310
  113. package/src-next/session/__tests__/ledger.test.ts +0 -744
  114. package/src-next/session/__tests__/next.test.ts +0 -368
  115. package/src-next/session/__tests__/preflight.test.ts +0 -491
  116. package/src-next/session/__tests__/run.test.ts +0 -1014
  117. package/src-next/session/__tests__/wave-line-phase.guard.test.ts +0 -49
  118. package/src-next/session/__tests__/wave.test.ts +0 -469
  119. package/src-next/session/faces.ts +0 -110
  120. package/src-next/session/graph.ts +0 -411
  121. package/src-next/session/handoff-schema.ts +0 -373
  122. package/src-next/session/ledger.ts +0 -1004
  123. package/src-next/session/next.ts +0 -192
  124. package/src-next/session/preflight.ts +0 -240
  125. package/src-next/session/run.ts +0 -606
  126. package/src-next/session/state.ts +0 -30
  127. package/src-next/session/wave.ts +0 -139
@@ -0,0 +1,1030 @@
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 / cross-doc-chain /
7
+ // section-scoped-domain (the four seam strategies that absorb the
8
+ // old doctype classes' contextual judgment — fourTableAudit,
9
+ // deviations, Class-A/B, 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.
15
+ var _a;
16
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
17
+ import path from "node:path";
18
+ import { ENGINE_DOC_ROOTS } from "../infra/doc-roots.js";
19
+ import { MarkdownPrimitives } from "./doc.js";
20
+ // ---------------------------------------------------------------------------
21
+ // judgment records + the context
22
+ // ---------------------------------------------------------------------------
23
+ /** The doc-tree root namespace derived from the ONE doc-root declaration (the
24
+ * common parent of the spec/plan roots) — the finding messages name the
25
+ * repo-root form `<namespace>/…` from THIS, never a hard-coded copy (P9 T5 §2.8). */
26
+ const DOC_ROOT_NAMESPACE = path.dirname(ENGINE_DOC_ROOTS.specs);
27
+ /** The two doc-root segment names derived from the same ONE declaration — the
28
+ * sibling-scan finding message's `<segments>` form names THIS, never a hard-coded
29
+ * copy (P9 T5 §2.8). */
30
+ const DOC_ROOT_SEGMENTS = Object.values(ENGINE_DOC_ROOTS)
31
+ .map((dir) => path.basename(dir))
32
+ .join("/");
33
+ /** The node:fs default — the production seam for file-existence / sibling scans. */
34
+ export class NodeFs {
35
+ exists(p) {
36
+ return existsSync(p);
37
+ }
38
+ read(p) {
39
+ try {
40
+ return readFileSync(p, "utf8");
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ list(p) {
47
+ try {
48
+ return readdirSync(p);
49
+ }
50
+ catch {
51
+ return [];
52
+ }
53
+ }
54
+ }
55
+ // ---------------------------------------------------------------------------
56
+ // the abstract strategy base
57
+ // ---------------------------------------------------------------------------
58
+ /**
59
+ * The abstract invariant — one strategy = one structural judgment. Subclasses
60
+ * implement evaluate(ctx) and read all judgment data from the declared registries
61
+ * + the parse face carried by the context. The base extends MarkdownPrimitives:
62
+ * the link/token/table-row parsers shared with the parse face live in one home
63
+ * (doc.ts), never re-declared here.
64
+ */
65
+ export class Invariant extends MarkdownPrimitives {
66
+ /** The single finding-construction point. */
67
+ finding(ctx, field, message, fix) {
68
+ return { path: ctx.path, field, message, fix, kind: this.name };
69
+ }
70
+ /** The judged doc type's declared registry. */
71
+ registry(ctx) {
72
+ return ctx.registries[ctx.docKey];
73
+ }
74
+ /** The judged doc type's registered elements in registry order. */
75
+ elementsOf(ctx) {
76
+ return this.registry(ctx).elements;
77
+ }
78
+ /** The slice of one registered anchor (undefined when the anchor is not registered here). */
79
+ sliceOf(ctx, anchor) {
80
+ return ctx.slices.slices.find((slice) => slice.anchor === anchor);
81
+ }
82
+ /** Whether a line carries the element — the literal anchor or the declared value shape. */
83
+ lineCarries(slice, line) {
84
+ return line.includes(slice.anchor) || (slice.valuePattern?.test(line) ?? false);
85
+ }
86
+ /** The lines carrying the element's anchor token literal. */
87
+ anchorLines(ctx, anchor) {
88
+ return ctx.lines.filter((line) => line.includes(anchor));
89
+ }
90
+ /** The lines carrying the element (literal anchor or declared value shape). */
91
+ occurrenceLines(ctx, slice) {
92
+ return ctx.lines.filter((line) => this.lineCarries(slice, line));
93
+ }
94
+ /** The lines that carry the element as a real structural occurrence — a line whose
95
+ * anchor only appears as a citation (a backticked code span, or a table cell of a
96
+ * non-table element) is not a carrier and is never judged as a value. */
97
+ carrierLines(ctx, slice) {
98
+ return ctx.lines.filter((line) => this.lineCarries(slice, line) && this.#isStructuralCarrier(line, slice));
99
+ }
100
+ #isStructuralCarrier(line, slice) {
101
+ if (this.#isTableRow(line) && slice.home !== "table")
102
+ return false;
103
+ if (!line.includes(slice.anchor))
104
+ return true;
105
+ return !this.#everyAnchorMentionIsCodeSpan(line, slice.anchor);
106
+ }
107
+ #isTableRow(line) {
108
+ const trimmed = line.trim();
109
+ return trimmed.startsWith("|") && trimmed.endsWith("|");
110
+ }
111
+ /** Whether every literal anchor mention on the line stays inside a backtick code span. */
112
+ #everyAnchorMentionIsCodeSpan(line, anchor) {
113
+ return !this.#withoutCodeSpans(line).includes(anchor);
114
+ }
115
+ /** The line with its backtick-quoted region removed. A line's quoted content is
116
+ * the region between its FIRST and LAST backtick (inclusive) — ONE contiguous
117
+ * quoted fragment, the shape the doc prose actually uses: a simple `` `span` ``
118
+ * and a quoted command fragment with a NESTED citation (`` `read X + the plan's
119
+ * \`## Constraints\` (by the wave brief mirror)` ``) both read as one quoted region (the
120
+ * find-#8 gap: the old span-by-span strip left a nested citation naked after its
121
+ * opener got consumed by the outer span, judging quoted prose as a value). The
122
+ * tradeoff is pinned: a line carrying TWO separate backtick spans (`` `x` … `y` ``)
123
+ * also reads as ONE quoted region, so the mid-span prose between the spans is not
124
+ * judged (judge.test.ts pins this — an anchor quoted only between two adjacent
125
+ * spans stays invisible to the presence/domain rules; no enforced doc carries that
126
+ * shape). A zero- or one-tick line carries no quoted region (unbalanced — nothing
127
+ * to strip). */
128
+ #withoutCodeSpans(line) {
129
+ const first = line.indexOf("`");
130
+ if (first === -1)
131
+ return line;
132
+ const last = line.lastIndexOf("`");
133
+ if (first === last)
134
+ return line;
135
+ return line.slice(0, first) + line.slice(last + 1);
136
+ }
137
+ /** The parsed overall record — when the judged doc is an overall. */
138
+ overall(ctx) {
139
+ return ctx.docKey === "overall-spec" ? ctx.parsed : null;
140
+ }
141
+ /** The parsed plan record — when the judged doc is a plan. */
142
+ plan(ctx) {
143
+ return ctx.docKey === "plan" ? ctx.parsed : null;
144
+ }
145
+ /** The parsed phase-spec record — when the judged doc is a phase-spec. */
146
+ phaseSpec(ctx) {
147
+ return ctx.docKey === "phase-spec" ? ctx.parsed : null;
148
+ }
149
+ /** The four-table section heading anchors of the overall (registry-declared). */
150
+ overallTableHeadings(ctx) {
151
+ const headings = this.overall(ctx);
152
+ if (headings === null)
153
+ return [];
154
+ const declared = ctx.registries["overall-spec"].elements
155
+ .filter((element) => element.home === "section" && element.anchor.startsWith("## "))
156
+ .map((element) => element.anchor);
157
+ return declared.filter((anchor) => ["File paths", "Issue inventory", "Phase inventory", "Change history"].some((name) => anchor.includes(name)));
158
+ }
159
+ }
160
+ // ---------------------------------------------------------------------------
161
+ // base nine
162
+ // ---------------------------------------------------------------------------
163
+ /** Home surfaces the presence invariant judges — the structural doc surface
164
+ * (table rows/columns/tokens are judged by hollow/section-scoped strategies). */
165
+ const PRESENCE_HOMES = new Set([
166
+ "frontmatter",
167
+ "section",
168
+ "facet",
169
+ "graph",
170
+ "task-block",
171
+ "task-field",
172
+ "task-step",
173
+ "design-body",
174
+ "conditional",
175
+ ]);
176
+ /** presence — every required structural element of the declared registry must occur. */
177
+ export class PresenceInvariant extends Invariant {
178
+ name = "presence";
179
+ evaluate(ctx) {
180
+ const findings = [];
181
+ for (const element of this.elementsOf(ctx)) {
182
+ if (element.presence !== "required")
183
+ continue;
184
+ if (PRESENCE_HOMES.has(element.home) === false)
185
+ continue;
186
+ const slice = this.sliceOf(ctx, element.anchor);
187
+ if (slice === undefined)
188
+ continue;
189
+ if (this.#derivedPresenceHolds(ctx, slice))
190
+ continue;
191
+ // The front-matter-home elements judge the typed head record (the §2.2
192
+ // delivery seam — NEVER the body line scan: front matter is data, and a
193
+ // whitespace line or a body-line mention of a key is not an occurrence).
194
+ if (slice.home === "frontmatter") {
195
+ if (ctx.head.value(element.anchor) !== null)
196
+ continue;
197
+ findings.push(this.finding(ctx, element.anchor, `missing required element: ${element.anchor}`, `add the "${element.anchor}" key to the document's front matter`));
198
+ continue;
199
+ }
200
+ if (this.occurrenceLines(ctx, slice).length === 0) {
201
+ findings.push(this.finding(ctx, element.anchor, `missing required element: ${element.anchor}`, `add the "${element.anchor}" ${element.home} element to the document`));
202
+ }
203
+ }
204
+ findings.push(...this.taskFieldPresence(ctx));
205
+ return findings;
206
+ }
207
+ /** A required surface whose occurrence is established by the parsed structure rather
208
+ * than a line scan — the plan's `Task id token` only ever appears inside the
209
+ * `### Task N:` headings, so it is present iff a task block exists. */
210
+ #derivedPresenceHolds(ctx, slice) {
211
+ if (slice.home !== "task-block" || slice.anchor.startsWith("#"))
212
+ return false;
213
+ return (this.plan(ctx)?.taskBlocks.length ?? 0) > 0;
214
+ }
215
+ /** The per-task-block required field keys — derived from the plan registry's
216
+ * task-field elements (the bold `**Key**` markers; the `File path token` and
217
+ * DependsOn-value leaves carry non-key anchors, and `Step action` lives on the
218
+ * task-step home). Single-source: a field key added to the registry is enforced
219
+ * per task block automatically. */
220
+ #requiredFieldKeys(ctx) {
221
+ return this.elementsOf(ctx)
222
+ .filter((element) => element.home === "task-field" &&
223
+ element.anchor.startsWith("**") &&
224
+ element.anchor.endsWith("**"))
225
+ .map((element) => element.anchor.slice(2, -2));
226
+ }
227
+ /** The per-task-block field surface — every required task-field key of a plan. */
228
+ taskFieldPresence(ctx) {
229
+ const data = this.plan(ctx);
230
+ if (data === null)
231
+ return [];
232
+ const findings = [];
233
+ for (const block of data.taskBlocks) {
234
+ const keys = new Set(block.fields.map((field) => field.key));
235
+ for (const key of this.#requiredFieldKeys(ctx)) {
236
+ if (!keys.has(key)) {
237
+ findings.push(this.finding(ctx, `**${key}**`, `task ${block.id} carries no **${key}** field`, `add the - **${key}**: line to ### Task ${block.id}:`));
238
+ }
239
+ }
240
+ }
241
+ return findings;
242
+ }
243
+ }
244
+ /** uniqueness — every identity-carrying surface registers exactly once. */
245
+ export class UniquenessInvariant extends Invariant {
246
+ name = "uniqueness";
247
+ evaluate(ctx) {
248
+ const findings = [...this.headingUniqueness(ctx), ...this.derivedUniqueness(ctx)];
249
+ return findings;
250
+ }
251
+ /** Heading-style anchors: a duplicated heading line text is a duplicate registration. */
252
+ headingUniqueness(ctx) {
253
+ const findings = [];
254
+ const seenLine = new Set();
255
+ for (const element of this.elementsOf(ctx)) {
256
+ if (!element.anchor.startsWith("#"))
257
+ continue;
258
+ const slice = this.sliceOf(ctx, element.anchor);
259
+ if (slice === undefined)
260
+ continue;
261
+ for (const line of this.occurrenceLines(ctx, slice)) {
262
+ const trimmed = line.trim();
263
+ const key = `${element.anchor}::${trimmed}`;
264
+ if (seenLine.has(key)) {
265
+ findings.push(this.finding(ctx, element.anchor, `duplicate heading registration: ${trimmed}`, `keep "${trimmed}" in exactly one place`));
266
+ }
267
+ seenLine.add(key);
268
+ }
269
+ }
270
+ return findings;
271
+ }
272
+ /** The derived identity rows: task ids, phase ids, change-history versions. */
273
+ derivedUniqueness(ctx) {
274
+ const findings = [];
275
+ if (ctx.docKey === "plan") {
276
+ const seenIds = new Set();
277
+ for (const block of this.plan(ctx)?.taskBlocks ?? []) {
278
+ if (seenIds.has(block.id)) {
279
+ 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"));
280
+ }
281
+ seenIds.add(block.id);
282
+ }
283
+ }
284
+ if (ctx.docKey === "overall-spec") {
285
+ const data = this.overall(ctx);
286
+ if (data !== null) {
287
+ const seenPhases = new Set();
288
+ for (const phase of data.chain.phases) {
289
+ const lower = phase.id.toLowerCase();
290
+ if (seenPhases.has(lower)) {
291
+ 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"));
292
+ }
293
+ seenPhases.add(lower);
294
+ }
295
+ const seenVersions = new Set();
296
+ for (const row of data.tables["Change history"].rows) {
297
+ const version = this.#firstVersion(row[0] ?? "");
298
+ if (version !== null && seenVersions.has(version)) {
299
+ 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"));
300
+ }
301
+ if (version !== null)
302
+ seenVersions.add(version);
303
+ }
304
+ }
305
+ }
306
+ return findings;
307
+ }
308
+ #firstVersion(text) {
309
+ const match = text.match(/v\d+\.\d+/);
310
+ return match === null ? null : match[0];
311
+ }
312
+ }
313
+ /** domain — every value an anchor literal carries must conform to its declared shape. */
314
+ export class DomainInvariant extends Invariant {
315
+ name = "domain";
316
+ evaluate(ctx) {
317
+ const findings = [];
318
+ for (const element of this.elementsOf(ctx)) {
319
+ const slice = this.sliceOf(ctx, element.anchor);
320
+ if (slice === undefined)
321
+ continue;
322
+ // The front-matter-home elements judge the typed head SCALAR (the §2.2
323
+ // delivery seam — the registered value patterns are scalar shapes, §2.3).
324
+ // Absence is presence's surface; a present scalar outside the declared
325
+ // shape is the finding. The pattern is read from the REGISTRY ELEMENT
326
+ // (project.ts's header leg deliberately stops both slice RegExp
327
+ // compilations — the front-matter key is looked up against the head).
328
+ if (slice.home === "frontmatter") {
329
+ const value = ctx.head.value(element.anchor);
330
+ if (value === null)
331
+ continue;
332
+ const rawPattern = element.valuePattern;
333
+ if (rawPattern === undefined)
334
+ continue;
335
+ if (!new RegExp(rawPattern).test(value)) {
336
+ findings.push(this.finding(ctx, element.anchor, `value outside the declared domain: ${value}`, `make the front-matter ${element.anchor} value match ${rawPattern}`));
337
+ }
338
+ continue;
339
+ }
340
+ if (slice.valuePattern === undefined)
341
+ continue;
342
+ // The element is judged by the SHAPE of the lines that carry it structurally —
343
+ // a table row or a heading must match its declared pattern. A prose citation
344
+ // (a backticked code-span mention, or a table cell of a non-table element) is
345
+ // not a carrier and is never judged as a value.
346
+ for (const line of this.carrierLines(ctx, slice)) {
347
+ if (!slice.valuePattern.test(line)) {
348
+ findings.push(this.finding(ctx, element.anchor, `value outside the declared domain: ${line.trim()}`, `make the line match ${slice.valuePattern.source}`));
349
+ }
350
+ }
351
+ }
352
+ return findings;
353
+ }
354
+ }
355
+ /** crosslink — in-document reference resolution against the doc's own identity sets. */
356
+ export class CrosslinkInvariant extends Invariant {
357
+ name = "crosslink";
358
+ evaluate(ctx) {
359
+ if (ctx.docKey === "overall-spec")
360
+ return this.overallCrosslinks(ctx);
361
+ if (ctx.docKey === "plan")
362
+ return this.planCrosslinks(ctx);
363
+ return [];
364
+ }
365
+ /** The overall's in-doc reference surfaces: issue rows + graph edges + dependency cells. */
366
+ overallCrosslinks(ctx) {
367
+ const data = this.overall(ctx);
368
+ if (data === null)
369
+ return [];
370
+ const findings = [];
371
+ const ids = new Set(data.chain.phases.map((phase) => phase.id.toLowerCase()));
372
+ // Issue-inventory rows: the Phase column must be a registered inventory id.
373
+ for (const row of data.tables["Issue inventory"].rows) {
374
+ const phaseCell = row[0]?.trim() ?? "";
375
+ if (phaseCell !== "" && !ids.has(phaseCell.toLowerCase())) {
376
+ 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"));
377
+ }
378
+ }
379
+ // Graph edges: every from/to token must be a registered phase id.
380
+ for (const edge of data.graphEdges) {
381
+ if (!ids.has(edge.from.toLowerCase())) {
382
+ 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`));
383
+ }
384
+ if (!ids.has(edge.to.toLowerCase())) {
385
+ findings.push(this.finding(ctx, "Dependency graph", `graph edge to ${edge.to} is not a Phase-inventory id`, `register ${edge.to} in the Phase inventory or fix the edge`));
386
+ }
387
+ }
388
+ // Phase-row dependency cells: every P-token must be a registered phase id.
389
+ for (const phase of data.chain.phases) {
390
+ for (const token of this.#phaseTokens(phase.dependencyCell)) {
391
+ if (!ids.has(token.toLowerCase())) {
392
+ findings.push(this.finding(ctx, "Phase inventory", `dependency of ${phase.id} references unregistered phase ${token}`, `register ${token} in the Phase inventory or fix the dependency cell`));
393
+ }
394
+ }
395
+ }
396
+ return findings;
397
+ }
398
+ /** The plan's in-doc reference surfaces: the DependsOn ids — the single structural
399
+ * reference gate. Prose task mentions are NOT consumed here (T6): the WARN-only
400
+ * observation belongs to the reference-lint pass, never a hard finding. */
401
+ planCrosslinks(ctx) {
402
+ const data = this.plan(ctx);
403
+ if (data === null)
404
+ return [];
405
+ const findings = [];
406
+ const ids = new Set(data.taskBlocks.map((block) => block.id));
407
+ for (const block of data.taskBlocks) {
408
+ const dependsOn = this.#dependsOnOf(block);
409
+ for (const id of dependsOn) {
410
+ if (!ids.has(id)) {
411
+ findings.push(this.finding(ctx, `Task ${block.id}`, `task ${block.id} depends on unregistered task ${id}`, "set DependsOn to a task id present in the plan (or `none`)"));
412
+ }
413
+ }
414
+ }
415
+ return findings;
416
+ }
417
+ /** The numeric DependsOn values of a task block. */
418
+ #dependsOnOf(block) {
419
+ const ids = [];
420
+ const field = block.fields.find((field) => field.key === "DependsOn");
421
+ if (field === undefined)
422
+ return ids;
423
+ for (const value of field.lines) {
424
+ for (const match of value.matchAll(/\b([1-9]\d*)\b/g))
425
+ ids.push(Number(match[1]));
426
+ }
427
+ return ids;
428
+ }
429
+ /** The `P<n>` tokens of a comment struct (dependency cells / depends-on values). */
430
+ #phaseTokens(text) {
431
+ const tokens = [];
432
+ for (const match of text.matchAll(/P(\d+(?:\.\d+)*)/g))
433
+ tokens.push(`P${match[1]}`);
434
+ return tokens;
435
+ }
436
+ }
437
+ /** order — structural surfaces appear in their declared sequence. */
438
+ export class OrderInvariant extends Invariant {
439
+ name = "order";
440
+ evaluate(ctx) {
441
+ return [...this.sectionOrder(ctx), ...this.historyOrder(ctx)];
442
+ }
443
+ /** Rank-2 headings must follow the declared registry order (design before constraints…). */
444
+ sectionOrder(ctx) {
445
+ const findings = [];
446
+ const anchors = this.elementsOf(ctx)
447
+ .filter((element) => element.anchor.startsWith("## "))
448
+ .map((element) => element.anchor);
449
+ const docSections = this.#docSections(ctx);
450
+ let previous = -1;
451
+ for (const section of docSections) {
452
+ const match = this.#registryAnchorFor(section, anchors, ctx);
453
+ if (match === null)
454
+ continue;
455
+ if (match.index < previous) {
456
+ findings.push(this.finding(ctx, section.heading, `${section.heading} appears out of the declared section order`, `move the section to its registry position (${match.index + 1} of the declared sequence)`));
457
+ }
458
+ previous = Math.max(previous, match.index);
459
+ }
460
+ return findings;
461
+ }
462
+ /** The overall's change-history rows must be version-ascending — oldest first, the
463
+ * latest revision last (the canonical repo format). */
464
+ historyOrder(ctx) {
465
+ const data = this.overall(ctx);
466
+ if (data === null)
467
+ return [];
468
+ const findings = [];
469
+ const versions = data.tables["Change history"].rows
470
+ .map((row) => this.#versionPair(row[0] ?? ""))
471
+ .filter((pair) => pair !== null);
472
+ for (let i = 1; i < versions.length; i++) {
473
+ const earlier = versions[i - 1];
474
+ const later = versions[i];
475
+ if (earlier.major > later.major ||
476
+ (earlier.major === later.major && earlier.minor > later.minor)) {
477
+ 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"));
478
+ break;
479
+ }
480
+ }
481
+ return findings;
482
+ }
483
+ /** The document's rank-2 section blocks in document order. */
484
+ #docSections(ctx) {
485
+ if (ctx.docKey === "overall-spec")
486
+ return ctx.parsed.sections;
487
+ if (ctx.docKey === "plan")
488
+ return ctx.parsed.sections;
489
+ return ctx.parsed.sections;
490
+ }
491
+ /** The registry anchor a doc section heading conforms to (null when unregistered). */
492
+ #registryAnchorFor(section, anchors, ctx) {
493
+ for (let index = 0; index < anchors.length; index++) {
494
+ const slice = this.sliceOf(ctx, anchors[index]);
495
+ if (slice?.valuePattern?.test(section.heading) === true) {
496
+ return { anchor: anchors[index], index };
497
+ }
498
+ if (slice === undefined && section.heading.startsWith(anchors[index])) {
499
+ return { anchor: anchors[index], index };
500
+ }
501
+ }
502
+ return null;
503
+ }
504
+ #versionPair(text) {
505
+ const match = text.match(/v(\d+)\.(\d+)/);
506
+ return match === null ? null : { major: Number(match[1]), minor: Number(match[2]) };
507
+ }
508
+ }
509
+ /** continuity — numbered surfaces are 1-indexed and contiguous. */
510
+ export class ContinuityInvariant extends Invariant {
511
+ name = "continuity";
512
+ evaluate(ctx) {
513
+ if (ctx.docKey === "plan")
514
+ return this.taskContinuity(ctx);
515
+ if (ctx.docKey === "phase-spec")
516
+ return this.groupContinuity(ctx);
517
+ return [];
518
+ }
519
+ /** Plan task ids must be exactly 1..N. */
520
+ taskContinuity(ctx) {
521
+ const data = this.plan(ctx);
522
+ if (data === null || data.taskBlocks.length === 0)
523
+ return [];
524
+ const findings = [];
525
+ data.taskBlocks.forEach((block, index) => {
526
+ const expected = index + 1;
527
+ if (block.id !== expected) {
528
+ 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"));
529
+ }
530
+ });
531
+ return findings;
532
+ }
533
+ /** Phase-spec design groups (and their items) must be 1-indexed and contiguous. */
534
+ groupContinuity(ctx) {
535
+ const data = this.phaseSpec(ctx);
536
+ if (data === null || data.design.length === 0)
537
+ return [];
538
+ const findings = [];
539
+ data.design.forEach((group, index) => {
540
+ if (Number(group.number) !== index + 1) {
541
+ findings.push(this.finding(ctx, "### N. group heading", `design group numbering is not contiguous from 1 (group ${group.number} at position ${index + 1})`, "renumber the design groups so they run exactly 1..N"));
542
+ }
543
+ this.#itemContinuity(ctx, group, group.number, findings);
544
+ });
545
+ return findings;
546
+ }
547
+ #itemContinuity(ctx, group, groupNumber, findings) {
548
+ group.items.forEach((item, index) => {
549
+ if (item.number !== `${groupNumber}.${index + 1}`) {
550
+ findings.push(this.finding(ctx, "#### N.M item heading", `design item numbering drifts within group ${groupNumber} (item ${item.number} at position ${index + 1})`, "renumber the items within each group so they run N.1..N.M"));
551
+ }
552
+ });
553
+ }
554
+ }
555
+ /** residue — conditional content leaves zero residue when its condition does not hold. */
556
+ export class ResidueInvariant extends Invariant {
557
+ name = "residue";
558
+ evaluate(ctx) {
559
+ const findings = [];
560
+ const elements = this.elementsOf(ctx);
561
+ let owner = null;
562
+ for (const element of elements) {
563
+ if (element.home === "conditional" && element.anchor.startsWith("## ")) {
564
+ owner = element.anchor;
565
+ continue;
566
+ }
567
+ if (element.home !== "conditional" || owner === null)
568
+ continue;
569
+ const slice = this.sliceOf(ctx, element.anchor);
570
+ if (slice === undefined || slice.valuePattern === undefined)
571
+ continue;
572
+ if (this.anchorLines(ctx, owner).length > 0)
573
+ continue; // the condition holds — the section is present
574
+ const leaked = this.occurrenceLines(ctx, slice).length;
575
+ if (leaked > 0) {
576
+ 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`));
577
+ }
578
+ }
579
+ return findings;
580
+ }
581
+ }
582
+ /** hollow — a structural surface that is present but carries no content. */
583
+ export class HollowInvariant extends Invariant {
584
+ name = "hollow";
585
+ evaluate(ctx) {
586
+ const findings = [...this.tableHollow(ctx), ...this.taskHollow(ctx), ...this.designHollow(ctx)];
587
+ return findings;
588
+ }
589
+ /** The overall's four tables: a present table section with zero data rows is hollow. */
590
+ tableHollow(ctx) {
591
+ const data = this.overall(ctx);
592
+ if (data === null)
593
+ return [];
594
+ const findings = [];
595
+ for (const anchor of this.overallTableHeadings(ctx)) {
596
+ const headingExists = this.anchorLines(ctx, anchor).length > 0;
597
+ if (!headingExists)
598
+ continue;
599
+ const section = data.sections.find((s) => s.heading.includes(anchor.replace(/^## /, "")));
600
+ const tableRows = section === undefined ? [] : this.tableRows(section.lines).slice(1);
601
+ if (tableRows.length === 0) {
602
+ 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"));
603
+ }
604
+ }
605
+ return findings;
606
+ }
607
+ /** A task block that carries no keyed fields is a hollow shell. */
608
+ taskHollow(ctx) {
609
+ const data = this.plan(ctx);
610
+ if (data === null)
611
+ return [];
612
+ const findings = [];
613
+ for (const block of data.taskBlocks) {
614
+ if (block.fields.length === 0) {
615
+ 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"));
616
+ }
617
+ }
618
+ return findings;
619
+ }
620
+ /** The phase-spec skeleton: a present Design with no groups (or an empty conditional section). */
621
+ designHollow(ctx) {
622
+ const data = this.phaseSpec(ctx);
623
+ if (data === null)
624
+ return [];
625
+ const findings = [];
626
+ const designSlice = this.sliceOf(ctx, "## Design");
627
+ if (designSlice !== undefined &&
628
+ this.anchorLines(ctx, "## Design").length > 0 &&
629
+ data.design.length === 0) {
630
+ 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"));
631
+ }
632
+ for (const section of data.sections) {
633
+ if (section.heading.trim().length === 0)
634
+ continue;
635
+ const bodyCount = section.lines.filter((line) => line.trim().length > 0).length;
636
+ if (bodyCount === 0) {
637
+ findings.push(this.finding(ctx, section.heading, `${section.heading} section is hollow — the heading carries no content`, "add the section's content or remove the empty section"));
638
+ }
639
+ }
640
+ return findings;
641
+ }
642
+ }
643
+ /** selfBounded — the doc's own-scope lineage stays consistent with itself. */
644
+ export class SelfBoundedInvariant extends Invariant {
645
+ name = "selfBounded";
646
+ evaluate(ctx) {
647
+ const headerVersion = ctx.head.version;
648
+ const historyVersions = this.#historyVersions(ctx);
649
+ if (headerVersion === null || historyVersions.length === 0)
650
+ return [];
651
+ const findings = [];
652
+ const newest = this.#newestVersion(historyVersions);
653
+ if (headerVersion !== newest) {
654
+ 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"));
655
+ }
656
+ if (!historyVersions.includes(headerVersion)) {
657
+ 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(", ")}`));
658
+ }
659
+ return findings;
660
+ }
661
+ /** The doc's Change-history row versions — the overall reads its parsed table,
662
+ * the plan/spec read the `## Change history` section's table rows (the shared
663
+ * row primitive — the P4.1 T2 isomorphic lineage: the same lineage judgment rides
664
+ * all doc types). */
665
+ #historyVersions(ctx) {
666
+ if (ctx.docKey === "overall-spec") {
667
+ const data = this.overall(ctx);
668
+ if (data === null)
669
+ return [];
670
+ return data.tables["Change history"].rows
671
+ .map((row) => this.#firstVersion(row[0] ?? ""))
672
+ .filter((version) => version !== null);
673
+ }
674
+ const section = ctx.docKey === "plan"
675
+ ? ctx.parsed.sections.find((s) => s.heading.includes("Change history"))
676
+ : ctx.parsed.sections.find((s) => s.heading.includes("Change history"));
677
+ if (section === undefined)
678
+ return [];
679
+ return this.tableRows(section.lines)
680
+ .map((row) => this.#firstVersion(row[0] ?? ""))
681
+ .filter((version) => version !== null);
682
+ }
683
+ #firstVersion(text) {
684
+ const match = text.match(/v\d+\.\d+/);
685
+ return match === null ? null : match[0];
686
+ }
687
+ /** The newest lineage version — the numerically greatest (major, minor) row. */
688
+ #newestVersion(versions) {
689
+ let best = versions[0];
690
+ for (const version of versions) {
691
+ const [bestMajor, bestMinor] = this.#versionNumber(best);
692
+ const [currentMajor, currentMinor] = this.#versionNumber(version);
693
+ if (currentMajor > bestMajor || (currentMajor === bestMajor && currentMinor > bestMinor)) {
694
+ best = version;
695
+ }
696
+ }
697
+ return best;
698
+ }
699
+ #versionNumber(version) {
700
+ const match = version.match(/v(\d+)\.(\d+)/);
701
+ return match === null ? [0, 0] : [Number(match[1]), Number(match[2])];
702
+ }
703
+ }
704
+ // ---------------------------------------------------------------------------
705
+ // the four context-seam strategies
706
+ // ---------------------------------------------------------------------------
707
+ /** The chain-link target shape contract (D2, shape judged at the boundary — the #342
708
+ * fix): a link target must be a BARE relative path (the repo-root form
709
+ * `docs/kairos/specs/…-overall.md` or a doc-relative file name) — never a
710
+ * markdown-link shell (`[label](path)`), a URL or a collation token
711
+ * (whitespace / parens / angle brackets). The ONE expression of the shape rule:
712
+ * `of()` yields either the accepted (trimmed) target or the reason the shape is
713
+ * invalid; the chain strategies judge the shape BEFORE any resolution, so a
714
+ * malformed fill reports the shape rule once — the confusing resolution cascade
715
+ * (#342's dead-tail `basename` + the file-existence double failure) never
716
+ * fires. */
717
+ export class LinkTargetShape {
718
+ /** The accepted, trimmed target — null when the shape is invalid. */
719
+ target;
720
+ /** The shape-rule reason the target is invalid — null when accepted. */
721
+ reason;
722
+ constructor(target, reason) {
723
+ this.target = target;
724
+ this.reason = reason;
725
+ }
726
+ /** Judge one raw target — a bare relative path accepts; any collation token
727
+ * rejects with the shape rule. */
728
+ static of(raw) {
729
+ const trimmed = raw.trim();
730
+ // The rejected collation tokens — whitespace, a markdown-link shell's
731
+ // brackets/parens (`[label](path)`), stray angle brackets and the `://`
732
+ // URL scheme. The path separators `/` and `:` alone stay legal (a bare
733
+ // relative path carries both) — only the URL-scheme pairing rejects.
734
+ if (/[\s()[\]<>]|:\/\//.test(trimmed)) {
735
+ return new LinkTargetShape(null, "the value must be a bare relative path (e.g. `docs/kairos/specs/…-overall.md` or `xxx-overall.md`), not a markdown link or URL");
736
+ }
737
+ return new LinkTargetShape(trimmed, null);
738
+ }
739
+ }
740
+ /** file-existence — every chain link target of the doc resolves to an existing file. */
741
+ export class FileExistenceInvariant extends Invariant {
742
+ name = "file-existence";
743
+ evaluate(ctx) {
744
+ const findings = [];
745
+ for (const { source, link } of this.chainLinks(ctx)) {
746
+ if (this.isPlaceholder(link.target))
747
+ continue;
748
+ const shape = LinkTargetShape.of(link.target);
749
+ // D2: a malformed target is the link-shape face's call — the resolution
750
+ // faces never feed it to the path resolution as a literal.
751
+ if (shape.target === null)
752
+ continue;
753
+ if (!this.#targetExists(ctx, shape.target)) {
754
+ findings.push(this.finding(ctx, source, `the chain link target does not resolve to an existing file: ${shape.target}`, `fix the link target (repo-root form ${DOC_ROOT_NAMESPACE}/... or a file-relative path)`));
755
+ }
756
+ }
757
+ return findings;
758
+ }
759
+ /** The chain links of the judged doc type (overall design/plan cells; plan/spec lineage links). */
760
+ chainLinks(ctx) {
761
+ const links = [];
762
+ if (ctx.docKey === "overall-spec") {
763
+ const data = this.overall(ctx);
764
+ if (data !== null) {
765
+ for (const phase of data.chain.phases) {
766
+ for (const link of this.linksOnLine(phase.designCell)) {
767
+ links.push({ source: `Phase inventory · ${phase.id}`, link });
768
+ }
769
+ for (const link of this.linksOnLine(phase.planCell)) {
770
+ links.push({ source: `Phase inventory · ${phase.id}`, link });
771
+ }
772
+ }
773
+ }
774
+ }
775
+ if (ctx.docKey === "plan") {
776
+ const data = this.plan(ctx);
777
+ if (data !== null) {
778
+ if (data.chain.specLink !== null)
779
+ links.push({ source: "spec", link: data.chain.specLink });
780
+ if (data.chain.parentLink !== null)
781
+ links.push({ source: "parent-program", link: data.chain.parentLink });
782
+ }
783
+ }
784
+ if (ctx.docKey === "phase-spec") {
785
+ const data = this.phaseSpec(ctx);
786
+ if (data !== null && data.chain.parentLink !== null) {
787
+ links.push({ source: "parent-program", link: data.chain.parentLink });
788
+ }
789
+ }
790
+ return links;
791
+ }
792
+ /** Whether a target's raw form marks it as a holder placeholder (no existence judgment). */
793
+ isPlaceholder(target) {
794
+ const trimmed = target.trim();
795
+ if (trimmed === "")
796
+ return true;
797
+ if (trimmed === "Pending" || trimmed === "[Pending]")
798
+ return true;
799
+ return /^<[^>]+>$/.test(trimmed);
800
+ }
801
+ /** Whether the target exists — absolute targets directly; repo-root form first, the
802
+ * doc's own dir as the file-relative fallback. The resolution chain is
803
+ * single-sourced in `targetPath` (the ONE home the CLI's plan `spec:` rebase
804
+ * delegates to as well — P9 branch-review-1 F8: a future contract change
805
+ * cannot silently diverge from the CLI's mirror). */
806
+ #targetExists(ctx, target) {
807
+ return ctx.fs.exists(_a.targetPath(ctx.root, ctx.path, target, (p) => ctx.fs.exists(p)));
808
+ }
809
+ /** The ONE chain-link target-resolution chain (the doc-contract's own judgment,
810
+ * reused by the CLI's plan `spec:` rebase — F8): an absolute target as
811
+ * itself; else the repoRoot-relative reading when it exists; else the doc-dir
812
+ * (file-relative) reading. `exists` is the caller's filesystem seam (the
813
+ * judgment's `ctx.fs`, the CLI's `fs.existsSync`) — the resolution is the shared
814
+ * fact, the read is injected. When neither reading exists the doc-dir path is
815
+ * returned (the link-space semantic — the caller owns the truly-missing case). */
816
+ static targetPath(root, docPath, target, exists) {
817
+ if (path.isAbsolute(target))
818
+ return target;
819
+ const fromRoot = path.join(path.resolve(root), target);
820
+ if (exists(fromRoot))
821
+ return fromRoot;
822
+ return path.join(path.dirname(path.resolve(docPath)), target);
823
+ }
824
+ }
825
+ _a = FileExistenceInvariant;
826
+ /** link-shape — every chain link target of the doc is a bare relative path (D2 ·
827
+ * #342). The shape rule reports ONCE here (single-responsibility strategy — the
828
+ * shared `LinkTargetShape` declaration): a malformed fill (a markdown link, a
829
+ * URL or a collation token) is judged BEFORE any resolution, so the
830
+ * file-existence / sibling-scan resolution faces silently skip malformed
831
+ * targets — the confusing per-strategy cascade never fires. */
832
+ export class LinkShapeInvariant extends FileExistenceInvariant {
833
+ name = "link-shape";
834
+ evaluate(ctx) {
835
+ const findings = [];
836
+ for (const { source, link } of this.chainLinks(ctx)) {
837
+ if (this.isPlaceholder(link.target))
838
+ continue;
839
+ const shape = LinkTargetShape.of(link.target);
840
+ if (shape.target !== null)
841
+ continue;
842
+ findings.push(this.finding(ctx, source, `the chain link target is not a bare relative path: ${link.target}`, shape.reason ?? ""));
843
+ }
844
+ return findings;
845
+ }
846
+ }
847
+ /** sibling-scan — every cross-linked doc must be a same-family sibling of this doc. */
848
+ export class SiblingScanInvariant extends FileExistenceInvariant {
849
+ name = "sibling-scan";
850
+ evaluate(ctx) {
851
+ const findings = [];
852
+ const baseline = new Set();
853
+ for (const root of SiblingScanInvariant.#scanRoots(ctx.root, ctx.path)) {
854
+ for (const entry of ctx.fs.list(root)) {
855
+ if (entry.endsWith(".md"))
856
+ baseline.add(entry);
857
+ }
858
+ }
859
+ for (const { source, link } of this.chainLinks(ctx)) {
860
+ if (this.isPlaceholder(link.target))
861
+ continue;
862
+ const shape = LinkTargetShape.of(link.target);
863
+ // D2: a malformed target is the link-shape face's call — the sibling face
864
+ // never basenames a markdown shell (the dead-tail `…)` miss).
865
+ if (shape.target === null)
866
+ continue;
867
+ const basename = path.basename(shape.target);
868
+ if (!baseline.has(basename)) {
869
+ findings.push(this.finding(ctx, source, `the cross-linked doc ${basename} is not a same-family sibling (not present in the sibling docs scan)`, `link to a sibling doc under the same ${DOC_ROOT_SEGMENTS} family`));
870
+ }
871
+ }
872
+ return findings;
873
+ }
874
+ /** The doc's own dir + the sibling doc-root dirs — the same-family scan roots,
875
+ * resolved on ONE basis (P9 T5 §2.8): the doc path and the doc roots
876
+ * (`ENGINE_RUNTIME.docRoots` segments) compose through `root` (the absolute
877
+ * basis) before they touch the filesystem — a relative string read without
878
+ * `root` would resolve against `process.cwd()` (the engine never chdirs),
879
+ * silently drifting off the repo root. `path.resolve(root, …)` reads an absolute
880
+ * doc path as itself and a repoRoot-relative one as joined to the basis (both
881
+ * callers — the pre-flight's absolute doc path and the judge's relative one — land
882
+ * on the same basis). The doc-root segments are read from the ONE declaration
883
+ * (never a hard-coded segment-name copy). */
884
+ static #scanRoots(root, docPath) {
885
+ return [
886
+ path.dirname(path.resolve(root, docPath)),
887
+ ...Object.values(ENGINE_DOC_ROOTS).map((dir) => path.join(root, dir)),
888
+ ];
889
+ }
890
+ }
891
+ /** cross-doc-chain — the Class-A/B chain resolves and its lineage tokens belong to the parent. */
892
+ export class CrossDocChainInvariant extends Invariant {
893
+ name = "cross-doc-chain";
894
+ evaluate(ctx) {
895
+ if (ctx.docKey === "overall-spec")
896
+ return this.overallChain(ctx);
897
+ if (ctx.docKey === "plan")
898
+ return this.planChain(ctx);
899
+ return this.specChain(ctx);
900
+ }
901
+ /** The overall chain-root face: a dispatch phase must be registered in the inventory. */
902
+ overallChain(ctx) {
903
+ if (ctx.phaseId === undefined || ctx.phaseId === null)
904
+ return [];
905
+ const data = this.overall(ctx);
906
+ if (data === null)
907
+ return [];
908
+ const registered = new Set(data.chain.phases.map((phase) => phase.id.toLowerCase()));
909
+ if (!registered.has(ctx.phaseId.toLowerCase())) {
910
+ return [
911
+ this.finding(ctx, "Phase inventory", `dispatch phase ${ctx.phaseId} is not registered in the parent overall's Phase inventory`, `register phase ${ctx.phaseId} in the Phase inventory`),
912
+ ];
913
+ }
914
+ return [];
915
+ }
916
+ /** The Class-A/Class-B plan chain: the `spec:`/`parent-program:` head targets + the Class-B lineage. */
917
+ planChain(ctx) {
918
+ const data = this.plan(ctx);
919
+ if (data === null)
920
+ return [];
921
+ const findings = [];
922
+ const specLink = data.chain.specLink;
923
+ if (specLink === null) {
924
+ findings.push(this.finding(ctx, "spec", "the plan carries no spec reference", "add a spec value pointing at the phase design spec"));
925
+ }
926
+ // The link-label drift judgment retired with the ChainLink label face — the
927
+ // spec link is a head scalar now (the `spec:` key), the label is not a fact.
928
+ if (data.chain.parentLink === null) {
929
+ findings.push(this.finding(ctx, "parent-program", "the plan carries no parent-program reference", "add a parent-program value pointing at the parent overall"));
930
+ }
931
+ findings.push(...this.classB(ctx, data.chain.parentLink, data.chain.parentTokens));
932
+ return findings;
933
+ }
934
+ /** The Class-B phase-spec chain: the parent-link lineage belongs to the parent overall. */
935
+ specChain(ctx) {
936
+ const data = this.phaseSpec(ctx);
937
+ if (data === null)
938
+ return [];
939
+ const findings = [];
940
+ if (data.chain.parentLink === null) {
941
+ findings.push(this.finding(ctx, "parent-program", "the phase-spec carries no parent-program reference", "add a parent-program value pointing at the parent overall"));
942
+ }
943
+ findings.push(...this.classB(ctx, data.chain.parentLink, data.chain.parentTokens));
944
+ return findings;
945
+ }
946
+ /** Class-B: the parent version tokens must belong to the parent overall's lineage. */
947
+ classB(ctx, parentLink, parentTokens) {
948
+ const findings = [];
949
+ if (parentLink === null || parentTokens.length === 0)
950
+ return findings;
951
+ const parentParsed = ctx.chainDocs?.get(parentLink.target);
952
+ if (parentParsed === undefined)
953
+ return findings;
954
+ const lineage = this.#parentLineage(parentParsed);
955
+ for (const token of parentTokens) {
956
+ if (!lineage.has(token)) {
957
+ findings.push(this.finding(ctx, "parent-program", `the parent-program version token ${token} does not belong to the parent overall's lineage`, `use a version the parent overall declares (its version front-matter or a Change-history row): ${[...lineage].join(", ")}`));
958
+ }
959
+ }
960
+ return findings;
961
+ }
962
+ /** The parent overall's lineage: its head `version:` scalar + every
963
+ * Change-history row version (the T6 read point — the header fact rides the
964
+ * typed head record, never a body line scan). */
965
+ #parentLineage(parent) {
966
+ const lineage = new Set();
967
+ if (parent.docType !== "overall-spec")
968
+ return lineage;
969
+ const version = parent.head?.version;
970
+ if (version !== null && version !== undefined)
971
+ lineage.add(version);
972
+ for (const row of parent.tables["Change history"].rows) {
973
+ const match = row[0]?.match(/v\d+\.\d+/);
974
+ if (match !== null)
975
+ lineage.add(match[0]);
976
+ }
977
+ return lineage;
978
+ }
979
+ }
980
+ /** section-scoped-domain — a value shape is enforced only inside its owning section. */
981
+ export class SectionScopedDomainInvariant extends Invariant {
982
+ name = "section-scoped-domain";
983
+ evaluate(ctx) {
984
+ if (ctx.docKey === "overall-spec")
985
+ return this.issueScopedRefs(ctx);
986
+ if (ctx.docKey === "phase-spec")
987
+ return this.designScoping(ctx);
988
+ return [];
989
+ }
990
+ /** Issue-ref forms are judged only within `## Issue inventory` (a content-wide rule
991
+ * would misfire on legacy `## Requirement inventory` tables whose ref cells are prose). */
992
+ issueScopedRefs(ctx) {
993
+ const data = this.overall(ctx);
994
+ if (data === null)
995
+ return [];
996
+ const slice = this.sliceOf(ctx, "Issue ref cell");
997
+ if (slice?.valuePattern === undefined)
998
+ return [];
999
+ const findings = [];
1000
+ for (const row of data.tables["Issue inventory"].rows) {
1001
+ const ref = row[1]?.trim() ?? "";
1002
+ if (ref === "" || ref.toLowerCase() === "none")
1003
+ continue;
1004
+ if (!slice.valuePattern.test(ref)) {
1005
+ findings.push(this.finding(ctx, "Issue inventory", `issue ref inside Issue inventory is outside its declared domain: ${ref}`, "use the anchored `#NNN#issuecomment-<digits>` / bare `#NNN` / `[#NNN]` / `none` or a parenthetical note"));
1006
+ }
1007
+ }
1008
+ return findings;
1009
+ }
1010
+ /** `### N.` design-group headings may appear only inside `## Design`. */
1011
+ designScoping(ctx) {
1012
+ const data = this.phaseSpec(ctx);
1013
+ if (data === null)
1014
+ return [];
1015
+ const slice = this.sliceOf(ctx, "### N. group heading");
1016
+ if (slice?.valuePattern === undefined)
1017
+ return [];
1018
+ const findings = [];
1019
+ for (const section of data.sections) {
1020
+ if (this.sliceOf(ctx, "## Design")?.valuePattern?.test(section.heading) === true)
1021
+ continue;
1022
+ for (const line of section.lines) {
1023
+ if (slice.valuePattern.test(line.trim())) {
1024
+ 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)"));
1025
+ }
1026
+ }
1027
+ }
1028
+ return findings;
1029
+ }
1030
+ }