@oscaner-skills/cdd-engine 3.0.1 → 4.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.
@@ -30,10 +30,20 @@
30
30
  //
31
31
  // Module-level exports are types / the declared word data / the class — zero
32
32
  // behavior-carrying bare functions (the plan's zero-bare-function discipline).
33
+ import { DOC_TYPE_VALUES } from "../contract/declare.js";
33
34
  /** The capsule word rows — every word the capsule face emits, one table. */
34
35
  export const CAPSULE_WORDS = {
35
- /** The capsule emit keys in order (a reorder is a red test — the pinned face). */
36
- keys: ["status", "blocker", "handoff"],
36
+ /** The capsule emit key rows — one declaration per status class (the summary
37
+ * face's key-set single source; a reorder is a red test — the pinned face).
38
+ * A success status renders `status · blocker · handoff`; a failure status renders
39
+ * `status` alone, plus `handoff` only when the round wrote a crash record. */
40
+ keys: {
41
+ success: ["status", "blocker", "handoff"],
42
+ failure: ["status"],
43
+ handoff: "handoff",
44
+ },
45
+ /** The failure status vocabulary — the reduced summary-key class (TIMEOUT / BLOCKED). */
46
+ failureStatuses: ["BLOCKED", "TIMEOUT"],
37
47
  /** The `·`-separator token of the capsule line. */
38
48
  separator: " · ",
39
49
  /** The status vocabulary — the five handoff-conclusion values. */
@@ -51,7 +61,11 @@ export const CAPSULE_WORDS = {
51
61
  review: "review",
52
62
  fix: "fix",
53
63
  implement: "implement",
54
- docType: "the doc declares no `doc-type:` key — add `doc-type: <overall-spec|phase-spec|single-spec|plan>` to the doc's front-matter (spec §12 · D34) and re-run",
64
+ docType: "the doc declares no `doc-type:` key — add `doc-type: <overall|phase-spec|single-spec|plan>` to the doc's front-matter (spec §12 · D34) and re-run",
65
+ docTypeValue: "the doc declares `doc-type: {value}`, which is outside the declared domain — use one of {domain} and re-run",
66
+ slugMissing: "the doc declares no `slug:` key — add `slug: <workspace-key>` to the doc's front-matter (the identity key the board and every work command share) and re-run",
67
+ slugInvalid: 'the doc\'s `slug:` value "{slug}" is illegal — use 1–128 characters, an alphanumeric first character, then alphanumerics, `.`, `_`, or `-` (the slug is the workspace directory name), then re-run',
68
+ slugDuplicated: 'the slug "{slug}" is declared by more than one document — keep exactly one identity document and at most one plan per slug, then re-run',
55
69
  frontmatterParse: "the doc's front-matter is not valid YAML: {reason} on line {line}, column {column} (`{source}`) — quote values that start with `[` or `{` (a YAML flow-sequence start) and re-run",
56
70
  },
57
71
  /** The wave-gate BLOCK wording rows (v1.21) — the highest-arity pre-flight refusal
@@ -59,14 +73,22 @@ export const CAPSULE_WORDS = {
59
73
  waveGate: {
60
74
  split: "the requested wave ({requested}) splits/mismatches the derived wave ({open}) — dispatch the full derived wave",
61
75
  wrongPhase: "the open wave is at {phase} — run cdd {phase} first",
76
+ mixedBatch: "the derived batch ({batch}) mixes closed and open tasks ({closed} closed, {open} open) — a wave closes as a unit; re-declare the **DependsOn** edges so no task joins an already-executed batch",
62
77
  },
63
78
  /** The pre-flight BLOCK wording rows (P4.1 T1) — the seam's refusal vocabulary,
64
79
  * single-sourced (the seam fills the {count} slot, never a re-type). */
65
80
  preflight: {
66
- dirtyTree: "the working tree is dirty — commit or discard your changes, then re-run the same command",
81
+ dirtyTree: "the working tree is dirty — commit or discard your changes (recovery is the orchestrator's job; the engine only refuses — it never stashes, makes a temporary commit, or resumes a dirty tree), then re-run the same command",
67
82
  graph: "the plan graph has {count} edge violation(s) — fix the **DependsOn** edges first",
68
83
  docContract: "the target document fails the doc-contract — fix its structural findings first",
69
84
  },
85
+ /** The terminated-review promotion warning — the one CDD_WARN wording row the
86
+ * lifecycle emits when a terminated review round's valid findings draft is
87
+ * promoted. The braces are fill slots ({cause} / {idleMs} / {verdict} / {count}). */
88
+ promotionWarning: "terminated review round promoted from its handoff draft — cause: {cause}, idleMs: {idleMs}, last sample verdict: {verdict}, findings recovered: {count}",
89
+ /** The terminated-round diagnostic suffix — appended to the one CDD_BLOCKED reason
90
+ * line of a non-promoted terminated round. Fill slots: {idleMs} / {verdict}. */
91
+ terminationDetail: " — idleMs: {idleMs}, last sample verdict: {verdict}",
70
92
  };
