@oscaner-skills/cdd-engine 4.12.0 → 4.14.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.
@@ -0,0 +1,645 @@
1
+ // packages/cdd-engine/src-next/session/round-artifacts.ts
2
+ // P36 T1 — the artifact matrix: WHO owns an artifact name (the identity domain) ×
3
+ // WHICH file belongs to that identity (the artifact kind). One closed registration
4
+ // table answers both directions of the naming fact:
5
+ //
6
+ // · `render(identity, kind)` — the ONE name rule of a rendered row (the engine
7
+ // mints the name from an identity, never from another name);
8
+ // · `attribute(name)` — the reverse: which identity + kind one on-disk name belongs
9
+ // to, or `null` for a name no row renders (an unknown name is an OBSERVATION, not
10
+ // a refusal).
11
+ //
12
+ // Registered domains — three, each ONE class owning its rows; the registry is their
13
+ // aggregate, and a domain the matrix never registered answers loudly rather than
14
+ // inventing a name:
15
+ // · the ROUND domain — draft / final / report / log / crash / evidence / the
16
+ // orchestrator's rulings sidecar (every row rendered from a round coordinate);
17
+ // · the WORKSPACE domain — `progress` · `base` · `in-flight` (the three
18
+ // coordinate-less literals) and `brief`, the one workspace kind carrying a
19
+ // coordinate;
20
+ // · the DOC domain — the four DECLARED rows (`overall` · `phase-spec` ·
21
+ // `single-spec` · `plan`), identity from the front-matter `slug:` and no `render`
22
+ // at all. Its `read` is where a slug naming ≥2 documents of one declared type is
23
+ // judged: `invalid(found)` with every path listed, never a first pick.
24
+ //
25
+ // Three facts this file is the single home of:
26
+ // · the workspace name SPELLINGS (`progress.json` · `base.json` · `in-flight.json` ·
27
+ // `tasks-{tasks}-brief.md`) — every read face asks the matrix for the answer
28
+ // instead of spelling a literal, so a moved name is one edit and a second spelling
29
+ // cannot be smuggled back in;
30
+ // · the matrix's construction (the composition root's command preamble) — zero
31
+ // module-level default instance, so "every read face holds the SAME instance" is a
32
+ // wiring fact rather than a hope;
33
+ // · the matrix's own scope — a row table is naming and policy KNOWLEDGE, so it binds
34
+ // no directory. The workspace a name resolves inside is a read-time coordinate
35
+ // (`locate(identity, kind, base)`): one board renders several node workspaces, and
36
+ // an instance bound to one of them would resolve another node's names against this
37
+ // node's directory — a legal-looking name that belongs to a different coordinate,
38
+ // which is the very defect this matrix exists to retire.
39
+ //
40
+ // Module-level exports are types / the registry and its domain — zero behavior-carrying
41
+ // bare functions.
42
+ import { accessSync, constants, statSync } from "node:fs";
43
+ import { basename } from "node:path";
44
+ import { DOC_KEYS } from "../contract/project.js";
45
+ import { SlugIndex } from "../infra/slug-index.js";
46
+ import { targetFaces } from "./faces.js";
47
+ /** One artifact's presence read — the ONE existence/readability judgment every
48
+ * rendered domain delegates to. Existence and readability are two questions:
49
+ * `stat` answers the first even when the file cannot be opened, so the arm asks the
50
+ * second explicitly (a file that is there but unreadable is `invalid`, never
51
+ * `absent`, §4.5). */
52
+ const readArtifactAt = (path) => {
53
+ try {
54
+ if (!statSync(path).isFile())
55
+ return { kind: "invalid", path, reason: "not a regular file" };
56
+ accessSync(path, constants.R_OK);
57
+ return { kind: "ok", path };
58
+ }
59
+ catch (raw) {
60
+ if (raw.code === "ENOENT")
61
+ return { kind: "absent" };
62
+ return { kind: "invalid", path, reason: "unreadable" };
63
+ }
64
+ };
65
+ /** The identity key of one round identity — the coordinate with the renderer's two
66
+ * defaults applied (a missing cycle renders as no segment; a missing attempt renders
67
+ * as attempt 1). Two identities with the same key render the same names, so the
68
+ * attribution set of one (identity, kind) is well defined.
69
+ *
70
+ * The two defaults are NOT symmetric, and the asymmetry is the point: a missing
71
+ * `attempt` is attempt 1 (the renderer never mints `-a1`, so attempt 1 and an absent
72
+ * attempt ARE one identity), while a missing `cycle` is its own coordinate (it renders
73
+ * no cycle segment at all, so `tasks-1-implement.json` and `tasks-1-implement-1.json`
74
+ * are two identities — spec §2.2 keeps the cycle-less spelling a legal value). Every
75
+ * identity comparison reads through this ONE key, never a private re-derivation. */
76
+ export const roundIdentityKey = (identity) => `${identity.line}\u0000${identity.op}\u0000${identity.cycle ?? ""}\u0000${identity.attempt ?? 1}`;
77
+ /** The workspace identity key — `tasks` is the whole coordinate. */
78
+ const workspaceIdentityKey = (identity) => identity.tasks ?? "";
79
+ /** A candidate that attributes into ANOTHER domain never compares equal to this
80
+ * domain's key — the ONE spelling of "not my identity", shared by both domains. */
81
+ const FOREIGN_KEY = "\u0000foreign";
82
+ /** The round domain's identity key for one attributed name. */
83
+ const roundKeyOf = (candidate) => candidate.identity.domain === "round" ? roundIdentityKey(candidate.identity) : FOREIGN_KEY;
84
+ /** The workspace domain's identity key for one attributed name. */
85
+ const workspaceKeyOf = (candidate) => candidate.identity.domain === "workspace"
86
+ ? workspaceIdentityKey(candidate.identity)
87
+ : FOREIGN_KEY;
88
+ /**
89
+ * The ONE read of a rendered row (spec §2.3 · §2.5) — the SET-based judgment, not a
90
+ * count:
91
+ *
92
+ * · `found` = every name in `base` that attributes to this (identity, kind);
93
+ * · `found` with any name other than the rendered one ⇒ `misplaced(derived, found)`
94
+ * — the rendered name is the only legal spelling, and a same-identity variant
95
+ * beside it is a name the engine did not mint (never a first pick between them);
96
+ * · `found` exactly the rendered name ⇒ the presence read (`ok` / `invalid`);
97
+ * · `found` empty ⇒ the presence read at the rendered path, whose answer is the
98
+ * honest one: `absent` when nothing is there, `invalid` when something is (a
99
+ * directory named like the artifact is not "missing").
100
+ *
101
+ * The two-name case is the largest instance of the rule, never its definition: a stem
102
+ * variant alone (the derived name never landed) is the same `misplaced` answer, which
103
+ * is why a count-based predicate could not answer it.
104
+ */
105
+ const readRendered = (request) => {
106
+ const { identity, kind, base, derived, attribute, keyOf } = request;
107
+ const key = keyOf({ identity, kind });
108
+ const found = base.names().filter((name) => {
109
+ const attributed = attribute(name);
110
+ return attributed !== null && attributed.kind === kind && keyOf(attributed) === key;
111
+ });
112
+ if (found.length === 0)
113
+ return readArtifactAt(base.resolve(derived));
114
+ if (found.some((name) => name !== derived))
115
+ return { kind: "misplaced", derived, found, identity };
116
+ return readArtifactAt(base.resolve(derived));
117
+ };
118
+ // ---------------------------------------------------------------------------
119
+ // the round domain — the seven rows a round identity renders
120
+ // ---------------------------------------------------------------------------
121
+ /** Every round kind, in the matrix's row order. */
122
+ const ROUND_KINDS = [
123
+ "draft",
124
+ "final",
125
+ "report",
126
+ "log",
127
+ "crash",
128
+ "evidence",
129
+ "rulings",
130
+ ];
131
+ /** The round LINE words — every target-type word renders a round line except `wave`,
132
+ * whose line word is the `tasks-<group>` spine instead. */
133
+ const ROUND_LINE_WORDS = Object.keys(targetFaces).filter((word) => word !== "wave");
134
+ /** The wave line's spine — the task group rides it. */
135
+ const WAVE_LINE = "tasks-";
136
+ /** The ops a non-wave line word can carry: `implement` belongs to the wave family
137
+ * alone, so a branch/doc line never mints it. */
138
+ const LINE_OPS = "review|fix";
139
+ /** One line-word stem — the line, the op, the optional cycle and the optional
140
+ * attempt. Both spellings of the round grammar are parsed back by ONE pair of
141
+ * patterns. */
142
+ const WAVE_STEM = new RegExp(`^(${WAVE_LINE}.+?)-(implement|${LINE_OPS})(?:-(\\d+))?(?:-a(\\d+))?$`);
143
+ const DOC_STEM = new RegExp(`^(${ROUND_LINE_WORDS.join("|")})-(${LINE_OPS})(?:-(\\d+))?(?:-a(\\d+))?$`);
144
+ /** The final/rulings cycle tag — `.c<cycle>`, the segment that closes a cycle. */
145
+ const CYCLE_TAG = /^(.*)\.c(\d+)$/;
146
+ /** The round suffixes whose kind the tail alone decides. */
147
+ const ROUND_SUFFIXES = [
148
+ { suffix: ".rulings.json", kind: "rulings" },
149
+ { suffix: "-test-evidence.json", kind: "evidence" },
150
+ { suffix: "-report.md", kind: "report" },
151
+ { suffix: ".log", kind: "log" },
152
+ ];
153
+ /** The round stem of one identity — `line-op[-cycle][-a<n>]`, the shared body every
154
+ * kind hangs its own prefix/suffix on. A cycle-less identity omits the cycle segment
155
+ * (never a `-undefined` token); the first attempt omits the `-a` segment. */
156
+ const roundStem = (identity) => {
157
+ const { cycle, attempt } = identity;
158
+ const cycleSegment = cycle === undefined || cycle === "" ? "" : `-${cycle}`;
159
+ const attemptSegment = attempt === undefined || attempt <= 1 ? "" : `-a${attempt}`;
160
+ return `${identity.line}-${identity.op}${cycleSegment}${attemptSegment}`;
161
+ };
162
+ /** The round name rule — the ONE rendered name of one round identity, for every
163
+ * round kind. The `rulings` sidecar shares the `final`'s stem deliberately: it is an
164
+ * attachment OF the reviewed carrier's round, so the spelling of the carrier the
165
+ * orchestrator handed in (`draft` or `final`) can no longer move it. */
166
+ export const renderRound = (identity, kind) => {
167
+ if (identity.domain !== "round")
168
+ throw new Error(`the round matrix renders no ${identity.domain} identity`);
169
+ if (!isRoundKind(kind))
170
+ throw new Error(`the matrix holds no round row for ${kind}`);
171
+ const stem = roundStem(identity);
172
+ const closing = identity.cycle === undefined || identity.cycle === "" ? "" : `.c${identity.cycle}`;
173
+ switch (kind) {
174
+ case "draft":
175
+ return `${stem}.json`;
176
+ case "final":
177
+ return `${stem}${closing}.json`;
178
+ case "report":
179
+ return `${stem}-report.md`;
180
+ case "log":
181
+ return `${stem}.log`;
182
+ case "crash":
183
+ return `crash-${stem}.json`;
184
+ case "evidence":
185
+ return `${stem}-test-evidence.json`;
186
+ case "rulings":
187
+ return `${stem}${closing}.rulings.json`;
188
+ }
189
+ };
190
+ /** Whether a kind belongs to the round domain's registered set. */
191
+ const isRoundKind = (kind) => ROUND_KINDS.includes(kind);
192
+ /** Split one on-disk round name into its kind and body — `null` for a name whose
193
+ * tail no round kind renders. */
194
+ const splitRoundName = (name) => {
195
+ if (name.startsWith("crash-") && name.endsWith(".json")) {
196
+ return { kind: "crash", body: name.slice("crash-".length, -".json".length) };
197
+ }
198
+ for (const { suffix, kind: tailKind } of ROUND_SUFFIXES) {
199
+ if (!name.endsWith(suffix))
200
+ continue;
201
+ const rest = name.slice(0, -suffix.length);
202
+ if (tailKind !== "rulings")
203
+ return { kind: tailKind, body: rest };
204
+ const tag = CYCLE_TAG.exec(rest);
205
+ return tag === null
206
+ ? { kind: tailKind, body: rest }
207
+ : { kind: tailKind, body: tag[1], cycleTag: Number(tag[2]) };
208
+ }
209
+ if (!name.endsWith(".json"))
210
+ return null;
211
+ const rest = name.slice(0, -".json".length);
212
+ const tag = CYCLE_TAG.exec(rest);
213
+ if (tag === null)
214
+ return { kind: "draft", body: rest };
215
+ return { kind: "final", body: tag[1], cycleTag: Number(tag[2]) };
216
+ };
217
+ /** Parse a round stem back into its identity — `null` when the body is no line word
218
+ * this matrix renders. */
219
+ const roundIdentityOfStem = (body) => {
220
+ const match = WAVE_STEM.exec(body) ?? DOC_STEM.exec(body);
221
+ if (match === null)
222
+ return null;
223
+ const [, line, op, cycle, attempt] = match;
224
+ return {
225
+ domain: "round",
226
+ line: line,
227
+ op: op,
228
+ ...(cycle === undefined ? {} : { cycle: Number(cycle) }),
229
+ ...(attempt === undefined ? {} : { attempt: Number(attempt) }),
230
+ };
231
+ };
232
+ /** The NAME → identity reverse port of the round domain: the render-name parse. It
233
+ * answers `null` for a name no round line renders, and the SAME `(identity, kind)`
234
+ * for every spelling that still attributes — an explicit `-a1`, a `rulings` name
235
+ * written without its `.c<cycle>` tag. No third state: the `misplaced` judgment needs
236
+ * the read-time workspace and belongs to `read`. */
237
+ const attributeRound = (name) => {
238
+ const parts = splitRoundName(name);
239
+ if (parts === null)
240
+ return null;
241
+ const identity = roundIdentityOfStem(parts.body);
242
+ if (identity === null)
243
+ return null;
244
+ if (parts.cycleTag !== undefined) {
245
+ // A `.c<cycle>` tag is the `final`/`rulings` face of a CYCLE-BEARING identity: the
246
+ // tag and the stem's own cycle must agree, or the name belongs to no identity.
247
+ if (identity.cycle === undefined || Number(identity.cycle) !== parts.cycleTag)
248
+ return null;
249
+ }
250
+ return { identity, kind: parts.kind };
251
+ };
252
+ /** The identifier vocabulary the `rulings` row declares — the ONE declaration site of
253
+ * "the same identifier is spelled differently in two adjacent artifacts". */
254
+ const RULINGS_IDENTIFIER = {
255
+ canonical: "finding",
256
+ accepts: ["finding", "id"],
257
+ };
258
+ /** The `rulings` row's policy — absence is legal: a ruling not yet recorded is not a
259
+ * defect (the read face stays silent; nothing is invented in its place). */
260
+ const RULINGS_POLICY = "absence is legal — a ruling not yet recorded is not a defect";
261
+ /** One round row. `sealed` is written out on every row (the matrix leaves no blank for
262
+ * an implementation to invent a default); the carrier pair is the engine's sealed set,
263
+ * and the sidecar is the orchestrator's — hence its own author, identifier and
264
+ * absence policy. */
265
+ const roundRow = (kind) => ({
266
+ domain: "round",
267
+ author: kind === "rulings" ? "orchestrator" : "engine",
268
+ sealed: kind === "draft" || kind === "final",
269
+ identityFrom: "rendered",
270
+ render: renderRound,
271
+ misplaced: "block",
272
+ ...(kind === "rulings" ? { identifier: RULINGS_IDENTIFIER, policy: RULINGS_POLICY } : {}),
273
+ });
274
+ /** The seven round rows, in row order. */
275
+ const ROUND_ENTRIES = ROUND_KINDS.map((kind) => ({
276
+ kind,
277
+ row: roundRow(kind),
278
+ }));
279
+ /**
280
+ * RoundDomain — the round identity domain: one (line, op, cycle, attempt) renders the
281
+ * carrier pair, the round's report / log / crash / evidence files and the
282
+ * orchestrator's rulings sidecar. Stateless: the workspace a path resolves inside
283
+ * arrives with each `locate` / `read` call, so one instance serves every node a board
284
+ * renders.
285
+ */
286
+ export class RoundDomain {
287
+ domain = "round";
288
+ kinds() {
289
+ return ROUND_KINDS;
290
+ }
291
+ entries() {
292
+ return ROUND_ENTRIES;
293
+ }
294
+ attribute(name) {
295
+ return attributeRound(name);
296
+ }
297
+ locate(identity, kind, base) {
298
+ return base.resolve(renderRound(identity, kind));
299
+ }
300
+ read(identity, kind, base) {
301
+ return readRendered({
302
+ identity,
303
+ kind,
304
+ base,
305
+ derived: renderRound(identity, kind),
306
+ attribute: attributeRound,
307
+ keyOf: roundKeyOf,
308
+ });
309
+ }
310
+ }
311
+ /** Every doc kind — the declaration root's OWN tuple (`DOC_KEYS`), never a second
312
+ * runtime copy: a value added there can not silently skip a row here. */
313
+ const DOC_KINDS = DOC_KEYS;
314
+ /** Whether a kind belongs to the doc domain's declared set. */
315
+ const isDocKind = (kind) => DOC_KINDS.includes(kind);
316
+ /** The four declared rows — human-authored documents, never sealed, no `misplaced`
317
+ * (there is no rendered name to sit beside). */
318
+ const DOC_ENTRIES = DOC_KINDS.map((kind) => ({
319
+ kind,
320
+ row: { domain: "doc", author: "human", sealed: false, identityFrom: "declared" },
321
+ }));
322
+ /** One indexed document's DECLARED identity — `null` when the document declares no
323
+ * legal `slug:` or no declared `doc-type:`. The file name plays no part. */
324
+ const docIdentityOf = (entry) => {
325
+ if (entry.docType === null || !SlugIndex.isLegalSlug(entry.slug))
326
+ return null;
327
+ return { domain: "doc", slug: entry.slug, docType: entry.docType };
328
+ };
329
+ /**
330
+ * DocDomain — the declared identity domain: the four document rows, answered entirely
331
+ * by the command's ONE identity index. `attribute` maps a repo-relative path to the
332
+ * document's declared identity, never to a filename-derived one; `locate` / `read`
333
+ * answer on the index entry's `rel` — the declared row's own home, and the basis every
334
+ * doc consumer compares paths on. The domain never renders a name (documents name
335
+ * themselves), so it holds no `render` and no orphan-by-name rule.
336
+ */
337
+ export class DocDomain {
338
+ domain = "doc";
339
+ #index;
340
+ constructor(index) {
341
+ this.#index = index;
342
+ }
343
+ kinds() {
344
+ return DOC_KINDS;
345
+ }
346
+ entries() {
347
+ return DOC_ENTRIES;
348
+ }
349
+ attribute(name) {
350
+ const entry = this.#index.entryAt(name);
351
+ if (entry === null)
352
+ return null;
353
+ const identity = docIdentityOf(entry);
354
+ return identity === null ? null : { identity, kind: identity.docType };
355
+ }
356
+ /** The sole matching document's path — `null` when the slug names none of the kind
357
+ * or names two of them. The path is the index entry's `rel` (its declared home on
358
+ * the ONE repo-root-relative basis every consumer compares on), never a rendered
359
+ * name and never the syscall form. */
360
+ locate(identity, kind, _base) {
361
+ const doc = this.#identityOf(identity, kind);
362
+ const found = this.#documentsOf(doc);
363
+ return found.length === 1 ? found[0].rel : null;
364
+ }
365
+ /** One read of the declared document — the ambiguity judgment's ONE home (spec §4.4):
366
+ * a slug naming two documents of the same declared type is `invalid(found)` and both
367
+ * paths are printed; the read never selects one. The `path` is the index entry's
368
+ * `rel`, the same basis `locate` answers on. */
369
+ read(identity, kind, _base) {
370
+ const doc = this.#identityOf(identity, kind);
371
+ const found = this.#documentsOf(doc);
372
+ if (found.length > 1) {
373
+ return {
374
+ kind: "invalid",
375
+ path: found[0].rel,
376
+ found: found.map((entry) => entry.rel),
377
+ reason: "duplicate-identity",
378
+ };
379
+ }
380
+ const only = found[0];
381
+ if (only === undefined)
382
+ return { kind: "absent" };
383
+ // The existence probe takes the syscall form; the ANSWER speaks the declared
384
+ // home, so a doc read and a doc locate never name one document two ways.
385
+ const at = readArtifactAt(only.path);
386
+ if (at.kind === "invalid")
387
+ return { ...at, path: only.rel };
388
+ return at.kind === "ok" ? { kind: "ok", path: only.rel } : at;
389
+ }
390
+ /** The documents declaring this slug at this declared type — 0, 1 or n. The set is
391
+ * the whole judgment: no arm of the doc domain ever picks a first document. */
392
+ #documentsOf(doc) {
393
+ return this.#index.docsOf(doc.slug).filter((entry) => entry.docType === doc.docType);
394
+ }
395
+ /** The doc identity narrowed to this row — a foreign domain or a kind the identity
396
+ * does not declare is a caller bug (loud, as `render` is). */
397
+ #identityOf(identity, kind) {
398
+ if (identity.domain !== "doc")
399
+ throw new Error(`the doc matrix reads no ${identity.domain} identity`);
400
+ if (!isDocKind(kind) || kind !== identity.docType)
401
+ throw new Error(`the doc matrix holds no ${kind} row for a ${identity.docType} identity`);
402
+ return identity;
403
+ }
404
+ }
405
+ // ---------------------------------------------------------------------------
406
+ // the workspace domain — the four workspace rows
407
+ // ---------------------------------------------------------------------------
408
+ /** The workspace kinds in the matrix's own row order. */
409
+ const WORKSPACE_KINDS = ["progress", "base", "in-flight", "brief"];
410
+ /** The three coordinate-less workspace names — the literals the conservation boundary
411
+ * pins byte for byte. */
412
+ const WORKSPACE_LITERALS = {
413
+ progress: "progress.json",
414
+ base: "base.json",
415
+ "in-flight": "in-flight.json",
416
+ };
417
+ /** The ONE workspace name rule — every rendered workspace row and every read face's
418
+ * literal ask delegate here. The coordinate is part of the identity, so an identity
419
+ * the kind does not carry is refused rather than rendered into a plausible-looking
420
+ * wrong name: the three literals take `tasks: null`, the brief a non-empty group. */
421
+ const workspaceName = (kind, tasks) => {
422
+ if (kind === "brief") {
423
+ if (tasks === null || tasks === "")
424
+ throw new Error("the brief's name needs a non-empty tasks coordinate");
425
+ return `tasks-${tasks}-brief.md`;
426
+ }
427
+ if (tasks !== null)
428
+ throw new Error(`the ${kind} artifact carries no tasks coordinate`);
429
+ return WORKSPACE_LITERALS[kind];
430
+ };
431
+ /** A workspace row's render — the domain is the row's own, so a foreign identity is a
432
+ * caller bug and answers loudly rather than rendering a plausible wrong name. */
433
+ const renderWorkspace = (identity, kind) => {
434
+ if (identity.domain !== "workspace")
435
+ throw new Error(`the workspace matrix renders no ${identity.domain} identity`);
436
+ if (!isWorkspaceKind(kind))
437
+ throw new Error(`the matrix holds no workspace row for ${kind}`);
438
+ return workspaceName(kind, identity.tasks);
439
+ };
440
+ /** Whether a kind belongs to the workspace domain's registered set. */
441
+ const isWorkspaceKind = (kind) => WORKSPACE_KINDS.includes(kind);
442
+ /** The brief's reverse pattern — `tasks-{tasks}-brief.md`, the ONE place the template
443
+ * is parsed back into its coordinate. */
444
+ const BRIEF_NAME = /^tasks-(.+)-brief\.md$/;
445
+ /** The four workspace rows — `sealed` is written out on every row (the matrix leaves no
446
+ * blank for an implementation to invent a default), and no row carries a `policy`:
447
+ * absence is a read fact, never a row rule — the workspace literals have no
448
+ * absence-charged face. */
449
+ const ENTRIES = WORKSPACE_KINDS.map((kind) => ({
450
+ kind,
451
+ row: {
452
+ domain: "workspace",
453
+ author: "engine",
454
+ sealed: false,
455
+ identityFrom: "rendered",
456
+ render: renderWorkspace,
457
+ misplaced: "block",
458
+ },
459
+ }));
460
+ /**
461
+ * WorkspaceDomain — the workspace identity domain: four engine-authored files whose
462
+ * names carry no round coordinate. `tasks: null` addresses the three literal names;
463
+ * the brief's own coordinate addresses it. The domain is stateless: the workspace a
464
+ * path resolves inside arrives with each `locate` / `read` call.
465
+ */
466
+ export class WorkspaceDomain {
467
+ domain = "workspace";
468
+ kinds() {
469
+ return WORKSPACE_KINDS;
470
+ }
471
+ entries() {
472
+ return ENTRIES;
473
+ }
474
+ attribute(name) {
475
+ for (const kind of WORKSPACE_KINDS) {
476
+ const literal = kind === "brief" ? null : WORKSPACE_LITERALS[kind];
477
+ if (literal !== name)
478
+ continue;
479
+ return { identity: { domain: "workspace", tasks: null }, kind };
480
+ }
481
+ const tasks = BRIEF_NAME.exec(name)?.[1] ?? null;
482
+ if (tasks === null || tasks === "")
483
+ return null;
484
+ return { identity: { domain: "workspace", tasks }, kind: "brief" };
485
+ }
486
+ locate(identity, kind, base) {
487
+ return base.resolve(renderWorkspace(identity, kind));
488
+ }
489
+ read(identity, kind, base) {
490
+ return readRendered({
491
+ identity,
492
+ kind,
493
+ base,
494
+ derived: renderWorkspace(identity, kind),
495
+ attribute: (name) => this.attribute(name),
496
+ keyOf: workspaceKeyOf,
497
+ });
498
+ }
499
+ }
500
+ // ---------------------------------------------------------------------------
501
+ // the registry — the matrix's public port
502
+ // ---------------------------------------------------------------------------
503
+ /** The default domain set — the registry's construction input and the module-level
504
+ * vocabulary read's scan surface, so the two entry forms answer over ONE table. */
505
+ const DEFAULT_DOMAINS = [new RoundDomain(), new WorkspaceDomain()];
506
+ /**
507
+ * ArtifactRegistry — the matrix as one object: the closed row table plus the two
508
+ * ports over it (`render` · `attribute`) and the read face. The instance is built ONCE
509
+ * per invocation by the composition root and handed down; a face that mints its own
510
+ * has already left the single source. It holds no directory: the same instance serves
511
+ * every workspace one command observes. The DECLARED domain is the one row set whose
512
+ * answers need an index, so it is bound onto this SAME instance once the command's
513
+ * index exists (`bindDocIndex`) — never built into a second registry.
514
+ */
515
+ export class ArtifactRegistry {
516
+ /** The registered domains, in registration order. Replaced only by `bindDocIndex`,
517
+ * which swaps the declared domain in place so every face holding this instance
518
+ * (the base face, the ledgers, the lifecycle, the board) keeps asking ONE table. */
519
+ #domains;
520
+ constructor(domains = DEFAULT_DOMAINS) {
521
+ this.#domains = domains;
522
+ }
523
+ /** One row's declared identifier vocabulary, WITHOUT an instance — the module-level
524
+ * entry for the read faces that hold no registry (a sidecar schema's acceptance set
525
+ * is a naming fact, not a directory fact). It reads the SAME domain instances the
526
+ * constructor's default does, so the declaration has one home and no caller can grow
527
+ * a second acceptance set. */
528
+ static identifierOf(kind) {
529
+ for (const domain of DEFAULT_DOMAINS) {
530
+ const entry = domain.entries().find((candidate) => candidate.kind === kind);
531
+ if (entry !== undefined)
532
+ return entry.row.identifier ?? null;
533
+ }
534
+ return null;
535
+ }
536
+ /** Whether one FILE NAME is a name this matrix owns — the product vocabulary's ONE
537
+ * answer, WITHOUT an instance (the pin gate's "not a coordinate" exclusion reads it:
538
+ * an artifact name is vocabulary, never a path a reader can follow). It answers from
539
+ * the same domain instances the constructor's default does, so no caller grows a
540
+ * second naming table. */
541
+ static ownsName(name) {
542
+ if (name === "")
543
+ return false;
544
+ return DEFAULT_DOMAINS.some((domain) => domain.attribute(name) !== null);
545
+ }
546
+ /** The workspace name rule WITHOUT an instance — the module-level entry to the SAME
547
+ * render the workspace rows carry (`renderWorkspace`), for the read faces that hold
548
+ * a workspace-relative name and no registry (a static constant, the naming face).
549
+ * One spelling, two entry forms: the pin `nameOf(kind, tasks)` equals
550
+ * `render({domain: "workspace", tasks}, kind)` holds by construction. Restricted to
551
+ * the workspace kinds — a round name needs a round identity. */
552
+ static nameOf(kind, tasks) {
553
+ return renderWorkspace({ domain: "workspace", tasks }, kind);
554
+ }
555
+ /** Every registered entry (`kind` ↔ row), in registration order. */
556
+ entries() {
557
+ return this.#domains.flatMap((domain) => domain.entries());
558
+ }
559
+ /** Bind this command's identity index to the DECLARED domain — the ONE doc-domain
560
+ * construction point, and it edits THIS instance rather than replacing it. The
561
+ * binding is idempotent: a command that resolves its root twice swaps one declared
562
+ * domain for the one over the newer index, and every face already holding the
563
+ * registry sees the new answers (an injected registry included, so a hermetic
564
+ * caller's instance answers doc reads exactly as the preamble's does). */
565
+ bindDocIndex(index) {
566
+ this.#domains = [
567
+ ...this.#domains.filter((domain) => domain.domain !== "doc"),
568
+ new DocDomain(index),
569
+ ];
570
+ }
571
+ /** Every registered row, in registration order. */
572
+ rows() {
573
+ return this.entries().map((entry) => entry.row);
574
+ }
575
+ /** The row one kind registers — `null` for a kind no domain registered yet. */
576
+ rowOf(kind) {
577
+ return this.entries().find((entry) => entry.kind === kind)?.row ?? null;
578
+ }
579
+ /** The name rule of one (identity, kind) — the rendered row's `render`. A declared
580
+ * row (no name rule) and an unregistered kind have no rendered name: both answer
581
+ * loudly rather than inventing one. */
582
+ render(identity, kind) {
583
+ const row = this.rowOf(kind);
584
+ if (row === null)
585
+ throw new Error(`the matrix holds no row for ${kind}`);
586
+ if (row.identityFrom !== "rendered")
587
+ throw new Error(`the ${kind} row has no name rule`);
588
+ return row.render(identity, kind);
589
+ }
590
+ /** The name → identity reverse port — the first domain that recognizes the name. */
591
+ attribute(name) {
592
+ for (const domain of this.#domains) {
593
+ const attributed = domain.attribute(name);
594
+ if (attributed !== null)
595
+ return attributed;
596
+ }
597
+ return null;
598
+ }
599
+ /** The REVIEWED round's identity for one carrier name — the ONE source of every
600
+ * name derived from a `--reviews` carrier (spec §2.1: `rulings` coordinates are the
601
+ * reviewed round's, `op` fixed to `review`). The caller hands the carrier's own
602
+ * spelling; the identity comes from `attribute(basename(carrier))` with the carrier's
603
+ * `cycle` / `attempt`, so a draft spelling and a final spelling of one round answer
604
+ * ONE identity. `null` = the matrix cannot place the name (a legacy spelling, a
605
+ * foreign file) — the caller then derives no name at all rather than guessing one.
606
+ *
607
+ * Two read faces ask this question — the sidecar read seam
608
+ * (`session/artifact-reads.ts`) and the router's readback value
609
+ * (`session/next.ts`) — and both call THIS entry, so the `op: "review"` construction
610
+ * has one production home (the door pins it). */
611
+ reviewedIdentityOf(name) {
612
+ if (name === "")
613
+ return null;
614
+ const attributed = this.attribute(basename(name));
615
+ if (attributed === null || attributed.identity.domain !== "round")
616
+ return null;
617
+ const { line, cycle, attempt } = attributed.identity;
618
+ return {
619
+ domain: "round",
620
+ line,
621
+ op: "review",
622
+ ...(cycle === undefined ? {} : { cycle }),
623
+ ...(attempt === undefined ? {} : { attempt }),
624
+ };
625
+ }
626
+ /** Where one (identity, kind) sits inside `base` — dispatched by the identity's own
627
+ * domain. The base is the caller's workspace, never the registry's: a board reads
628
+ * several node workspaces through ONE matrix. */
629
+ locate(identity, kind, base) {
630
+ return this.#domainOf(identity).locate(identity, kind, base);
631
+ }
632
+ /** One read of one (identity, kind) inside `base` — the same domain dispatch, one
633
+ * judgment. */
634
+ read(identity, kind, base) {
635
+ return this.#domainOf(identity).read(identity, kind, base);
636
+ }
637
+ /** The domain that owns an identity — a domain the matrix never registered is a
638
+ * caller bug (its task has not landed), so it answers loudly. */
639
+ #domainOf(identity) {
640
+ const domain = this.#domains.find((candidate) => candidate.domain === identity.domain);
641
+ if (domain === undefined)
642
+ throw new Error(`the matrix holds no ${identity.domain} domain`);
643
+ return domain;
644
+ }
645
+ }