@oscaner-skills/cdd-engine 1.0.0 → 2.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 (99) hide show
  1. package/README.md +9 -8
  2. package/README.zh-CN.md +9 -8
  3. package/package.json +15 -22
  4. package/src-next/__tests__/bin.test.ts +128 -0
  5. package/src-next/__tests__/smoke.integration.test.ts +202 -0
  6. package/src-next/__tests__/zero-dep.test.ts +134 -0
  7. package/src-next/bin.ts +61 -0
  8. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +238 -0
  9. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +153 -0
  10. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +173 -0
  11. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +89 -0
  12. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +225 -0
  13. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +155 -0
  14. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +175 -0
  15. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +85 -0
  16. package/src-next/contract/__tests__/declare.test.ts +242 -0
  17. package/src-next/contract/__tests__/doc.test.ts +358 -0
  18. package/src-next/contract/__tests__/judge.test.ts +873 -0
  19. package/src-next/contract/__tests__/lint.test.ts +314 -0
  20. package/src-next/contract/__tests__/project.test.ts +419 -0
  21. package/src-next/contract/__tests__/translate.test.ts +96 -0
  22. package/src-next/contract/declare.ts +983 -0
  23. package/src-next/contract/doc.ts +753 -0
  24. package/src-next/contract/invariants.ts +1268 -0
  25. package/src-next/contract/judge.ts +142 -0
  26. package/src-next/contract/lint.ts +275 -0
  27. package/src-next/contract/project.ts +596 -0
  28. package/src-next/contract/skill-anatomy.ts +273 -0
  29. package/src-next/contract/translate.ts +113 -0
  30. package/src-next/face/__tests__/board-view.test.ts +948 -0
  31. package/src-next/face/__tests__/capsule.test.ts +276 -0
  32. package/src-next/face/__tests__/channel-closure.guard.test.ts +102 -0
  33. package/src-next/face/__tests__/cli.test.ts +4643 -0
  34. package/src-next/face/__tests__/face.test.ts +289 -0
  35. package/src-next/face/__tests__/graph-view.test.ts +61 -0
  36. package/src-next/face/__tests__/host.test.ts +24 -0
  37. package/src-next/face/__tests__/negation.ts +6 -0
  38. package/src-next/face/__tests__/projection.test.ts +301 -0
  39. package/src-next/face/__tests__/sync-runner.test.ts +70 -0
  40. package/src-next/face/__tests__/words.guard.test.ts +93 -0
  41. package/src-next/face/artifacts.ts +195 -0
  42. package/src-next/face/board-view.ts +662 -0
  43. package/src-next/face/capsule.ts +149 -0
  44. package/src-next/face/cli.ts +819 -0
  45. package/src-next/face/declare.ts +326 -0
  46. package/src-next/face/gate.ts +170 -0
  47. package/src-next/face/graph-view.ts +74 -0
  48. package/src-next/face/host.ts +326 -0
  49. package/src-next/face/lifecycle.ts +700 -0
  50. package/src-next/face/projection.ts +282 -0
  51. package/src-next/face/route-render.ts +160 -0
  52. package/src-next/face/words.ts +296 -0
  53. package/src-next/infra/__tests__/infra.test.ts +287 -0
  54. package/src-next/infra/config.ts +42 -0
  55. package/src-next/infra/git.ts +39 -0
  56. package/src-next/infra/process.ts +34 -0
  57. package/src-next/infra/runtime.ts +185 -0
  58. package/src-next/infra/workspace.ts +232 -0
  59. package/src-next/render/__tests__/render.test.ts +499 -0
  60. package/src-next/render/__tests__/skeleton.test.ts +466 -0
  61. package/src-next/render/brief.ts +121 -0
  62. package/src-next/render/issue-body.ts +159 -0
  63. package/src-next/render/skeleton.ts +437 -0
  64. package/src-next/render/templates.ts +650 -0
  65. package/src-next/session/__tests__/graph.test.ts +270 -0
  66. package/src-next/session/__tests__/handoff-plane.guard.test.ts +48 -0
  67. package/src-next/session/__tests__/handoff-schema.test.ts +310 -0
  68. package/src-next/session/__tests__/ledger.test.ts +744 -0
  69. package/src-next/session/__tests__/next.test.ts +368 -0
  70. package/src-next/session/__tests__/preflight.test.ts +491 -0
  71. package/src-next/session/__tests__/run.test.ts +1014 -0
  72. package/src-next/session/__tests__/wave-line-phase.guard.test.ts +49 -0
  73. package/src-next/session/__tests__/wave.test.ts +469 -0
  74. package/src-next/session/faces.ts +110 -0
  75. package/src-next/session/graph.ts +411 -0
  76. package/src-next/session/handoff-schema.ts +373 -0
  77. package/src-next/session/ledger.ts +1004 -0
  78. package/src-next/session/next.ts +192 -0
  79. package/src-next/session/preflight.ts +240 -0
  80. package/src-next/session/run.ts +606 -0
  81. package/src-next/session/state.ts +30 -0
  82. package/src-next/session/wave.ts +139 -0
  83. package/templates/report/issue-body.json +18 -20
  84. package/dist/chunks/branch.mjs +0 -480
  85. package/dist/chunks/docs.mjs +0 -253
  86. package/dist/chunks/task.mjs +0 -913
  87. package/dist/cli.mjs +0 -5457
  88. package/dist/documents/schema/add-phase-protocol.json +0 -126
  89. package/dist/documents/schema/overall.json +0 -361
  90. package/dist/documents/schema/phase-spec.json +0 -145
  91. package/dist/documents/schema/plan.json +0 -191
  92. package/dist/documents/schema/skill-anatomy.json +0 -233
  93. package/dist/resources/harness-registry.json +0 -49
  94. package/dist/shared/cdd-engine.liioziig.mjs +0 -184
  95. package/templates/engine-config.json +0 -302
  96. package/templates/schema/cache-profile-schema.json +0 -23
  97. package/templates/schema/docs-handoff-schema.json +0 -129
  98. package/templates/schema/task-handoff-schema.json +0 -332
  99. package/templates/template-contract.json +0 -231