71
93
  /** The guard-ban vocabulary — the STALE / GATE / shape ban rows the guards assert
72
94
  * absent from the live faces (the single-source ban table; the guard scan releases
@@ -153,10 +175,16 @@ export class Words {
153
175
  // -------------------------------------------------------------------------
154
176
  // capsule — the station-word family
155
177
  // -------------------------------------------------------------------------
156
- /** The capsule emit keys in order — status · blocker · handoff (the pinned byte
157
- * order the capsule renders by). */
158
- capsuleKeys() {
159
- return CAPSULE_WORDS.keys;
178
+ /** The capsule emit keys of one status class, in the pinned byte order — the key
179
+ * set's single source. A success status renders `status · blocker · handoff`; a
180
+ * failure status (TIMEOUT / BLOCKED) renders `status`, plus `handoff` only when
181
+ * the round wrote a crash record (`withHandoff`). */
182
+ capsuleKeys(status, withHandoff) {
183
+ const rows = CAPSULE_WORDS.keys;
184
+ const failure = CAPSULE_WORDS.failureStatuses.includes(status);
185
+ if (!failure)
186
+ return rows.success;
187
+ return withHandoff ? [...rows.failure, rows.handoff] : rows.failure;
160
188
  }
161
189
  /** The `·`-separator token of the capsule line. */
162
190
  capsuleSeparator() {
@@ -174,6 +202,27 @@ export class Words {
174
202
  routeWord(kind) {
175
203
  return CAPSULE_WORDS.routeWords[kind];
176
204
  }
205
+ /** The out-of-domain `doc-type:` wording — the declared value named, the
206
+ * allowed domain interpolated from the ONE `DOC_TYPE_VALUES` declaration
207
+ * (never a second hand-written list). */
208
+ docTypeValueWord(value) {
209
+ return this.routeWord("docTypeValue")
210
+ .replace("{value}", value)
211
+ .replace("{domain}", DOC_TYPE_VALUES.join(", "));
212
+ }
213
+ /** The identity-gate refusal wording for one refused slug verdict — the ONE
214
+ * spelling the pre-flight gate and the dispatch carrier print (the row and its
215
+ * `{slug}` fill are owned here, never re-typed at a carrier). */
216
+ slugRefusal(verdict) {
217
+ switch (verdict.kind) {
218
+ case "missing":
219
+ return this.routeWord("slugMissing");
220
+ case "illegal":
221
+ return this.routeWord("slugInvalid").replace("{slug}", verdict.slug);
222
+ case "duplicated":
223
+ return this.routeWord("slugDuplicated").replace("{slug}", verdict.slug);
224
+ }
225
+ }
177
226
  /** The wave-gate BLOCK wording rows — the vocabulary the WaveGate verdicts render
178
227
  * (single source: the gate fills the placeholders from these rows, never re-types). */
179
228
  waveGateWords() {
@@ -184,6 +233,22 @@ export class Words {
184
233
  preflightWords() {
185
234
  return CAPSULE_WORDS.preflight;
186
235
  }
236
+ /** The terminated-review promotion warning, rendered from the termination facts —
237
+ * the single source of both the wording row and its slot names. */
238
+ promotionWarning(facts) {
239
+ return CAPSULE_WORDS.promotionWarning
240
+ .replace("{cause}", facts.cause)
241
+ .replace("{idleMs}", String(facts.idleMs))
242
+ .replace("{verdict}", facts.verdict)
243
+ .replace("{count}", String(facts.count));
244
+ }
245
+ /** The terminated-round diagnostic suffix, rendered from the termination facts —
246
+ * idle time plus the last sample's verdict (`none` when no sample was taken). */
247
+ terminationDetail(facts) {
248
+ return CAPSULE_WORDS.terminationDetail
249
+ .replace("{idleMs}", String(facts.idleMs))
250
+ .replace("{verdict}", facts.verdict);
251
+ }
187
252
  // -------------------------------------------------------------------------
188
253
  // locale — the word-table locale face (the langs projection + the label rows)
189
254
  // -------------------------------------------------------------------------
@@ -14,6 +14,7 @@
14
14
  /** The doc-tree root segments — the ONE value of the doc-root fact (the runtime's
15
15
  * `docRoots` and every derived literal read THIS constant). */
16
16
  export const ENGINE_DOC_ROOTS = {
17
+ overalls: "docs/kairos/overalls",
17
18
  specs: "docs/kairos/specs",
18
19
  plans: "docs/kairos/plans",
19
20
  };
@@ -14,8 +14,8 @@
14
14
  // The JSON plane's dead fields are not carried (the delete-dead-empties iron rule):
15
15
  // · failureCategories — the new tree keeps no failure-category counter data; the
16
16
  // ledger's progress key set is the declared code constant (PROGRESS_COUNTER_ZERO).
17
- // · handoffNamespace.slugRule — the slug derivation is code (Workspace.slugFromDoc),
18
- // never a prose data field.
17
+ // · handoffNamespace.slugRule — the workspace key is the document's declared
18
+ // `slug:` (judged by the identity index), never a prose data field.
19
19
  // · contextContract channels.git / derived / transport / timeouts and the env-host
20
20
  // channel — no live consumer; the host-marker closure is single-sourced by the
21
21
  // harness detect rows (face/host.ts), never re-declared here.
@@ -28,47 +28,38 @@ import { ENGINE_DOC_ROOTS } from "./doc-roots.js";
28
28
  * keyed by `op.type` (implement.wave / review.wave / … — the ledger's single
29
29
  * naming truth, verbatim from the engine-config handoff namespace). The v1.9
30
30
  * reparametrization: `returnFormat` is gone (RETURN_PROSE is the one return
31
- * contract) and the `schema` faces are the handoff-schema selector (work / findings —
32
- * §3.6, session/handoff-schema.ts). */
31
+ * contract) and each family is a pure name row — the carrier plane derives from the
32
+ * op, never from this table (`planeOf`, session plane). */
33
33
  export const HANDOFF_FAMILIES = {
34
34
  "implement.wave": {
35
35
  name: "tasks-{tasks}-implement.json",
36
- schema: "work",
37
36
  },
38
37
  "review.wave": {
39
38
  name: "tasks-{tasks}-review-{round}.json",
40
- schema: "findings",
41
39
  },
42
40
  "fix.wave": {
43
41
  name: "tasks-{tasks}-fix-{round}.json",
44
- schema: "work",
45
42
  },
46
43
  "review.spec": {
47
44
  name: "spec-review-{round}.json",
48
- schema: "findings",
49
45
  },
50
46
  "fix.spec": {
51
47
  name: "spec-fix-{round}.json",
52
- schema: "findings",
53
48
  },
54
49
  "review.plan": {
55
50
  name: "plan-review-{round}.json",
56
- schema: "findings",
57
51
  },
58
52
  "fix.plan": {
59
53
  name: "plan-fix-{round}.json",
60
- schema: "findings",
61
54
  },
62
55
  "review.branch": {
63
56
  // find #9 (spec §6.5): the range token leaves the file name — the workspace
64
57
  // slug is the plan-slug (the fix face carries --plan) · round accumulates
65
58
  // across re-reviews (lineKey pins "branch").
66
59
  name: "branch-review-{round}.json",
67
- schema: "findings",
68
60
  },
69
61
  "fix.branch": {
70
62
  name: "branch-fix-{round}.json",
71
- schema: "work",
72
63
  },
73
64
  };
74
65
  /** The engine runtime — the typed engine-config surface, one constant (the argv
@@ -0,0 +1,325 @@
1
+ // packages/cdd-engine/src-next/infra/slug-index.ts
2
+ // The identity index (spec §2.1/§2.2): ONE scan over the doc roots
3
+ // (`ENGINE_RUNTIME.docRoots`) groups every document by its front-matter facts.
4
+ // The index is the single judgment surface for document identity:
5
+ // · lookups — `identityDoc` / `planOf` / `phaseSpecsOf` / `overallOf` / `entryAt`;
6
+ // · violations — duplicate identity document · duplicate plan · missing `slug:` ·
7
+ // illegal `slug:` value · `program:` target with no overall document.
8
+ // Identity is the `slug:` value, never the file name; a document's class is its
9
+ // declared `doc-type:`, never the directory it happens to live in. Both the board
10
+ // and the dispatch pre-flight read THIS judgment — zero second implementation.
11
+ //
12
+ // One directory listing per doc root (`#entryNames`) plus one content read per
13
+ // candidate (`#readDoc`) — the ONE document predicate both scan legs share: a
14
+ // `*.md` name whose content reads is a document, whatever produced the name list.
15
+ // Zero filename derivation, zero `existsSync` path guessing.
16
+ // Module-level exports are types / the class — zero behavior-carrying bare
17
+ // functions (the plan's zero-bare-function discipline).
18
+ import { readdirSync, readFileSync, statSync } from "node:fs";
19
+ import path from "node:path";
20
+ import { SLUG_VALUE_PATTERN } from "../contract/declare.js";
21
+ import { FrontMatterExtractor } from "../contract/frontmatter.js";
22
+ import { DOC_KEYS } from "../contract/project.js";
23
+ import { ENGINE_RUNTIME } from "./runtime.js";
24
+ /**
25
+ * SlugIndex — the identity index over the doc roots. Construct it through
26
+ * `build` (the one scanning entry point); every lookup and the violation list
27
+ * read the single materialized scan.
28
+ */
29
+ export class SlugIndex {
30
+ /** The legal `slug:` value form (spec §2.1): 1–128 characters, an alphanumeric
31
+ * first character, then alphanumerics / `.` / `_` / `-`. The slug doubles as a
32
+ * workspace directory name, so path separators and whitespace are rejected at
33
+ * the value surface. Compiled from the registry declaration's own source string
34
+ * (`SLUG_VALUE_PATTERN`) — one grammar, zero second spelling. */
35
+ static #SLUG_PATTERN = new RegExp(SLUG_VALUE_PATTERN);
36
+ /** Whether a raw `slug:` value is a legal identity value (spec §2.1) — the ONE
37
+ * spelling of the value judgment the board marker, the dispatch carrier and the
38
+ * pre-flight gate all read. Narrows a nullable raw value to a legal slug. */
39
+ static isLegalSlug(value) {
40
+ return value !== null && SlugIndex.#SLUG_PATTERN.test(value);
41
+ }
42
+ /** Whether a repo-relative path lies inside any doc root — pure path
43
+ * grammar, zero document reads. The board's not-found face uses this (plus an
44
+ * existence probe) to refuse an outside-root or absent path BEFORE the identity
45
+ * scan opens a single document (spec §3.1). */
46
+ static insideDocRoots(rel) {
47
+ const normalized = path.normalize(rel);
48
+ return Object.values(ENGINE_RUNTIME.docRoots).some((root) => {
49
+ const prefix = path.normalize(root);
50
+ return normalized === prefix || normalized.startsWith(`${prefix}${path.sep}`);
51
+ });
52
+ }
53
+ /** Every indexed document, ordered by repo-relative path. */
54
+ entries;
55
+ /** The rel → entry lookup. */
56
+ #byRel;
57
+ /** The valid-slug → entries lookup (an illegal value never groups). */
58
+ #bySlug;
59
+ /** The materialized judgment over this scan. */
60
+ #violations;
61
+ constructor(entries) {
62
+ this.entries = entries;
63
+ const byRel = new Map();
64
+ const bySlug = new Map();
65
+ for (const entry of entries) {
66
+ byRel.set(entry.rel, entry);
67
+ if (!SlugIndex.isLegalSlug(entry.slug))
68
+ continue;
69
+ const group = bySlug.get(entry.slug);
70
+ if (group === undefined)
71
+ bySlug.set(entry.slug, [entry]);
72
+ else
73
+ group.push(entry);
74
+ }
75
+ this.#byRel = byRel;
76
+ this.#bySlug = bySlug;
77
+ this.#violations = SlugIndex.#judge(entries, bySlug);
78
+ }
79
+ /** Scan every doc root once and index every `.md` document under them. The
80
+ * optional `fs` is the caller's scan seam (the judgment plane's in-memory
81
+ * `DocFs`); absent, the node:fs scan is the production default. */
82
+ static build(repoRoot, fs) {
83
+ const entries = [
84
+ ...SlugIndex.#scanRoot(repoRoot, ENGINE_RUNTIME.docRoots.overalls, fs),
85
+ ...SlugIndex.#scanRoot(repoRoot, ENGINE_RUNTIME.docRoots.specs, fs),
86
+ ...SlugIndex.#scanRoot(repoRoot, ENGINE_RUNTIME.docRoots.plans, fs),
87
+ ].sort((a, b) => (a.rel < b.rel ? -1 : a.rel > b.rel ? 1 : 0));
88
+ return new SlugIndex(entries);
89
+ }
90
+ /** The entry at one repo-root-relative path, or null when the path is not indexed. */
91
+ entryAt(rel) {
92
+ return this.#byRel.get(rel) ?? null;
93
+ }
94
+ /** The identity document (overall / phase-spec / single-spec) carrying the
95
+ * slug, or null when no identity document does. */
96
+ identityDoc(slug) {
97
+ for (const entry of this.#bySlug.get(slug) ?? []) {
98
+ if (SlugIndex.#isIdentity(entry))
99
+ return entry;
100
+ }
101
+ return null;
102
+ }
103
+ /** The plan document carrying the slug, or null when no plan does. */
104
+ planOf(slug) {
105
+ for (const entry of this.#bySlug.get(slug) ?? []) {
106
+ if (entry.docType === "plan")
107
+ return entry;
108
+ }
109
+ return null;
110
+ }
111
+ /** The phase-spec documents whose `program:` names the program slug, in program
112
+ * order: the slugs' `-p<major>[.<minor>…]` tail numerically (p2 before p10,
113
+ * `p4.1` after `p4`), then the slugs without that tail in rel order. */
114
+ phaseSpecsOf(programSlug) {
115
+ return this.entries
116
+ .filter((entry) => entry.docType === "phase-spec" && entry.program === programSlug)
117
+ .sort(SlugIndex.#phaseCompare);
118
+ }
119
+ /** The overall document carrying the program slug, or null. */
120
+ overallOf(programSlug) {
121
+ for (const entry of this.#bySlug.get(programSlug) ?? []) {
122
+ if (entry.docType === "overall")
123
+ return entry;
124
+ }
125
+ return null;
126
+ }
127
+ /** The materialized violation list (deterministic over the rel-ordered scan). */
128
+ violations() {
129
+ return this.#violations;
130
+ }
131
+ /** The duplicate roles the slug carries in this scan — empty when the slug is
132
+ * unique, `identity` when a second identity document declares it, `plan` when a
133
+ * second plan does (spec §2.1's uniqueness rule). The ONE duplicate judgment the
134
+ * board's row marker, the dispatch carrier and the pre-flight gate share. */
135
+ duplicatedRolesOf(slug) {
136
+ const roles = [];
137
+ for (const violation of this.#violations) {
138
+ if (violation.slug !== slug)
139
+ continue;
140
+ const role = violation.kind === "duplicate-identity"
141
+ ? "identity"
142
+ : violation.kind === "duplicate-plan"
143
+ ? "plan"
144
+ : null;
145
+ if (role !== null && !roles.includes(role))
146
+ roles.push(role);
147
+ }
148
+ return roles;
149
+ }
150
+ /** The identity gate for one document's declared `slug:` — the ONE four-way
151
+ * judgment the dispatch pre-flight and the dispatch carrier share (spec §2.1):
152
+ * present · legal · indexed · unique. The `entryAt` guard keeps a content read
153
+ * the scan did not re-index from judging a stale value. */
154
+ slugVerdict(rel, slug) {
155
+ if (slug === null)
156
+ return { kind: "missing" };
157
+ if (!SlugIndex.isLegalSlug(slug))
158
+ return { kind: "illegal", slug };
159
+ const entry = this.entryAt(rel);
160
+ const duplicated = entry !== null && entry.slug === slug && this.duplicatedRolesOf(slug).length > 0;
161
+ return duplicated ? { kind: "duplicated", slug } : { kind: "accepted", slug };
162
+ }
163
+ /** The phase ordinal a slug carries in its `-p<major>[.<minor>…]` tail — the
164
+ * numeric segments in order, or null when the slug carries no such tail. The
165
+ * segment is read off the IDENTITY value (never the file name). */
166
+ static #phaseOrdinal(slug) {
167
+ if (slug === null)
168
+ return null;
169
+ const match = /-p(\d+(?:\.\d+)*)$/.exec(slug);
170
+ return match === null ? null : match[1].split(".").map(Number);
171
+ }
172
+ /** Program order for phase rows: numbered slugs numerically (p2 before p10,
173
+ * `p4.1` after `p4`), then the unnumbered ones; rel path is the final tie-break
174
+ * so the order stays deterministic over one scan. */
175
+ static #phaseCompare(left, right) {
176
+ const leftOrdinal = SlugIndex.#phaseOrdinal(left.slug);
177
+ const rightOrdinal = SlugIndex.#phaseOrdinal(right.slug);
178
+ if (leftOrdinal !== null && rightOrdinal !== null) {
179
+ const width = Math.max(leftOrdinal.length, rightOrdinal.length);
180
+ for (let index = 0; index < width; index++) {
181
+ const delta = (leftOrdinal[index] ?? 0) - (rightOrdinal[index] ?? 0);
182
+ if (delta !== 0)
183
+ return delta;
184
+ }
185
+ }
186
+ else if (leftOrdinal !== null) {
187
+ return -1;
188
+ }
189
+ else if (rightOrdinal !== null) {
190
+ return 1;
191
+ }
192
+ return left.rel < right.rel ? -1 : left.rel > right.rel ? 1 : 0;
193
+ }
194
+ /** Scan one doc root — the names come from `#entryNames`, the document judgment
195
+ * from the shared `#readDoc` predicate (a `*.md` name whose content reads). An
196
+ * unreadable candidate is not a document. */
197
+ static #scanRoot(repoRoot, root, fs) {
198
+ const entries = [];
199
+ for (const name of SlugIndex.#entryNames(path.join(repoRoot, root), fs)) {
200
+ if (!name.endsWith(".md"))
201
+ continue;
202
+ const rel = path.join(root, name);
203
+ const abs = path.join(repoRoot, rel);
204
+ const content = SlugIndex.#readDoc(abs, fs);
205
+ if (content === null)
206
+ continue;
207
+ const { head } = FrontMatterExtractor.split(content);
208
+ entries.push({
209
+ path: abs,
210
+ rel,
211
+ docType: SlugIndex.#docTypeOf(head.docType),
212
+ slug: head.slug,
213
+ program: head.program,
214
+ version: head.version,
215
+ status: head.status,
216
+ title: head.title,
217
+ });
218
+ }
219
+ return entries;
220
+ }
221
+ /** The entry names of one doc root — the ONE `readdirSync` call site (the
222
+ * injected seam's `list` otherwise). Names only: the document judgment is
223
+ * `#readDoc`'s, so both legs classify the same set (a symlinked document is a
224
+ * document, a directory named `*.md` is not). A missing root lists nothing
225
+ * (ENOENT only); a permission or shape failure of an existing root is a real
226
+ * break — both legs rethrow it rather than index an empty root. */
227
+ static #entryNames(root, fs) {
228
+ if (fs !== undefined)
229
+ return fs.list(root);
230
+ try {
231
+ return readdirSync(root);
232
+ }
233
+ catch (err) {
234
+ if (err.code === "ENOENT")
235
+ return [];
236
+ throw err;
237
+ }
238
+ }
239
+ /** One candidate's content, or null when it is not a readable regular file —
240
+ * the ONE document predicate (read-through = document). The node:fs leg owns the
241
+ * regular-file guard here (a directory, device or broken symlink named `*.md`
242
+ * never reads); the injected leg's `read` answers the same question for its own
243
+ * store. */
244
+ static #readDoc(abs, fs) {
245
+ if (fs !== undefined)
246
+ return fs.read(abs);
247
+ try {
248
+ return statSync(abs).isFile() ? readFileSync(abs, "utf8") : null;
249
+ }
250
+ catch {
251
+ return null;
252
+ }
253
+ }
254
+ /** Narrow a raw `doc-type:` value to the declared domain (the ONE `DOC_KEYS`
255
+ * declaration) — anything else reads null. */
256
+ static #docTypeOf(raw) {
257
+ if (raw === null)
258
+ return null;
259
+ return DOC_KEYS.includes(raw) ? raw : null;
260
+ }
261
+ /** An identity document is any declared spec class — every key except `plan`. */
262
+ static #isIdentity(entry) {
263
+ return entry.docType !== null && entry.docType !== "plan";
264
+ }
265
+ /** Materialize the five violation classes over the scan and its slug groups. */
266
+ static #judge(entries, bySlug) {
267
+ const violations = [];
268
+ for (const entry of entries) {
269
+ if (entry.slug === null) {
270
+ violations.push({
271
+ kind: "missing-slug",
272
+ rel: entry.rel,
273
+ slug: null,
274
+ program: entry.program,
275
+ });
276
+ }
277
+ else if (!SlugIndex.isLegalSlug(entry.slug)) {
278
+ violations.push({
279
+ kind: "invalid-slug",
280
+ rel: entry.rel,
281
+ slug: entry.slug,
282
+ program: entry.program,
283
+ });
284
+ }
285
+ }
286
+ for (const [slug, group] of bySlug) {
287
+ const identities = group.filter((entry) => SlugIndex.#isIdentity(entry));
288
+ for (const duplicate of identities.slice(1)) {
289
+ violations.push({
290
+ kind: "duplicate-identity",
291
+ rel: duplicate.rel,
292
+ slug,
293
+ program: duplicate.program,
294
+ });
295
+ }
296
+ const plans = group.filter((entry) => entry.docType === "plan");
297
+ for (const duplicate of plans.slice(1)) {
298
+ violations.push({
299
+ kind: "duplicate-plan",
300
+ rel: duplicate.rel,
301
+ slug,
302
+ program: duplicate.program,
303
+ });
304
+ }
305
+ }
306
+ const overallSlugs = new Set();
307
+ for (const entry of entries) {
308
+ if (entry.docType === "overall" && entry.slug !== null)
309
+ overallSlugs.add(entry.slug);
310
+ }
311
+ for (const entry of entries) {
312
+ if (entry.docType !== "phase-spec" || entry.program === null)
313
+ continue;
314
+ if (overallSlugs.has(entry.program))
315
+ continue;
316
+ violations.push({
317
+ kind: "missing-program-target",
318
+ rel: entry.rel,
319
+ slug: entry.slug,
320
+ program: entry.program,
321
+ });
322
+ }
323
+ return violations;
324
+ }
325
+ }
@@ -10,28 +10,13 @@
10
10
  // the sub-agent-authored draft face (jsonc-parser + trailing-comma/comment
