@oscaner-skills/cdd-engine 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/package.json +4 -3
  4. package/src-next/__tests__/dead-decl.guard.test.ts +39 -0
  5. package/src-next/__tests__/floor.guard.test.ts +69 -0
  6. package/src-next/__tests__/issue-body.guard.test.ts +66 -0
  7. package/src-next/__tests__/phase-suffix.guard.test.ts +72 -0
  8. package/src-next/__tests__/smoke.integration.test.ts +60 -77
  9. package/src-next/__tests__/support/strip-comments.ts +99 -0
  10. package/src-next/__tests__/zero-dep.test.ts +6 -46
  11. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +39 -21
  12. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +40 -28
  13. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +40 -23
  14. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +38 -21
  15. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +21 -6
  16. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +22 -12
  17. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +23 -8
  18. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +21 -6
  19. package/src-next/contract/__tests__/declare.test.ts +251 -12
  20. package/src-next/contract/__tests__/doc.test.ts +214 -45
  21. package/src-next/contract/__tests__/dockey.guard.test.ts +58 -0
  22. package/src-next/contract/__tests__/edge-conditions.guard.test.ts +81 -0
  23. package/src-next/contract/__tests__/frontmatter.test.ts +164 -0
  24. package/src-next/contract/__tests__/judge.test.ts +410 -172
  25. package/src-next/contract/__tests__/lint.test.ts +49 -39
  26. package/src-next/contract/__tests__/project.test.ts +60 -19
  27. package/src-next/contract/__tests__/structure-pin.test.ts +186 -0
  28. package/src-next/contract/declare.ts +179 -91
  29. package/src-next/contract/doc.ts +227 -164
  30. package/src-next/contract/frontmatter.ts +233 -0
  31. package/src-next/contract/home-extractors.ts +397 -0
  32. package/src-next/contract/invariants.ts +214 -69
  33. package/src-next/contract/judge.ts +28 -19
  34. package/src-next/contract/lint.ts +5 -41
  35. package/src-next/contract/project.ts +103 -43
  36. package/src-next/contract/skill-anatomy.ts +39 -11
  37. package/src-next/face/__tests__/board-view.test.ts +318 -115
  38. package/src-next/face/__tests__/capsule.test.ts +49 -25
  39. package/src-next/face/__tests__/channel-closure.guard.test.ts +28 -1
  40. package/src-next/face/__tests__/cli.test.ts +1091 -837
  41. package/src-next/face/__tests__/face.test.ts +5 -5
  42. package/src-next/face/__tests__/install-rows.guard.test.ts +58 -0
  43. package/src-next/face/__tests__/preview.test.ts +374 -0
  44. package/src-next/face/__tests__/projection.test.ts +5 -3
  45. package/src-next/face/__tests__/repo-root.guard.test.ts +120 -0
  46. package/src-next/face/__tests__/termination.test.ts +650 -0
  47. package/src-next/face/artifacts.ts +90 -37
  48. package/src-next/face/board-view.ts +128 -138
  49. package/src-next/face/capsule.ts +30 -16
  50. package/src-next/face/cli.ts +306 -97
  51. package/src-next/face/declare.ts +15 -18
  52. package/src-next/face/gate.ts +19 -18
  53. package/src-next/face/host.ts +6 -30
  54. package/src-next/face/lifecycle.ts +213 -188
  55. package/src-next/face/preview.ts +151 -0
  56. package/src-next/face/projection.ts +4 -1
  57. package/src-next/face/route-render.ts +39 -14
  58. package/src-next/face/termination.ts +573 -0
  59. package/src-next/face/words.ts +20 -2
  60. package/src-next/infra/__tests__/infra.test.ts +49 -3
  61. package/src-next/infra/__tests__/root.test.ts +56 -0
  62. package/src-next/infra/doc-roots.ts +29 -0
  63. package/src-next/infra/root.ts +73 -0
  64. package/src-next/infra/runtime.ts +12 -65
  65. package/src-next/infra/workspace.ts +95 -5
  66. package/src-next/render/__tests__/render.test.ts +92 -41
  67. package/src-next/render/__tests__/skeleton.test.ts +282 -64
  68. package/src-next/render/issue-body.ts +5 -2
  69. package/src-next/render/skeleton.ts +155 -90
  70. package/src-next/render/templates.ts +51 -56
  71. package/src-next/session/__tests__/graph.test.ts +11 -4
  72. package/src-next/session/__tests__/ledger.test.ts +3 -2
  73. package/src-next/session/__tests__/next.test.ts +100 -8
  74. package/src-next/session/__tests__/preflight.test.ts +79 -25
  75. package/src-next/session/__tests__/round-naming.test.ts +142 -0
  76. package/src-next/session/__tests__/run.test.ts +140 -128
  77. package/src-next/session/__tests__/wave.test.ts +11 -4
  78. package/src-next/session/ledger.ts +96 -24
  79. package/src-next/session/next.ts +116 -15
  80. package/src-next/session/preflight.ts +41 -10
  81. package/src-next/session/round-naming.ts +84 -0
  82. package/src-next/session/run.ts +24 -20
  83. package/templates/report/issue-body.json +0 -46
  84. package/src-next/face/__tests__/sync-runner.test.ts +0 -70