@@ -0,0 +1,142 @@
1
+ // packages/cdd-engine/src-next/contract/judge.ts
2
+ // T4 — the single interpreter's coordinator (design spec §2.1): the Contract
3
+ // class's validate() is the ONLY entry for structural judgment. It loads the
4
+ // parse context through the doc-type parsers (doc.ts — pure parse), composes the
5
+ // per-doc-key invariant strategy set (invariants.ts) as declared data, runs every
6
+ // strategy in order, and aggregates the findings. Judgment dispatch is a record
7
+ // index over the declared strategy set — zero switch-case, zero hand-written
8
+ // judgment branches in this module (the plan's coordinator semantics: the
9
+ // polymorphic strategy family judges, the coordinator assembles).
10
+
11
+ import { Words } from "../face/words.ts";
12
+ import { declaredRegistries } from "./declare.ts";
13
+ import type { ParsedDoc } from "./doc.ts";
14
+ import { docTypeParsers } from "./doc.ts";
15
+ import type { DocFs, Finding, Invariant, JudgeContext } from "./invariants.ts";
16
+ import {
17
+ ContinuityInvariant,
18
+ CrossDocChainInvariant,
19
+ CrosslinkInvariant,
20
+ DomainInvariant,
21
+ FileExistenceInvariant,
22
+ HollowInvariant,
23
+ NodeFs,
24
+ OrderInvariant,
25
+ PresenceInvariant,
26
+ ResidueInvariant,
27
+ SectionScopedDomainInvariant,
28
+ SelfBoundedInvariant,
29
+ SiblingScanInvariant,
30
+ UniquenessInvariant,
31
+ } from "./invariants.ts";
32
+ import type { DocKey } from "./project.ts";
33
+ import { Projector } from "./project.ts";
34
+ import { Translator } from "./translate.ts";
35
+
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
+ /** The judgment input — the doc's identity, content and the seam closures. */
40
+ export interface ContractInput {
41
+ /** The doc-type record key of the document under judgment. */
42
+ docKey: DocKey;
43
+ /** The document's file path (message attribution + the doc's own dir). */
44
+ path: string;
45
+ /** The document's raw content. */
46
+ content: string;
47
+ /** The workspace/repo root the doc chain resolves against. */
48
+ root: string;
49
+ /** The dispatch phase id — enables the face-④ phase-registration check. */
50
+ phaseId?: string;
51
+ /** Pre-parsed chain/sibling docs (path → parsed record). */
52
+ chainDocs?: ReadonlyMap<string, ParsedDoc>;
53
+ /** The filesystem seam (defaults to node:fs). */
54
+ fs?: DocFs;
55
+ }
56
+
57
+ /**
58
+ * The contract coordinator — the interpreter's single face. One instance; the
59
+ * strategy set is stateless (each strategy reads its judgment data from the
60
+ * context), so construction is cheap and validates compose safely.
61
+ *
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.
72
+ */
73
+ export class Contract {
74
+ /** The per-doc-key policy sets — the declared composition of the strategy family.
75
+ * All thirteen strategies are registry-driven and judge every doc type, so the
76
+ * per-key sets are the same ordered family; the record keying is what a future
77
+ * per-type ordering/selection change would carry. */
78
+ readonly #strategies: Record<DocKey, readonly Invariant[]>;
79
+ /** The projection carrier — the derived parse/skeleton faces the judgment reads. */
80
+ readonly #projector: Projector;
81
+ /** The row-source translator — the canonicalize seam carrier. One instance over
82
+ * the same locale word table the rest of the plane reads (the recognition face
83
+ * of the P7 translation layer); embedded like the projector, so the production
84
+ * construction points (`new Contract()`) stay argument-free. */
85
+ readonly #translator: Translator;
86
+
87
+ constructor() {
88
+ this.#strategies = Contract.#buildPolicy();
89
+ this.#projector = new Projector(declaredRegistries);
90
+ this.#translator = new Translator(new Words());
91
+ }
92
+
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(input: ContractInput): Finding[] {
97
+ const lines = input.content.split("\n").map((line) => this.#translator.canonicalize(line));
98
+ const parsed = docTypeParsers[input.docKey].parse(lines);
99
+ const context: JudgeContext = {
100
+ docKey: input.docKey,
101
+ parsed,
102
+ lines,
103
+ path: input.path,
104
+ root: input.root,
105
+ slices: this.#projector.slices()[input.docKey],
106
+ shape: this.#projector.shape()[input.docKey],
107
+ registries: declaredRegistries,
108
+ phaseId: input.phaseId,
109
+ chainDocs: input.chainDocs,
110
+ fs: input.fs ?? new NodeFs(),
111
+ };
112
+ const findings: Finding[] = [];
113
+ for (const strategy of this.#strategies[input.docKey]) {
114
+ findings.push(...strategy.evaluate(context));
115
+ }
116
+ return findings;
117
+ }
118
+
119
+ /** The declared strategy composition — one ordered family set per doc key. */
120
+ static #buildPolicy(): Record<DocKey, readonly Invariant[]> {
121
+ const family: readonly Invariant[] = [
122
+ new PresenceInvariant(),
123
+ new UniquenessInvariant(),
124
+ new DomainInvariant(),
125
+ new CrosslinkInvariant(),
126
+ new OrderInvariant(),
127
+ new ContinuityInvariant(),
128
+ new ResidueInvariant(),
129
+ new HollowInvariant(),
130
+ new SelfBoundedInvariant(),
131
+ new FileExistenceInvariant(),
132
+ new SiblingScanInvariant(),
133
+ new CrossDocChainInvariant(),
134
+ new SectionScopedDomainInvariant(),
135
+ ];
136
+ const policy = {} as Record<DocKey, readonly Invariant[]>;
137
+ for (const key of DOC_KEYS) {
138
+ policy[key] = family;
139
+ }
140
+ return policy;
141
+ }
142
+ }
@@ -0,0 +1,275 @@
1
+ // packages/cdd-engine/src-next/contract/lint.ts
2
+ // T5 — the reference lint WARN pass (design spec §2.3): an independent observation
3
+ // face that runs at the dispatch gate, never part of the judgment definition.
4
+ // The reference vocabulary it applies is the derived projection (project.ts —
5
+ // `Projector.reference()`, the per-element reference rows) — zero self-copied
6
+ // reference patterns. The lint consumes the SAME doc.ts parse record the dispatch
7
+ // and the graph read (parse once, reuse everywhere), so its observations are
8
+ // anchored on the parsed task blocks and the chain root, never a re-scan of raw
9
+ // text.
10
+ //
11
+ // The WARN families:
12
+ // · missing-edge suspect (plan) — a backward `Task N` / `T<N>` prose reference
13
+ // inside a task's Objective/Acceptance value that has no matching
14
+ // `- **DependsOn**:` declaration. The graph's edge classes never fire here:
15
+ // unregistered targets (missing-id) and self-edges (self-loop) stay silent —
16
+ // a suspect is always an existing task with a lower id whose edge was simply
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.
22
+ //
23
+ // Every warning is a Warn — a WARN-only observation, never a Finding, never a
24
+ // BLOCK. Module-level exports are types / the class — zero behavior-carrying
25
+ // bare functions (the plan's zero-bare-function discipline).
26
+
27
+ import path from "node:path";
28
+ import { declaredRegistries } from "./declare.ts";
29
+ import type { ChainLink, ParsedDoc, PlanParsed, TaskBlock } from "./doc.ts";
30
+ import { MarkdownPrimitives } from "./doc.ts";
31
+ import type { ReferenceEntry, ReferenceProjection } from "./project.ts";
32
+ import { Projector } from "./project.ts";
33
+
34
+ /** One reference-lint warning — a WARN-only observation, never a judge Finding. */
35
+ export interface Warn {
36
+ /** The doc file the warning refers to. */
37
+ path: string;
38
+ /** The anchored surface the warning anchors to (a `Task N` block or a field name). */
39
+ field: string;
40
+ /** The one-line warning message — what the observation suspects. */
41
+ message: string;
42
+ /** The actionable fix. */
43
+ fix: string;
44
+ /** The lint family that produced the warning. */
45
+ kind: "reference-lint";
46
+ }
47
+
48
+ /** The lint input — the document's path + the shared doc.ts parse instance (the
49
+ * doc type rides the parsed record's docType, never a re-typed key — no field
50
+ * the pass does not read). */
51
+ export interface LintInput {
52
+ /** The document's file path (message attribution). */
53
+ path: string;
54
+ /** The shared parsed record — the same instance the dispatch and the graph read. */
55
+ parsed: ParsedDoc;
56
+ }
57
+
58
+ /**
59
+ * The reference-lint pass — the WARN observation face over the derived reference
60
+ * vocabulary. One instance; every reference pattern it applies is read from the
61
+ * projection, never re-typed. The prose scan surface (Objective / Acceptance) is
62
+ * a scanning-semantics decision, tied to the vocabulary by a construction guard
63
+ * that fails loudly if the plan registry renames either prose field.
64
+ */
65
+ export class LintPass extends MarkdownPrimitives {
66
+ /** The derived reference vocabulary — the single source the lint applies. */
67
+ readonly #reference: ReferenceProjection;
68
+ /** The derived `Task prose reference` token pattern (global — matchAll over prose lines). */
69
+ readonly #proseToken: RegExp;
70
+ /** The derived `DependsOn id` value pattern (whole-token — the declared-edge values). */
71
+ readonly #depIdToken: RegExp;
72
+ /** The prose-owning task fields of the plan — the scanning-semantics surface. */
73
+ readonly #proseFieldKeys: readonly string[] = ["Objective", "Acceptance"];
74
+
75
+ constructor() {
76
+ super();
77
+ this.#reference = new Projector(declaredRegistries).reference();
78
+ const planEntries = this.#reference.plan.entries;
79
+ this.#proseToken = new RegExp(this.#valuePatternOf(planEntries, "Task prose reference"), "g");
80
+ this.#depIdToken = new RegExp(this.#valuePatternOf(planEntries, "DependsOn id"));
81
+ for (const key of this.#proseFieldKeys) {
82
+ this.#valuePatternOf(planEntries, `**${key}**`);
83
+ }
84
+ }
85
+
86
+ /** run — the single observation entry: one Warn per offending surface. */
87
+ run(input: LintInput): Warn[] {
88
+ const warns: Warn[] = [];
89
+ if (input.parsed.docType === "plan") {
90
+ warns.push(...this.#missingEdgeWarns(input, input.parsed));
91
+ warns.push(...this.#numberingAdvisories(input, input.parsed));
92
+ warns.push(...this.#transitiveAdvisories(input, input.parsed));
93
+ }
94
+ warns.push(...this.#crossDocDriftWarns(input, input.parsed.chain.parentLink));
95
+ return warns;
96
+ }
97
+
98
+ // -------------------------------------------------------------------------
99
+ // the missing-edge suspect scan (plan)
100
+ // -------------------------------------------------------------------------
101
+
102
+ /** One WARN per task block whose prose references an existing lower task with no edge. */
103
+ #missingEdgeWarns(input: LintInput, parsed: PlanParsed): Warn[] {
104
+ const warns: Warn[] = [];
105
+ const registered = new Set(parsed.taskBlocks.map((block) => block.id));
106
+ for (const block of parsed.taskBlocks) {
107
+ const declared = this.#declaredEdgesOf(block);
108
+ const suspects = this.#suspectRefsOf(block, declared, registered);
109
+ if (suspects.length === 0) continue;
110
+ const list = suspects.map((id) => `Task ${id}`).join(" and ");
111
+ warns.push({
112
+ path: input.path,
113
+ field: `Task ${block.id}`,
114
+ message: `task ${block.id} prose-references ${list} with no matching **DependsOn** declaration — a suspected missing edge (WARN: the author's intent is authoritative, never a gate)`,
115
+ fix: `declare the edge in the block's **DependsOn** line, or treat the reference as prose (task ${list})`,
116
+ kind: "reference-lint",
117
+ });
118
+ }
119
+ return warns;
120
+ }
121
+
122
+ /** One WARN per forward reference (a dep on a higher-numbered task) — the numbering
123
+ * read-order advisory (T24: legal after the anti-dependency gate retired, but a
124
+ * hint that the numbering no longer follows the topological reading order). */
125
+ #numberingAdvisories(input: LintInput, parsed: PlanParsed): Warn[] {
126
+ const warns: Warn[] = [];
127
+ for (const block of parsed.taskBlocks) {
128
+ for (const dep of this.#declaredEdgesOf(block)) {
129
+ if (dep <= block.id) continue;
130
+ warns.push({
131
+ path: input.path,
132
+ field: `Task ${block.id}`,
133
+ message: `task ${block.id} depends on the higher-numbered Task ${dep} — legal (forward references), but the numbering no longer follows the topological reading order; consider renumbering (advisory only)`,
134
+ fix: "renumber the pair for a linear reading order, or keep the forward dependency — the engine derives waves from **DependsOn** alone",
135
+ kind: "reference-lint",
136
+ });
137
+ }
138
+ }
139
+ return warns;
140
+ }
141
+
142
+ /** One WARN per transitively-redundant declaration (a dep d reachable from another
143
+ * declared dep) — the direct-only advisory: redundant edges are harmless (the
144
+ * waves derive over the closure) but clutter the display, so the engine hints
145
+ * the author to declare direct prerequisites only. */
146
+ #transitiveAdvisories(input: LintInput, parsed: PlanParsed): Warn[] {
147
+ const warns: Warn[] = [];
148
+ const declared = new Map<number, Set<number>>();
149
+ for (const block of parsed.taskBlocks) declared.set(block.id, this.#declaredEdgesOf(block));
150
+ const reachOf = (from: number): Set<number> => {
151
+ const seen = new Set<number>();
152
+ const stack = [...(declared.get(from) ?? [])];
153
+ while (stack.length > 0) {
154
+ const current = stack.pop()!;
155
+ if (seen.has(current)) continue;
156
+ seen.add(current);
157
+ stack.push(...(declared.get(current) ?? []));
158
+ }
159
+ return seen;
160
+ };
161
+ const reach = new Map<number, Set<number>>();
162
+ for (const id of declared.keys()) reach.set(id, reachOf(id));
163
+ for (const block of parsed.taskBlocks) {
164
+ for (const dep of declared.get(block.id) ?? []) {
165
+ const redundantVia = [...(declared.get(block.id) ?? [])].find(
166
+ (other) => other !== dep && (reach.get(other) ?? new Set()).has(dep),
167
+ );
168
+ if (redundantVia === undefined) continue;
169
+ warns.push({
170
+ path: input.path,
171
+ field: `Task ${block.id}`,
172
+ message: `task ${block.id} depends on Task ${dep}, already reachable via declared dependency Task ${redundantVia} — declare direct prerequisites only (advisory: redundant edges are inert for the wave derivation, but clutter the graph)`,
173
+ fix: `drop ${dep} from the block's **DependsOn** (or keep it — the engine reduces the display, the closure is unchanged)`,
174
+ kind: "reference-lint",
175
+ });
176
+ }
177
+ }
178
+ return warns;
179
+ }
180
+
181
+ /** The block's declared edge ids — read from its **DependsOn** VALUE PREFIX only
182
+ * (the first `(`/`(` truncates — a trailing parenthetical's numbers are prose,
183
+ * never an edge; the same §3.8 value-domain contract the graph's extractor keeps). */
184
+ #declaredEdgesOf(block: TaskBlock): Set<number> {
185
+ const edges = new Set<number>();
186
+ const field = block.fields.find((entry) => entry.key === "DependsOn");
187
+ if (field === undefined) return edges;
188
+ for (const line of field.lines) {
189
+ const prefix = line.split(/[((]/)[0]!;
190
+ for (const token of prefix.split(/[,\s]+/)) {
191
+ if (this.#depIdToken.test(token.trim())) edges.add(Number(token.trim()));
192
+ }
193
+ }
194
+ return edges;
195
+ }
196
+
197
+ /** The backward prose references of a block that exist, are undeclared and are not a
198
+ * code-span citation — the missing-edge suspects. */
199
+ #suspectRefsOf(
200
+ block: TaskBlock,
201
+ declared: ReadonlySet<number>,
202
+ registered: ReadonlySet<number>,
203
+ ): number[] {
204
+ const suspects: number[] = [];
205
+ const seenId = new Set<number>();
206
+ for (const field of block.fields) {
207
+ if (!this.#proseFieldKeys.includes(field.key)) continue;
208
+ for (const line of field.lines) {
209
+ const prose = this.#withoutCodeSpans(line);
210
+ for (const match of prose.matchAll(this.#proseToken)) {
211
+ const id = Number(match[1]);
212
+ if (id >= block.id) continue; // forward / self — undeclareable, never a suspect
213
+ if (!registered.has(id)) continue; // missing-id — the graph's class, never a suspect
214
+ if (declared.has(id) || seenId.has(id)) continue;
215
+ seenId.add(id);
216
+ suspects.push(id);
217
+ }
218
+ }
219
+ }
220
+ return suspects.sort((a, b) => a - b);
221
+ }
222
+
223
+ /** The line with its backtick-delimited inline code spans removed (a span cites a symbol, never prose). */
224
+ #withoutCodeSpans(line: string): string {
225
+ return line.replace(/`+[^`\n]*`+/g, "");
226
+ }
227
+
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
+ // -------------------------------------------------------------------------
263
+ // construction helpers
264
+ // -------------------------------------------------------------------------
265
+
266
+ /** The value pattern of a registered reference entry — a lookup that fails
267
+ * loudly when the declaration renames an anchor the lint consumes. */
268
+ #valuePatternOf(entries: readonly ReferenceEntry[], anchor: string): string {
269
+ const entry = entries.find((row) => row.anchor === anchor);
270
+ if (entry === undefined) {
271
+ throw new Error(`reference-lint requires the registered reference entry "${anchor}"`);
272
+ }
273
+ return entry.valuePattern ?? "";
274
+ }
275
+ }