11
11
  // tolerance — a child-LLM slip never voids a round, a real break still reports
12
12
  // malformed; D39), resolve() is the
13
- // child-path single fact, slugFromDoc is the doc-file → slug derivation
14
- // (`-design`/`-plan` suffix strip), docsOfSlug is the slug → doc-tree reverse
15
- // derivation (the board's file-system-only truth, phase-suffix parse included).
13
+ // child-path single fact. Document identity is NOT derived here: the workspace
14
+ // key is the document's declared `slug:`, judged by the ONE identity index
15
+ // (infra/slug-index.ts).
16
16
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
17
17
  import path from "node:path";
18
18
  import { parse } from "jsonc-parser";
19
19
  import { RepoRoot } from "./root.js";
20
- import { ENGINE_RUNTIME } from "./runtime.js";
21
- /** The slug phase-suffix syntax — the trailing `-p<major>(.<minor>)*` segment
22
- * (spec §3.2 ⑬). This is the ONE source of the phase-suffix grammar: both the
23
- * suffix parse (`Workspace.phaseSuffixOf`, the `-p…$` form) and the board's
24
- * suffix-only match (`BoardView.scanPhases`, the `^p…$` form) compose their
25
- * patterns from this fragment. (Distinct from the doc-contract design-unit value
26
- * syntax `P\d+(\.\d+)*-design` — uppercase + `-design` tail — which is another
27
- * fact, never merged here.) */
28
- export const PHASE_SUFFIX_CORE = "p\\d+(?:\\.\\d+)*";
29
- /** The phase-suffix parse — the trailing `-p<major>(.<minor>)*` segment captured
30
- * as the named `suffix` group (composed from PHASE_SUFFIX_CORE: the ONE grammar). */
31
- const PHASE_SUFFIX_TAIL = new RegExp(`(?<program>.+?)(?<suffix>-${PHASE_SUFFIX_CORE})$`);
32
- /** The suffix-only match — a bare `<major>(.<minor>)*` phase path (composed from
33
- * the SAME PHASE_SUFFIX_CORE; the board's scan uses this form). */
34
- export const PHASE_SUFFIX_BARE = new RegExp(`^${PHASE_SUFFIX_CORE}$`);
35
20
  /** The persisted path-field keys — the JSON fields whose value is a PATH (the
36
21
  * progress.json `reviewedRevision.doc` / `.plan` layers · the base.json `plan`
37
22
  * field). The read-time normalization (P9 T4 §2.11) relativizes exactly these
@@ -87,64 +72,6 @@ export class Workspace {
87
72
  this.slug = slug;
88
73
  this.path = path.join(root.path, slug);
89
74
  }
90
- /** The doc-file → slug derivation: strip `.md`, then one trailing `-design` or
91
- * `-plan` suffix (anchored, mutually exclusive — spec and plan converge). */
92
- static slugFromDoc(doc) {
93
- const base = path.basename(doc).replace(/\.md$/, "");
94
- return base.replace(/-(?:design|plan)$/, "");
95
- }
96
- /** The slug's phase-suffix parse — the trailing `-p<major>(.<minor>)*` segment
97
- * (null when the slug is a program slug, i.e. carries no phase suffix). The
98
- * grammar is PHASE_SUFFIX_TAIL, composed from the shared PHASE_SUFFIX_CORE. */
99
- static phaseSuffixOf(slug) {
100
- const match = PHASE_SUFFIX_TAIL.exec(slug);
101
- return match?.groups?.suffix ?? null;
102
- }
103
- /** The slug → doc-tree reverse derivation: from a program or phase slug, derive
104
- * the artifact paths the doc tree should carry, judged by `existsSync` (the
105
- * file system is the only truth — an absent file is null, never synthesized).
106
- * A phase slug's overall anchors at the nearest existing `<ancestor>-overall.md`
107
- * walking up the dotted phase path (`-p7.1` → `-p7` → program root) — no
108
- * overall-declared table is parsed (the Phase inventory is stale-prone). */
109
- static docsOfSlug(slug, repoRoot) {
110
- const specs = path.join(repoRoot, ENGINE_RUNTIME.docRoots.specs);
111
- const plans = path.join(repoRoot, ENGINE_RUNTIME.docRoots.plans);
112
- const suffix = Workspace.phaseSuffixOf(slug);
113
- if (suffix === null) {
114
- const overall = path.join(specs, `${slug}-overall.md`);
115
- return {
116
- overall: existsSync(overall) ? overall : null,
117
- spec: null,
118
- plan: null,
119
- phaseSuffix: null,
120
- };
121
- }
122
- const overall = Workspace.#nearestOverall(specs, slug, suffix);
123
- const spec = path.join(specs, `${slug}-design.md`);
124
- const plan = path.join(plans, `${slug}.md`);
125
- return {
126
- overall,
127
- spec: existsSync(spec) ? spec : null,
128
- plan: existsSync(plan) ? plan : null,
129
- phaseSuffix: suffix,
130
- };
131
- }
132
- /** The nearest existing overall anchor walking up the dotted phase path: for a
133
- * deep suffix (`-p7.1`) the candidates are `<program>-p7`, then the program
134
- * root; for a single-segment suffix the program root only. Null when no
135
- * candidate's overall file exists — nothing synthesized. */
136
- static #nearestOverall(specs, slug, suffix) {
137
- const stem = slug.slice(0, slug.length - suffix.length);
138
- const segments = suffix.slice(2).split(".");
139
- for (let keep = segments.length - 1; keep >= 0; keep--) {
140
- const candidate = keep === 0
141
- ? path.join(specs, `${stem}-overall.md`)
142
- : path.join(specs, `${stem}-p${segments.slice(0, keep).join(".")}-overall.md`);
143
- if (existsSync(candidate))
144
- return candidate;
145
- }
146
- return null;
147
- }
148
75
  /** Idempotently create the workspace directory. */
149
76
  ensure() {
150
77
  this.root.ensure();