@@ -15,6 +15,7 @@
15
15
 
16
16
  import { existsSync, readdirSync, readFileSync } from "node:fs";
17
17
  import path from "node:path";
18
+ import { ENGINE_DOC_ROOTS } from "../infra/doc-roots.ts";
18
19
  import type { ElementRegistry, RegistryElement } from "./declare.ts";
19
20
  import type {
20
21
  ChainLink,
@@ -27,12 +28,25 @@ import type {
27
28
  TaskBlock,
28
29
  } from "./doc.ts";
29
30
  import { MarkdownPrimitives } from "./doc.ts";
31
+ import type { FrontMatterHead } from "./frontmatter.ts";
30
32
  import type { DocKey, DocShape, DocSlices, ElementSlice } from "./project.ts";
31
33
 
32
34
  // ---------------------------------------------------------------------------
33
35
  // judgment records + the context
34
36
  // ---------------------------------------------------------------------------
35
37
 
38
+ /** The doc-tree root namespace derived from the ONE doc-root declaration (the
39
+ * common parent of the spec/plan roots) — the finding messages name the
40
+ * repo-root form `<namespace>/…` from THIS, never a hard-coded copy (P9 T5 §2.8). */
41
+ const DOC_ROOT_NAMESPACE = path.dirname(ENGINE_DOC_ROOTS.specs);
42
+
43
+ /** The two doc-root segment names derived from the same ONE declaration — the
44
+ * sibling-scan finding message's `<segments>` form names THIS, never a hard-coded
45
+ * copy (P9 T5 §2.8). */
46
+ const DOC_ROOT_SEGMENTS = Object.values(ENGINE_DOC_ROOTS)
47
+ .map((dir) => path.basename(dir))
48
+ .join("/");
49
+
36
50
  /** One contract finding — a single invariant violation, bound to a doc + field. */
37
51
  export interface Finding {
38
52
  /** The doc file the finding refers to. */
@@ -84,11 +98,15 @@ export interface JudgeContext {
84
98
  docKey: DocKey;
85
99
  /** The parsed structural record of the document. */
86
100
  parsed: ParsedDoc;
87
- /** The judged document's normalized content lines — the canonicalize view the
88
- * row-source seam (Contract.validate) builds ONCE per judgment: every
89
- * valuePattern / anchor-literal face (occurrenceLines · carrierLines ·
90
- * anchorLines and the parsed records) matches the view. The view is never
91
- * written back — the source document stays byte-identical. */
101
+ /** The document's typed front-matter head — the §2.2 delivery seam: the SAME
102
+ * record validate() fed into parse (front-matter-home elements judge THIS,
103
+ * never a body line scan — front matter is data, not body structure). */
104
+ head: FrontMatterHead;
105
+ /** The judged document's normalized content lines — the post-fence body's
106
+ * canonicalize view the row-source seam (Contract.validate) builds ONCE per
107
+ * judgment: every valuePattern / anchor-literal face (occurrenceLines ·
108
+ * carrierLines · anchorLines and the parsed records) matches the view. The
109
+ * view is never written back — the source document stays byte-identical. */
92
110
  lines: readonly string[];
93
111
  /** The document's file path (message attribution + the doc's own dir for links). */
94
112
  path: string;
@@ -248,7 +266,7 @@ export abstract class Invariant extends MarkdownPrimitives {
248
266
  /** Home surfaces the presence invariant judges — the structural doc surface
249
267
  * (table rows/columns/tokens are judged by hollow/section-scoped strategies). */
250
268
  const PRESENCE_HOMES = new Set([
251
- "header",
269
+ "frontmatter",
252
270
  "section",
253
271
  "facet",
254
272
  "graph",
@@ -271,6 +289,21 @@ export class PresenceInvariant extends Invariant {
271
289
  const slice = this.sliceOf(ctx, element.anchor);
272
290
  if (slice === undefined) continue;
273
291
  if (this.#derivedPresenceHolds(ctx, slice)) continue;
292
+ // The front-matter-home elements judge the typed head record (the §2.2
293
+ // delivery seam — NEVER the body line scan: front matter is data, and a
294
+ // whitespace line or a body-line mention of a key is not an occurrence).
295
+ if (slice.home === "frontmatter") {
296
+ if (ctx.head.value(element.anchor) !== null) continue;
297
+ findings.push(
298
+ this.finding(
299
+ ctx,
300
+ element.anchor,
301
+ `missing required element: ${element.anchor}`,
302
+ `add the "${element.anchor}" key to the document's front matter`,
303
+ ),
304
+ );
305
+ continue;
306
+ }
274
307
  if (this.occurrenceLines(ctx, slice).length === 0) {
275
308
  findings.push(
276
309
  this.finding(
@@ -441,9 +474,33 @@ export class DomainInvariant extends Invariant {
441
474
  const findings: Finding[] = [];
442
475
  for (const element of this.elementsOf(ctx)) {
443
476
  const slice = this.sliceOf(ctx, element.anchor);
444
- if (slice === undefined || slice.valuePattern === undefined) continue;
477
+ if (slice === undefined) continue;
478
+ // The front-matter-home elements judge the typed head SCALAR (the §2.2
479
+ // delivery seam — the registered value patterns are scalar shapes, §2.3).
480
+ // Absence is presence's surface; a present scalar outside the declared
481
+ // shape is the finding. The pattern is read from the REGISTRY ELEMENT
482
+ // (project.ts's header leg deliberately stops both slice RegExp
483
+ // compilations — the front-matter key is looked up against the head).
484
+ if (slice.home === "frontmatter") {
485
+ const value = ctx.head.value(element.anchor);
486
+ if (value === null) continue;
487
+ const rawPattern = element.valuePattern;
488
+ if (rawPattern === undefined) continue;
489
+ if (!new RegExp(rawPattern).test(value)) {
490
+ findings.push(
491
+ this.finding(
492
+ ctx,
493
+ element.anchor,
494
+ `value outside the declared domain: ${value}`,
495
+ `make the front-matter ${element.anchor} value match ${rawPattern}`,
496
+ ),
497
+ );
498
+ }
499
+ continue;
500
+ }
501
+ if (slice.valuePattern === undefined) continue;
445
502
  // The element is judged by the SHAPE of the lines that carry it structurally —
446
- // a `**Status**: Draft` line must match its declared pattern. A prose citation
503
+ // a table row or a heading must match its declared pattern. A prose citation
447
504
  // (a backticked code-span mention, or a table cell of a non-table element) is
448
505
  // not a carrier and is never judged as a value.
449
506
  for (const line of this.carrierLines(ctx, slice)) {
@@ -876,7 +933,7 @@ export class SelfBoundedInvariant extends Invariant {
876
933
  readonly name = "selfBounded";
877
934
 
878
935
  evaluate(ctx: JudgeContext): Finding[] {
879
- const headerVersion = this.#headerVersion(ctx);
936
+ const headerVersion = ctx.head.version;
880
937
  const historyVersions = this.#historyVersions(ctx);
881
938
  if (headerVersion === null || historyVersions.length === 0) return [];
882
939
  const findings: Finding[] = [];
@@ -885,9 +942,9 @@ export class SelfBoundedInvariant extends Invariant {
885
942
  findings.push(
886
943
  this.finding(
887
944
  ctx,
888
- "**Version**",
945
+ "version",
889
946
  `the header version ${headerVersion} is not the change-history's newest row (${newest})`,
890
- "bump both the **Version** header and the newest Change-history row together",
947
+ "bump both the version front-matter key and the newest Change-history row together",
891
948
  ),
892
949
  );
893
950
  }
@@ -895,9 +952,9 @@ export class SelfBoundedInvariant extends Invariant {
895
952
  findings.push(
896
953
  this.finding(
897
954
  ctx,
898
- "**Version**",
955
+ "version",
899
956
  `the header version ${headerVersion} is outside the document's own lineage`,
900
- `the **Version** header must belong to the Change-history row versions: ${historyVersions.join(", ")}`,
957
+ `the version front-matter key must belong to the Change-history row versions: ${historyVersions.join(", ")}`,
901
958
  ),
902
959
  );
903
960
  }
@@ -928,14 +985,6 @@ export class SelfBoundedInvariant extends Invariant {
928
985
  .filter((version) => version !== null) as readonly string[];
929
986
  }
930
987
 
931
- #headerVersion(ctx: JudgeContext): string | null {
932
- for (const line of this.anchorLines(ctx, "**Version**")) {
933
- const tokens = this.versionTokens(line);
934
- if (tokens.length > 0) return tokens[0];
935
- }
936
- return null;
937
- }
938
-
939
988
  #firstVersion(text: string): string | null {
940
989
  const match = text.match(/v\d+\.\d+/);
941
990
  return match === null ? null : match[0];
@@ -964,6 +1013,45 @@ export class SelfBoundedInvariant extends Invariant {
964
1013
  // the four context-seam strategies
965
1014
  // ---------------------------------------------------------------------------
966
1015
 
1016
+ /** The chain-link target shape contract (D2, shape judged at the boundary — the #342
1017
+ * fix): a link target must be a BARE relative path (the repo-root form
1018
+ * `docs/kairos/specs/…-overall.md` or a doc-relative file name) — never a
1019
+ * markdown-link shell (`[label](path)`), a URL or a collation token
1020
+ * (whitespace / parens / angle brackets). The ONE expression of the shape rule:
1021
+ * `of()` yields either the accepted (trimmed) target or the reason the shape is
1022
+ * invalid; the chain strategies judge the shape BEFORE any resolution, so a
1023
+ * malformed fill reports the shape rule once — the confusing resolution cascade
1024
+ * (#342's dead-tail `basename` + the file-existence double failure) never
1025
+ * fires. */
1026
+ export class LinkTargetShape {
1027
+ /** The accepted, trimmed target — null when the shape is invalid. */
1028
+ readonly target: string | null;
1029
+ /** The shape-rule reason the target is invalid — null when accepted. */
1030
+ readonly reason: string | null;
1031
+
1032
+ private constructor(target: string | null, reason: string | null) {
1033
+ this.target = target;
1034
+ this.reason = reason;
1035
+ }
1036
+
1037
+ /** Judge one raw target — a bare relative path accepts; any collation token
1038
+ * rejects with the shape rule. */
1039
+ static of(raw: string): LinkTargetShape {
1040
+ const trimmed = raw.trim();
1041
+ // The rejected collation tokens — whitespace, a markdown-link shell's
1042
+ // brackets/parens (`[label](path)`), stray angle brackets and the `://`
1043
+ // URL scheme. The path separators `/` and `:` alone stay legal (a bare
1044
+ // relative path carries both) — only the URL-scheme pairing rejects.
1045
+ if (/[\s()[\]<>]|:\/\//.test(trimmed)) {
1046
+ return new LinkTargetShape(
1047
+ null,
1048
+ "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",
1049
+ );
1050
+ }
1051
+ return new LinkTargetShape(trimmed, null);
1052
+ }
1053
+ }
1054
+
967
1055
  /** file-existence — every chain link target of the doc resolves to an existing file. */
968
1056
  export class FileExistenceInvariant extends Invariant {
969
1057
  readonly name: string = "file-existence";
@@ -972,13 +1060,17 @@ export class FileExistenceInvariant extends Invariant {
972
1060
  const findings: Finding[] = [];
973
1061
  for (const { source, link } of this.chainLinks(ctx)) {
974
1062
  if (this.isPlaceholder(link.target)) continue;
975
- if (!this.#targetExists(ctx, link.target)) {
1063
+ const shape = LinkTargetShape.of(link.target);
1064
+ // D2: a malformed target is the link-shape face's call — the resolution
1065
+ // faces never feed it to the path resolution as a literal.
1066
+ if (shape.target === null) continue;
1067
+ if (!this.#targetExists(ctx, shape.target)) {
976
1068
  findings.push(
977
1069
  this.finding(
978
1070
  ctx,
979
1071
  source,
980
- `the chain link target does not resolve to an existing file: ${link.target}`,
981
- "fix the link target (repo-root form docs/kairos/... or a file-relative path)",
1072
+ `the chain link target does not resolve to an existing file: ${shape.target}`,
1073
+ `fix the link target (repo-root form ${DOC_ROOT_NAMESPACE}/... or a file-relative path)`,
982
1074
  ),
983
1075
  );
984
1076
  }
@@ -1005,16 +1097,15 @@ export class FileExistenceInvariant extends Invariant {
1005
1097
  if (ctx.docKey === "plan") {
1006
1098
  const data = this.plan(ctx);
1007
1099
  if (data !== null) {
1008
- if (data.chain.specLink !== null)
1009
- links.push({ source: "**Spec:**", link: data.chain.specLink });
1100
+ if (data.chain.specLink !== null) links.push({ source: "spec", link: data.chain.specLink });
1010
1101
  if (data.chain.parentLink !== null)
1011
- links.push({ source: "**Parent program**", link: data.chain.parentLink });
1102
+ links.push({ source: "parent-program", link: data.chain.parentLink });
1012
1103
  }
1013
1104
  }
1014
1105
  if (ctx.docKey === "phase-spec") {
1015
1106
  const data = this.phaseSpec(ctx);
1016
1107
  if (data !== null && data.chain.parentLink !== null) {
1017
- links.push({ source: "**Parent program**", link: data.chain.parentLink });
1108
+ links.push({ source: "parent-program", link: data.chain.parentLink });
1018
1109
  }
1019
1110
  }
1020
1111
  return links;
@@ -1029,14 +1120,62 @@ export class FileExistenceInvariant extends Invariant {
1029
1120
  }
1030
1121
 
1031
1122
  /** Whether the target exists — absolute targets directly; repo-root form first, the
1032
- * doc's own dir as the file-relative fallback. */
1123
+ * doc's own dir as the file-relative fallback. The resolution chain is
1124
+ * single-sourced in `targetPath` (the ONE home the CLI's plan `spec:` rebase
1125
+ * delegates to as well — P9 branch-review-1 F8: a future contract change
1126
+ * cannot silently diverge from the CLI's mirror). */
1033
1127
  #targetExists(ctx: JudgeContext, target: string): boolean {
1034
- if (path.isAbsolute(target)) return ctx.fs.exists(target);
1035
- return (
1036
- ctx.fs.exists(path.join(ctx.root, target)) ||
1037
- ctx.fs.exists(path.join(path.dirname(ctx.path), target))
1128
+ return ctx.fs.exists(
1129
+ FileExistenceInvariant.targetPath(ctx.root, ctx.path, target, (p) => ctx.fs.exists(p)),
1038
1130
  );
1039
1131
  }
1132
+
1133
+ /** The ONE chain-link target-resolution chain (the doc-contract's own judgment,
1134
+ * reused by the CLI's plan `spec:` rebase — F8): an absolute target as
1135
+ * itself; else the repoRoot-relative reading when it exists; else the doc-dir
1136
+ * (file-relative) reading. `exists` is the caller's filesystem seam (the
1137
+ * judgment's `ctx.fs`, the CLI's `fs.existsSync`) — the resolution is the shared
1138
+ * fact, the read is injected. When neither reading exists the doc-dir path is
1139
+ * returned (the link-space semantic — the caller owns the truly-missing case). */
1140
+ static targetPath(
1141
+ root: string,
1142
+ docPath: string,
1143
+ target: string,
1144
+ exists: (path: string) => boolean,
1145
+ ): string {
1146
+ if (path.isAbsolute(target)) return target;
1147
+ const fromRoot = path.join(path.resolve(root), target);
1148
+ if (exists(fromRoot)) return fromRoot;
1149
+ return path.join(path.dirname(path.resolve(docPath)), target);
1150
+ }
1151
+ }
1152
+
1153
+ /** link-shape — every chain link target of the doc is a bare relative path (D2 ·
1154
+ * #342). The shape rule reports ONCE here (single-responsibility strategy — the
1155
+ * shared `LinkTargetShape` declaration): a malformed fill (a markdown link, a
1156
+ * URL or a collation token) is judged BEFORE any resolution, so the
1157
+ * file-existence / sibling-scan resolution faces silently skip malformed
1158
+ * targets — the confusing per-strategy cascade never fires. */
1159
+ export class LinkShapeInvariant extends FileExistenceInvariant {
1160
+ readonly name = "link-shape";
1161
+
1162
+ evaluate(ctx: JudgeContext): Finding[] {
1163
+ const findings: Finding[] = [];
1164
+ for (const { source, link } of this.chainLinks(ctx)) {
1165
+ if (this.isPlaceholder(link.target)) continue;
1166
+ const shape = LinkTargetShape.of(link.target);
1167
+ if (shape.target !== null) continue;
1168
+ findings.push(
1169
+ this.finding(
1170
+ ctx,
1171
+ source,
1172
+ `the chain link target is not a bare relative path: ${link.target}`,
1173
+ shape.reason ?? "",
1174
+ ),
1175
+ );
1176
+ }
1177
+ return findings;
1178
+ }
1040
1179
  }
1041
1180
 
1042
1181
  /** sibling-scan — every cross-linked doc must be a same-family sibling of this doc. */
@@ -1046,21 +1185,25 @@ export class SiblingScanInvariant extends FileExistenceInvariant {
1046
1185
  evaluate(ctx: JudgeContext): Finding[] {
1047
1186
  const findings: Finding[] = [];
1048
1187
  const baseline = new Set<string>();
1049
- for (const root of SiblingScanInvariant.#scanRoots(ctx.path)) {
1188
+ for (const root of SiblingScanInvariant.#scanRoots(ctx.root, ctx.path)) {
1050
1189
  for (const entry of ctx.fs.list(root)) {
1051
1190
  if (entry.endsWith(".md")) baseline.add(entry);
1052
1191
  }
1053
1192
  }
1054
1193
  for (const { source, link } of this.chainLinks(ctx)) {
1055
1194
  if (this.isPlaceholder(link.target)) continue;
1056
- const basename = path.basename(link.target);
1195
+ const shape = LinkTargetShape.of(link.target);
1196
+ // D2: a malformed target is the link-shape face's call — the sibling face
1197
+ // never basenames a markdown shell (the dead-tail `…)` miss).
1198
+ if (shape.target === null) continue;
1199
+ const basename = path.basename(shape.target);
1057
1200
  if (!baseline.has(basename)) {
1058
1201
  findings.push(
1059
1202
  this.finding(
1060
1203
  ctx,
1061
1204
  source,
1062
1205
  `the cross-linked doc ${basename} is not a same-family sibling (not present in the sibling docs scan)`,
1063
- "link to a sibling doc under the same specs/plans family",
1206
+ `link to a sibling doc under the same ${DOC_ROOT_SEGMENTS} family`,
1064
1207
  ),
1065
1208
  );
1066
1209
  }
@@ -1068,11 +1211,21 @@ export class SiblingScanInvariant extends FileExistenceInvariant {
1068
1211
  return findings;
1069
1212
  }
1070
1213
 
1071
- /** The doc's own dir + its sibling specs/plans dirs — the same-family scan roots. */
1072
- static #scanRoots(docPath: string): readonly string[] {
1073
- const own = path.dirname(docPath);
1074
- const grand = path.dirname(own);
1075
- return [own, path.join(grand, "specs"), path.join(grand, "plans")];
1214
+ /** The doc's own dir + the sibling doc-root dirs — the same-family scan roots,
1215
+ * resolved on ONE basis (P9 T5 §2.8): the doc path and the doc roots
1216
+ * (`ENGINE_RUNTIME.docRoots` segments) compose through `root` (the absolute
1217
+ * basis) before they touch the filesystem — a relative string read without
1218
+ * `root` would resolve against `process.cwd()` (the engine never chdirs),
1219
+ * silently drifting off the repo root. `path.resolve(root, …)` reads an absolute
1220
+ * doc path as itself and a repoRoot-relative one as joined to the basis (both
1221
+ * callers — the pre-flight's absolute doc path and the judge's relative one — land
1222
+ * on the same basis). The doc-root segments are read from the ONE declaration
1223
+ * (never a hard-coded segment-name copy). */
1224
+ static #scanRoots(root: string, docPath: string): readonly string[] {
1225
+ return [
1226
+ path.dirname(path.resolve(root, docPath)),
1227
+ ...Object.values(ENGINE_DOC_ROOTS).map((dir) => path.join(root, dir)),
1228
+ ];
1076
1229
  }
1077
1230
  }
1078
1231
 
@@ -1105,7 +1258,7 @@ export class CrossDocChainInvariant extends Invariant {
1105
1258
  return [];
1106
1259
  }
1107
1260
 
1108
- /** The Class-A/Class-B plan chain: `**Spec:**` label == basename + the Class-B lineage. */
1261
+ /** The Class-A/Class-B plan chain: the `spec:`/`parent-program:` head targets + the Class-B lineage. */
1109
1262
  private planChain(ctx: JudgeContext): Finding[] {
1110
1263
  const data = this.plan(ctx);
1111
1264
  if (data === null) return [];
@@ -1115,28 +1268,21 @@ export class CrossDocChainInvariant extends Invariant {
1115
1268
  findings.push(
1116
1269
  this.finding(
1117
1270
  ctx,
1118
- "**Spec:**",
1119
- "the plan carries no **Spec:** reference",
1120
- "add a **Spec:** link pointing at the phase design spec",
1121
- ),
1122
- );
1123
- } else if (specLink.label.trim() !== path.basename(specLink.target)) {
1124
- findings.push(
1125
- this.finding(
1126
- ctx,
1127
- "**Spec:**",
1128
- `the **Spec:** link label ${specLink.label.trim()} does not equal the resolved basename ${path.basename(specLink.target)}`,
1129
- "make the link label equal the resolved file's basename",
1271
+ "spec",
1272
+ "the plan carries no spec reference",
1273
+ "add a spec value pointing at the phase design spec",
1130
1274
  ),
1131
1275
  );
1132
1276
  }
1277
+ // The link-label drift judgment retired with the ChainLink label face — the
1278
+ // spec link is a head scalar now (the `spec:` key), the label is not a fact.
1133
1279
  if (data.chain.parentLink === null) {
1134
1280
  findings.push(
1135
1281
  this.finding(
1136
1282
  ctx,
1137
- "**Parent program**",
1138
- "the plan carries no **Parent program** link",
1139
- "add the **Parent program** link pointing at the parent overall",
1283
+ "parent-program",
1284
+ "the plan carries no parent-program reference",
1285
+ "add a parent-program value pointing at the parent overall",
1140
1286
  ),
1141
1287
  );
1142
1288
  }
@@ -1153,9 +1299,9 @@ export class CrossDocChainInvariant extends Invariant {
1153
1299
  findings.push(
1154
1300
  this.finding(
1155
1301
  ctx,
1156
- "**Parent program**",
1157
- "the phase-spec carries no **Parent program** link",
1158
- "add the **Parent program** link pointing at the parent overall",
1302
+ "parent-program",
1303
+ "the phase-spec carries no parent-program reference",
1304
+ "add a parent-program value pointing at the parent overall",
1159
1305
  ),
1160
1306
  );
1161
1307
  }
@@ -1179,9 +1325,9 @@ export class CrossDocChainInvariant extends Invariant {
1179
1325
  findings.push(
1180
1326
  this.finding(
1181
1327
  ctx,
1182
- "**Parent program**",
1183
- `the **Parent program** version token ${token} does not belong to the parent overall's lineage`,
1184
- `use a version the parent overall declares (its **Version** header or a Change-history row): ${[...lineage].join(", ")}`,
1328
+ "parent-program",
1329
+ `the parent-program version token ${token} does not belong to the parent overall's lineage`,
1330
+ `use a version the parent overall declares (its version front-matter or a Change-history row): ${[...lineage].join(", ")}`,
1185
1331
  ),
1186
1332
  );
1187
1333
  }
@@ -1189,15 +1335,14 @@ export class CrossDocChainInvariant extends Invariant {
1189
1335
  return findings;
1190
1336
  }
1191
1337
 
1192
- /** The parent overall's lineage: its header version + every Change-history row version. */
1338
+ /** The parent overall's lineage: its head `version:` scalar + every
1339
+ * Change-history row version (the T6 read point — the header fact rides the
1340
+ * typed head record, never a body line scan). */
1193
1341
  #parentLineage(parent: ParsedDoc): Set<string> {
1194
1342
  const lineage = new Set<string>();
1195
1343
  if (parent.docType !== "overall-spec") return lineage;
1196
- for (const line of (parent as OverallParsed).headerLines) {
1197
- if (line.includes("**Version**")) {
1198
- for (const token of this.versionTokens(line)) lineage.add(token);
1199
- }
1200
- }
1344
+ const version = (parent as OverallParsed).head?.version;
1345
+ if (version !== null && version !== undefined) lineage.add(version);
1201
1346
  for (const row of (parent as OverallParsed).tables["Change history"].rows) {
1202
1347
  const match = row[0]?.match(/v\d+\.\d+/);
1203
1348
  if (match !== null) lineage.add(match[0]);
@@ -12,6 +12,7 @@ import { Words } from "../face/words.ts";
12
12
  import { declaredRegistries } from "./declare.ts";
13
13
  import type { ParsedDoc } from "./doc.ts";
14
14
  import { docTypeParsers } from "./doc.ts";
15
+ import { FrontMatterExtractor } from "./frontmatter.ts";
15
16
  import type { DocFs, Finding, Invariant, JudgeContext } from "./invariants.ts";
16
17
  import {
17
18
  ContinuityInvariant,
@@ -20,6 +21,7 @@ import {
20
21
  DomainInvariant,
21
22
  FileExistenceInvariant,
22
23
  HollowInvariant,
24
+ LinkShapeInvariant,
23
25
  NodeFs,
24
26
  OrderInvariant,
25
27
  PresenceInvariant,
@@ -30,12 +32,9 @@ import {
30
32
  UniquenessInvariant,
31
33
  } from "./invariants.ts";
32
34
  import type { DocKey } from "./project.ts";
33
- import { Projector } from "./project.ts";
35
+ import { DOC_KEYS, Projector } from "./project.ts";
34
36
  import { Translator } from "./translate.ts";
35
37
 
36
- /** The four doc-type record keys — the policy-composition identity. */
37
- const DOC_KEYS: readonly DocKey[] = ["overall-spec", "plan", "phase-spec", "single-spec"];
38
-
39
38
  /** The judgment input — the doc's identity, content and the seam closures. */
40
39
  export interface ContractInput {
41
40
  /** The doc-type record key of the document under judgment. */
@@ -59,16 +58,20 @@ export interface ContractInput {
59
58
  * strategy set is stateless (each strategy reads its judgment data from the
60
59
  * context), so construction is cheap and validates compose safely.
61
60
  *
62
- * The P7 structure-plane canonicalize seam (design spec §2.1): the Contract
63
- * self-holds a Translator, and validate() canonicalizes EVERY input line once at
64
- * the row source — the normalized view shared by parse and JudgeContext.lines.
65
- * Every valuePattern judgment face (presence occurrenceLines · domain
66
- * carrierLines · section-scoped · crosslink) matches the view, so the legacy
67
- * Chinese charter markers (the doc-arch decision-group / upstream-endorsements
68
- * leaves) match their English canonical element patterns through the recognition
69
- * face — never a second hand-written zh pattern. The view is never written back:
70
- * the source document stays byte-identical and the original lines remain in
71
- * input.content.
61
+ * The P7 structure-plane canonicalize seam (design spec §2.1) + the T6 front-matter
62
+ * delivery seam (§2.2): the Contract self-holds a Translator, and validate()
63
+ * canonicalizes EVERY body line once at the row source — the normalized view
64
+ * shared by parse and JudgeContext.lines. The split order is RAW-first: the raw
65
+ * content resolves its front-matter head BEFORE any canonicalize (front matter is
66
+ * data — the canonicalize view would silently rewrite registered Chinese aliases
67
+ * inside header values), then the post-fence body lines canonicalize and the SAME
68
+ * typed head rides into parse(lines, head) and JudgeContext.head. Every
69
+ * valuePattern judgment face (presence occurrenceLines · domain carrierLines ·
70
+ * section-scoped · crosslink) matches the view, so the legacy Chinese charter
71
+ * markers (the doc-arch decision-group / upstream-endorsements leaves) match their
72
+ * English canonical element patterns through the recognition face — never a second
73
+ * hand-written zh pattern. The view is never written back: the source document
74
+ * stays byte-identical and the original lines remain in input.content.
72
75
  */
73
76
  export class Contract {
74
77
  /** The per-doc-key policy sets — the declared composition of the strategy family.
@@ -90,15 +93,20 @@ export class Contract {
90
93
  this.#translator = new Translator(new Words());
91
94
  }
92
95
 
93
- /** validate(doc) — parse, compose, run, aggregate. The single judgment entry.
94
- * Every input line canonicalizes ONCE at the row source (the normalized view);
95
- * parse and the judgment context read the same view, the source stays intact. */
96
+ /** validate(doc) — split, parse, compose, run, aggregate. The single judgment entry.
97
+ * The RAW content resolves its front-matter head first (the data plane — never
98
+ * canonicalized); the post-fence body lines canonicalize ONCE at the row source
99
+ * (the normalized view), and the SAME typed head rides into parse(lines, head)
100
+ * and JudgeContext.head (§2.2's delivery seam — the chain facts the head carries
101
+ * are the same record the invariants judge). The source stays intact. */
96
102
  validate(input: ContractInput): Finding[] {
97
- const lines = input.content.split("\n").map((line) => this.#translator.canonicalize(line));
98
- const parsed = docTypeParsers[input.docKey].parse(lines);
103
+ const { head, body } = FrontMatterExtractor.split(input.content);
104
+ const lines = body.split("\n").map((line) => this.#translator.canonicalize(line));
105
+ const parsed = docTypeParsers[input.docKey].parse(lines, head);
99
106
  const context: JudgeContext = {
100
107
  docKey: input.docKey,
101
108
  parsed,
109
+ head,
102
110
  lines,
103
111
  path: input.path,
104
112
  root: input.root,
@@ -128,6 +136,7 @@ export class Contract {
128
136
  new ResidueInvariant(),
129
137
  new HollowInvariant(),
130
138
  new SelfBoundedInvariant(),
139
+ new LinkShapeInvariant(),
131
140
  new FileExistenceInvariant(),
132
141
  new SiblingScanInvariant(),
133
142
  new CrossDocChainInvariant(),
@@ -15,18 +15,17 @@
15
15
  // unregistered targets (missing-id) and self-edges (self-loop) stay silent —
16
16
  // a suspect is always an existing task with a lower id whose edge was simply
17
17
  // not declared (forward references are legal — no contradiction class).
18
- // · cross-doc label drift (plan / phase-spec) — the Class-B `**Parent
19
- // program**` link whose label (version tokens stripped) drifts from the
20
- // target's basename. The Class-A `**Spec:**` drift is the cross-doc-chain
21
- // invariant's BLOCK, never re-observed here.
18
+ //
19
+ // The cross-doc label-drift observation (Class-B `parent-program:` label vs
20
+ // target basename) retired with the ChainLink label face at the front-matter flip
21
+ // (T6) — the chain facts ride the typed head scalars, a link label is not a fact.
22
22
  //
23
23
  // Every warning is a Warn — a WARN-only observation, never a Finding, never a
24
24
  // BLOCK. Module-level exports are types / the class — zero behavior-carrying
25
25
  // bare functions (the plan's zero-bare-function discipline).
26
26
 
27
- import path from "node:path";
28
27
  import { declaredRegistries } from "./declare.ts";
29
- import type { ChainLink, ParsedDoc, PlanParsed, TaskBlock } from "./doc.ts";
28
+ import type { ParsedDoc, PlanParsed, TaskBlock } from "./doc.ts";
30
29
  import { MarkdownPrimitives } from "./doc.ts";
31
30
  import type { ReferenceEntry, ReferenceProjection } from "./project.ts";
32
31
  import { Projector } from "./project.ts";
@@ -91,7 +90,6 @@ export class LintPass extends MarkdownPrimitives {
91
90
  warns.push(...this.#numberingAdvisories(input, input.parsed));
92
91
  warns.push(...this.#transitiveAdvisories(input, input.parsed));
93
92
  }
94
- warns.push(...this.#crossDocDriftWarns(input, input.parsed.chain.parentLink));
95
93
  return warns;
96
94
  }
97
95
 
@@ -225,40 +223,6 @@ export class LintPass extends MarkdownPrimitives {
225
223
  return line.replace(/`+[^`\n]*`+/g, "");
226
224
  }
227
225
 
228
- // -------------------------------------------------------------------------
229
- // the cross-doc drift observation (plan / phase-spec)
230
- // -------------------------------------------------------------------------
231
-
232
- /** The Class-B `**Parent program**` link whose label (version tokens stripped)
233
- * drifts from the target basename — one WARN per offending link. */
234
- #crossDocDriftWarns(input: LintInput, parent: ChainLink | null): Warn[] {
235
- if (parent === null || parent.target.trim() === "") return [];
236
- if (this.#labelWithoutVersion(parent.label) !== path.basename(parent.target)) {
237
- return [
238
- {
239
- path: input.path,
240
- field: "**Parent program**",
241
- message: `the **Parent program** label ${JSON.stringify(parent.label.trim())} does not resolve to the target basename ${path.basename(parent.target)}`,
242
- fix: "make the link label equal the resolved file's basename (a trailing version token is allowed)",
243
- kind: "reference-lint",
244
- },
245
- ];
246
- }
247
- return [];
248
- }
249
-
250
- /** The label with a trailing version-token segment stripped (the canonical
251
- * `basename v<m>.<n>` Class-B form) — the shared token primitive parses the
252
- * tokens, never a re-typed version regex. */
253
- #labelWithoutVersion(label: string): string {
254
- const stripped = label.trim();
255
- const tokens = this.versionTokens(stripped);
256
- if (tokens.length === 0) return stripped;
257
- const last = tokens[tokens.length - 1];
258
- const index = stripped.lastIndexOf(last);
259
- return index <= 0 ? "" : stripped.slice(0, index).trimEnd();
260
- }
261
-
262
226
  // -------------------------------------------------------------------------
263
227
  // construction helpers
264
228
  // -------------------------------------------------------------------------