@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.
@@ -48,6 +48,7 @@
48
48
  //
49
49
  // Module-level exports are types / the declared constant data / the class — zero
50
50
  // behavior-carrying bare functions (the plan's zero-bare-function discipline).
51
+ import { CRITERIA, LENS_QUESTIONS } from "../contract/review-criteria.js";
51
52
  import { DISPATCH } from "../face/host.js";
52
53
  import { TerminationPolicy } from "../face/termination.js";
53
54
  /** The nominal fixed-frame cells shared by every shell (byte-identical words — the
@@ -110,6 +111,11 @@ const IMPLEMENT_SHELL = [
110
111
  ...LICENSE_ITEMS,
111
112
  ...SCHEMA_SECTION,
112
113
  ];
114
+ /** The fix face's ONE rulings reading instruction (spec §2.10) — the fixed prefix
115
+ * names where the orchestrator's rulings live and what they outrank; the SIDECAR PATH
116
+ * itself rides the round context (`INPUT_RULINGS`), never this sentence. Both fix
117
+ * shells carry the same words: one reading, one meaning. */
118
+ const RULINGS_READING = "**Rulings:** read the orchestrator's ruling file named by `INPUT_RULINGS` before touching a finding — each ruling answers one finding id and overrides that finding's own suggestion (`REJECTED` = do not adopt that finding's fix); the carrier itself is read-only, never rewritten.";
113
119
  /** The fix row's fixed prefix — header + instructions + the shared work tail. */
114
120
  const FIX_TYPED_INSTRUCTIONS = [
115
121
  "**Verify-then-apply:** verify each finding against the codebase's actual state before changing anything — apply a finding only when it is technically sound; a finding that does not hold up stays open with a note (never blind adoption). Apply findings one at a time and test each one before moving on.",
@@ -124,8 +130,9 @@ const FIX_SHELL = [
124
130
  ...FRAME_ITEMS,
125
131
  WORK_CAPABILITY,
126
132
  ...FIX_TYPED_INSTRUCTIONS,
127
- "**fix:** read `INPUT_REVIEWS` (open findings) + the plan context (`INPUT_WAVE_BRIEF` on a wave line — the complete plan mirror; `INPUT_PLAN` on the branch line — the plan document; `INPUT_SPEC` on the branch line — the design spec, a conformance reference, never the judged document). Fix ALL findings (blocker/warn/nit), verifying against `INPUT_REVIEWS` none remain open. Fix + write the draft at `OUTPUT_HANDOFF` per `## Handoff schema` in one process; draft write failure → `status: BLOCKED`; retry = full re-run (idempotent).",
133
+ "**fix:** read `INPUT_REVIEWS` (open findings) + the plan context (`INPUT_WAVE_BRIEF` on a wave line — the complete plan mirror; `INPUT_PLAN` on the branch line — the plan document; `INPUT_SPEC` on the wave and branch lines — the design spec, a conformance reference, never the judged document; `INPUT_OVERALL` on those two lines — that spec's parent charter, a conformance reference too). Fix ALL findings (blocker/warn/nit), verifying against `INPUT_REVIEWS` none remain open. Fix + write the draft at `OUTPUT_HANDOFF` per `## Handoff schema` in one process; draft write failure → `status: BLOCKED`; retry = full re-run (idempotent).",
128
134
  '**Dispositions:** every requested finding needs a disposition keyed by its `id` exactly as the requesting carrier prints it (`F1`, `F2`, … — the summary is description only), valued `{ "status": "fixed" | "rejected", "reason"?: "…" }` — a missing or mis-keyed disposition fails the round.',
135
+ RULINGS_READING,
129
136
  EVIDENCE_ITEM,
130
137
  ...LICENSE_ITEMS,
131
138
  // T5 (v0.3) — The work plane's ONE strict-schema sentence: every top-level draft
@@ -152,6 +159,7 @@ const DOCS_FIX_SHELL = [
152
159
  "**Table cells:** never hard-wrap a table cell — a wrapped continuation parses as a row whose cell count disagrees with the header, and the lineage row it was meant to be stops registering.",
153
160
  "**Escaped pipes:** a `## Change history` summary cell that needs a literal vertical bar carries `\\|` — a bare `|` splits the cell in two and the row stops matching the declared header.",
154
161
  '**Dispositions:** every requested finding needs a disposition keyed by its `id` exactly as the requesting carrier prints it (`F1`, `F2`, … — the summary is description only), valued `{ "status": "fixed" | "rejected", "reason"?: "…" }` — a missing or mis-keyed disposition fails the round.',
162
+ RULINGS_READING,
155
163
  ...LICENSE_ITEMS,
156
164
  // The generic strict-schema sentence — the SAME one the work shells carry: the
157
165
  // injected declaration is the draft's single field source, zero per-mode field
@@ -257,11 +265,21 @@ export const SEVERITY_RUBRIC_SLOTS = {
257
265
  artifact: "{artifact}",
258
266
  audience: "{audience}",
259
267
  };
268
+ /** The rubric's opening calibration line — a stance, not criteria prose: the tier
269
+ * boundaries themselves come from the criteria registry below. */
270
+ const RUBRIC_PREAMBLE = "Calibrate findings by real severity — not everything is a blocker.";
271
+ /** The calibration tail — the same-grade consistency duty, the vision
272
+ * (silence-is-not-permission) sentence with its two slots, the set-aside ledger and
273
+ * the closing acknowledgement. It shares the fragment with every review axes guide,
274
+ * and it is NOT a second copy of the tier criteria: those are rows in
275
+ * `contract/review-criteria.ts`. */
276
+ const CALIBRATION_TAIL = "Within one run, a defect already graded in the same class keeps that grade; crossing grades names its reason in the finding. The reviewed {artifact} is a vision, not an exhaustive enumeration — behavior it is silent on is judged by what a reasonable {audience} would expect; its silence is not permission, and a finding's severity grades that expectation, not whether the text mentions the trigger. Before your verdict, list every behavior you considered and set aside as outside the reviewed scope — one line each with the reason; nothing set aside is dropped silently; an empty list means you set nothing aside. Acknowledge what was done well before listing findings (accurate praise earns the rest of the report trust).";
260
277
  /** The severity rubric — the ONE calibration fragment every review axes guide
261
- * shares: the four blocker questions, the warn/nit tiers, the same-grade
262
- * consistency duty, the vision (silence-is-not-permission) sentence with its two
263
- * slots, the set-aside ledger and the closing acknowledgement. */
264
- export const SEVERITY_RUBRIC = "Calibrate findings by real severity — not everything is a blocker. A finding is a blocker when any one of these holds: (a) the declared acceptance gate, contract or prompt is violated; (b) a legal input escapes the declared failure face (a blank input returns 500, an unknown id is not a 404); (c) the gate fails or the suite can never go red (an inert grep · a dead guard · an unconditional skip); (d) a security or privacy defect. Debt inside the contract is a warn (duplicated policy · stale docstring · a missing coverage case). Style, naming and line-wrapping is a nit. Within one run, a defect already graded in the same class keeps that grade; crossing grades names its reason in the finding. The reviewed {artifact} is a vision, not an exhaustive enumeration — behavior it is silent on is judged by what a reasonable {audience} would expect; its silence is not permission, and a finding's severity grades that expectation, not whether the text mentions the trigger. Before your verdict, list every behavior you considered and set aside as outside the reviewed scope — one line each with the reason; nothing set aside is dropped silently; an empty list means you set nothing aside. Acknowledge what was done well before listing findings (accurate praise earns the rest of the report trust).";
278
+ * shares. Its tier body is ASSEMBLED from the criteria registry (every row's
279
+ * `body` → `duty` → `counterExample`, tiers in blocker → warn → nit order), so the
280
+ * registry is the only corpus of tier prose; the calibration tail rides here, and
281
+ * `reviewGuideOf` fills the two slots. */
282
+ export const SEVERITY_RUBRIC = `${RUBRIC_PREAMBLE} ${CRITERIA.renderRubric()} ${CALIBRATION_TAIL}`;
265
283
  /** The slot values per criteria body — the ONE registry the filled fragment reads.
266
284
  * `{artifact}` = the reviewed product's name; `{audience}` = the subject whose
267
285
  * expectation judges the artifact's silence. The two spec-shaped targets share the
@@ -282,6 +300,13 @@ export const reviewGuideOf = (key) => {
282
300
  const text = REVIEW_BODY_TEXT[key];
283
301
  return SEVERITY_RUBRIC.replaceAll(SEVERITY_RUBRIC_SLOTS.artifact, text.artifact).replaceAll(SEVERITY_RUBRIC_SLOTS.audience, text.audience);
284
302
  };
303
+ /** One review kind's numbered lens question list (design spec §3.2 · §6.1) — the
304
+ * `LENS_QUESTIONS.forReviewKind` projection rendered as `1. …` lines, appended to
305
+ * that kind's axes guide so the questions ride the `**Criteria —` bytes. The list is
306
+ * the table's projection, never a second copy: deleting a row shortens this list. */
307
+ const lensQuestionBlock = (kind) => LENS_QUESTIONS.forReviewKind(kind)
308
+ .map((row, index) => `${index + 1}. ${row.question}`)
309
+ .join("\n");
285
310
  /** The closed-wave discipline's ONE sentence (P30 §2.7) — the document review axes'
286
311
  * shared body: a finding on an already-closed task block's content face is answered
287
312
  * by the document, never by moving the work. Both document criteria bodies select
@@ -311,24 +336,45 @@ const docCharterAxes = (guide) => `Follow URC: single-cycle, lens-tagged finding
311
336
  * copy. */
312
337
  export const REVIEWS = {
313
338
  wave: {
314
- lensEnum: ["standards", "spec", "buildability"],
315
- axesGuide: `Standards axis (repo coding standards + code-review smell baseline) + Spec axis (wave brief / plan requirements) + Buildability axis (the reviewer explicitly runs the repository's typecheck command — \`tsc --noEmit\`, or the repo equivalent — AND its test command; every buildability finding self-reports the dual evidence, both commands ran) + Scope axis (changed-surface reasonableness): run \`git diff origin/<BASE_BRANCH>..HEAD\` yourself (BASE_BRANCH as named in the round context; on a missing artifact judge the working tree) — every changed file must fall within the wave brief's file surface (\`**Files:**\` seams) or be attributable to the plan / reviewed intent; an unattributable changed file is a candidate finding (severity by your judgment). The reviewer is the changed-surface judge — the engine reconciles nothing. ${reviewGuideOf("wave")}`,
339
+ lensEnum: ["standards", "spec", "buildability", "scope"],
340
+ pinLens: "standards",
341
+ axesGuide: `Standards axis (repo coding standards + code-review smell baseline) + Spec axis (wave brief / plan requirements) + Buildability axis (the reviewer explicitly runs the repository's typecheck command — \`tsc --noEmit\`, or the repo equivalent — AND its test command; every buildability finding self-reports the dual evidence, both commands ran) + Scope axis (changed-surface reasonableness): run \`git diff origin/<BASE_BRANCH>..HEAD\` yourself (BASE_BRANCH as named in the round context; on a missing artifact judge the working tree) — every changed file must fall within the wave brief's file surface (\`**Files:**\` seams) or be attributable to the plan / reviewed intent; an unattributable changed file is a candidate finding. The reviewer is the changed-surface judge — the engine reconciles nothing. ${reviewGuideOf("wave")}
342
+
343
+ ${lensQuestionBlock("wave")}`,
316
344
  },
317
345
  branch: {
318
- lensEnum: ["standards", "spec", "buildability"],
319
- axesGuide: `Same four axes as the wave review (branch-wide health: run \`git diff origin/<BASE_BRANCH>..HEAD\` + plan conformance) + Buildability axis (the reviewer explicitly runs the repository's typecheck command — \`tsc --noEmit\`, or the repo equivalent — AND its test command; every buildability finding self-reports the dual evidence, both commands ran) + Scope axis (changed-surface reasonableness): branch review IS the full diff — every changed file must be attributable to a finding, a plan requirement, or the reviewed intent; unrelated surface = candidate finding (severity by your judgment), normal finding → fix loop. ${reviewGuideOf("branch")} Three things a green run cannot show you: design — does the changed structure fit this codebase and is it the simplest structure that solves the plan's problem (over-engineering is a finding, not a preference); test adequacy — would these tests fail if the code broke (a run that cannot go red is not evidence); migration — does every breaking change name the path a not-yet-migrated consumer takes.`,
346
+ lensEnum: ["standards", "spec", "buildability", "scope"],
347
+ pinLens: "standards",
348
+ axesGuide: `Same four axes as the wave review (branch-wide health: run \`git diff origin/<BASE_BRANCH>..HEAD\` + plan conformance) + Buildability axis (the reviewer explicitly runs the repository's typecheck command — \`tsc --noEmit\`, or the repo equivalent — AND its test command; every buildability finding self-reports the dual evidence, both commands ran) + Scope axis (changed-surface reasonableness): branch review IS the full diff — every changed file must be attributable to a finding, a plan requirement, or the reviewed intent; unrelated surface = candidate finding, normal finding → fix loop. ${reviewGuideOf("branch")} Three things a green run cannot show you: design — does the changed structure fit this codebase and is it the simplest structure that solves the plan's problem (over-engineering is a finding, not a preference); test adequacy — would these tests fail if the code broke (a run that cannot go red is not evidence); migration — does every breaking change name the path a not-yet-migrated consumer takes.
349
+
350
+ ${lensQuestionBlock("branch")}`,
320
351
  },
321
352
  spec: {
322
353
  lensEnum: ["completeness", "consistency", "clarity"],
323
- axesGuide: docNarrativeAxes(reviewGuideOf("spec")),
354
+ // §7.2's own word for this corpus: two statements of one fact — the document's
355
+ // claim and the tree — disagree.
356
+ pinLens: "consistency",
357
+ axesGuide: `${docNarrativeAxes(reviewGuideOf("spec"))}
358
+
359
+ ${lensQuestionBlock("spec")}`,
324
360
  },
325
361
  overall: {
326
362
  lensEnum: ["scope", "inventory", "dependency", "acceptance", "boundary"],
327
- axesGuide: docCharterAxes(reviewGuideOf("overall")),
363
+ // The charter's criterion 6 is this row's home: the inventory and the tree
364
+ // disagree, so a pin that resolves nowhere reads as a ledger drift.
365
+ pinLens: "inventory",
366
+ axesGuide: `${docCharterAxes(reviewGuideOf("overall"))}
367
+
368
+ ${lensQuestionBlock("overall")}`,
328
369
  },
329
370
  plan: {
330
371
  lensEnum: ["completeness", "decomposition", "buildability"],
331
- axesGuide: `Follow URC: single-cycle, lens-tagged findings (completeness/decomposition/buildability) + spec conformance — the plan is judged against its design spec at \`INPUT_SPEC\` (the plan's \`spec\` front-matter target): every spec requirement must map to a task, and a spec requirement with no owning task is a completeness finding + the writing-plans self-check + verification evidence — the reviewer runs the repository's typecheck and test commands and self-reports the dual evidence + Claimed→pin: every behavior claim (usage-line attribution · semantic contract · byte face) must cite a colocated pin (path:line + the assertion face) — the review checks every claim against its pin, claim by claim; a pinless claim is a lens-tagged finding. ${CLOSED_WAVE_DISCIPLINE} ${reviewGuideOf("plan")}`,
372
+ // A step naming a coordinate the tree does not have is a step that cannot be
373
+ // executed against the tree as it stands.
374
+ pinLens: "buildability",
375
+ axesGuide: `Follow URC: single-cycle, lens-tagged findings (completeness/decomposition/buildability) + spec conformance — the plan is judged against its design spec at \`INPUT_SPEC\` (the plan's \`spec\` front-matter target): every spec requirement must map to a task, and a spec requirement with no owning task is a completeness finding + the writing-plans self-check + verification evidence — the reviewer runs the repository's typecheck and test commands and self-reports the dual evidence + Claimed→pin: every behavior claim (usage-line attribution · semantic contract · byte face) must cite a colocated pin (path:line + the assertion face) — the review checks every claim against its pin, claim by claim; a pinless claim is a lens-tagged finding. ${CLOSED_WAVE_DISCIPLINE} ${reviewGuideOf("plan")}
376
+
377
+ ${lensQuestionBlock("plan")}`,
332
378
  },
333
379
  };
334
380
  /** The criteria-body selection — the ONE target → criteria map. Four targets select
@@ -336,6 +382,22 @@ export const REVIEWS = {
336
382
  * narrative body (`spec`). Keeping the mapping here (never in the row literals)
337
383
  * means a target cannot silently drift onto another target's criteria. */
338
384
  export const reviewBodyOf = (type) => type === "phase-spec" || type === "single-spec" ? "spec" : type;
385
+ /** The lens an engine-authored pin row carries on one target's face (design spec
386
+ * §7.2) — the ONE derivation the read-back's injection point reads. The value is
387
+ * the face's declared `pinLens`, and it is cross-checked against that face's own
388
+ * `lensEnum` here: the menu and the injected row are written for different readers
389
+ * (the child's prompt vs the carrier), so a drifted pair must throw at its first
390
+ * dispatch instead of reaching a carrier as a label the same round's prompt calls
391
+ * impossible. `guides` is the declared table, injectable so the gate itself is
392
+ * pinnable. */
393
+ export const pinLensOf = (type, guides = REVIEWS) => {
394
+ const key = reviewBodyOf(type);
395
+ const row = guides[key];
396
+ if (!row.lensEnum.includes(row.pinLens)) {
397
+ throw new Error(`the pin lens "${row.pinLens}" is not declared by the ${key} lens menu (${row.lensEnum.join(" | ")})`);
398
+ }
399
+ return row.pinLens;
400
+ };
339
401
  /** One review variant row (§3.7) — the fixed prefix folds the SELECTED criteria
340
402
  * body + its lens INLINE (the `INPUT_CRITERIA`/`INPUT_LENS` round-context tokens
341
403
  * are gone) and shares the REVIEW_CONTEXT dynamic tail. The target word labels the
@@ -396,8 +458,10 @@ const TOKENS = [
396
458
  { name: "INPUT_SPEC", zone: "round-context" },
397
459
  { name: "INPUT_OVERALL", zone: "round-context" },
398
460
  { name: "INPUT_REVIEWS", zone: "round-context" },
399
- // P31 — the fix round's ruling sidecar (the source carrier's `.rulings.json`
400
- // sibling); a review writes its own draft, so its round context never carries it.
461
+ // P31 — the fix round's ruling sidecar; the path is the matrix's `rulings` row
462
+ // rendered from the REVIEWED round's identity (P36 §2.10), so it moves with that
463
+ // cycle, never with the carrier's own spelling. A review writes its own draft, so its
464
+ // round context never carries it.
401
465
  { name: "INPUT_RULINGS", zone: "round-context" },
402
466
  { name: "INPUT_WAVE_BRIEF", zone: "round-context" },
403
467
  // find #5 — the prescribed artifact write paths (the {family}-{key}-{artifact}
@@ -427,7 +491,11 @@ export const CLAUSES = {
427
491
  "cl:no-secret-access": "Never read, print, or derive a user secret — no keychain access (`security find-generic-password` / `security dump-keychain` / `login.keychain-db`), no `~/.ssh/*`, `~/.aws/credentials`, `~/.netrc`, no host CLI credential store, and no token-bearing environment variable (`*_TOKEN` / `*_API_KEY` / `*_SECRET`). A missing or failing credential is never yours to obtain: report it as `status: BLOCKED` on a work round or as a finding on a review round, then continue with the rest. A secret that reaches a report, evidence file, handoff draft, commit, or issue body has leaked — if one is already visible in your inputs, redact it as `[REDACTED]` and never echo its value.",
428
492
  "cl:sync-completion": "This dispatch is one-shot and non-interactive: end your turn with anything still running and the process exits — the work and the handoff die with it. So do not end your turn — a background command, a background subagent, or any yield-and-wait path such as `bg_run` / `bg_delegate` — before the handoff draft is written. Finish nested work in this same turn: complete it synchronously in this process turn, then write the handoff and finish.",
429
493
  };
430
- /** The dispatch-prompt data plane — the typed template-contract surface. $version 23
494
+ /** The dispatch-prompt data plane — the typed template-contract surface. $version 24
495
+ * names the wave line in the fix shell's anchor clause (P37 §4.1): the wave line now
496
+ * carries the same `INPUT_SPEC` conformance reference and the `INPUT_OVERALL` parent
497
+ * charter as the branch line, so the clause a maintainer reads can no longer
498
+ * attribute those anchors to the branch line alone. $version 23
431
499
  * calibrates the shared body's five faces (§2.6 G · H · I · J · K): the freeze
432
500
  * clause limits itself to the round's declared `capability: may.amend` scope and
433
501
  * the commit clause names the read-only round's absent commit; the capability
@@ -490,7 +558,7 @@ export const CLAUSES = {
490
558
  * prose return contract (`RETURN_PROSE` — nothing downstream parses the child's
491
559
  * stdout), and the per-type review criterion shells. */
492
560
  export const TEMPLATE_PROMPT = {
493
- $version: 23,
561
+ $version: 24,
494
562
  modes: MODE_PROMPTS,
495
563
  reviews: REVIEW_VARIANTS,
496
564
  return: RETURN_ZONE,
@@ -0,0 +1,108 @@
1
+ // packages/cdd-engine/src-next/session/artifact-reads.ts
2
+ // P36 T7 — the artifact read SEAM: the ONE composition of the matrix's judgment
3
+ // (names · presence · `misplaced` · `absent`) with the strict sidecar schema
4
+ // (`CarrierRulings#verdict`). Design spec §2.3 puts the two levels in one function so
5
+ // the prompt cell and the dispatch gate read one value; this file is that function's
6
+ // home, and it holds NO frame: the workspace arrives with the construction, so the
7
+ // frame-holding lifecycle and the frame-free board are two consumers of ONE seam
8
+ // instead of two composers.
9
+ //
10
+ // The seam's other half is the coordinate: a `rulings` sidecar belongs to the REVIEWED
11
+ // round, so its identity is always `attribute(basename(carrier))` with `op` fixed to
12
+ // `review` — never this dispatch's own `(line, op)`. That second expression would mint
13
+ // a name no gate ever sees.
14
+ //
15
+ // Module-level exports are the value type, the absent value and the class — zero
16
+ // behavior-carrying bare functions (the plan's zero-bare-function discipline).
17
+ import path from "node:path";
18
+ import { CarrierIntegrity, CarrierMismatchError } from "./carrier-integrity.js";
19
+ import { CarrierRulings } from "./carrier-rulings.js";
20
+ /** The no-sidecar read — nothing for the matrix to judge, nothing for the schema to
21
+ * parse. */
22
+ export const ABSENT_READ = { read: { kind: "absent" }, rulings: [] };
23
+ /**
24
+ * ArtifactReads — the frame-free artifact read seam: one workspace, one matrix, one
25
+ * method. `read(kind, carrier, digest)` answers the composed judgment for the kind a
26
+ * caller resolved, with `carrier` the round's carrier path and `digest` the digest its
27
+ * record remembered (`null` = a record that predates the column — a present-facts read,
28
+ * never a second-grade judgment).
29
+ *
30
+ * A carrier that attributes to no round identity (a matrix-external spelling, a P34-era
31
+ * legacy name) reads `absent`: the seam judges the kind it was asked for, and a name the
32
+ * matrix cannot place is an observation, not a refusal. A carrier whose bytes no longer
33
+ * digest to the recorded value THROWS (`CarrierMismatchError`) — a tampered carrier's id
34
+ * set is not a fact any round may read.
35
+ */
36
+ export class ArtifactReads {
37
+ #artifacts;
38
+ #base;
39
+ constructor(artifacts, base) {
40
+ this.#artifacts = artifacts;
41
+ this.#base = base;
42
+ }
43
+ /** The ONE read of this `kind` — matrix `read` × schema `verdict`, composed once. */
44
+ read(kind, carrier, digest) {
45
+ const identity = this.#identityOf(carrier);
46
+ if (identity === null)
47
+ return ABSENT_READ;
48
+ const read = this.#artifacts.read(identity, kind, this.#base);
49
+ if (read.kind !== "ok")
50
+ return { read, rulings: [] };
51
+ return this.#compose(read, carrier, digest);
52
+ }
53
+ /** The schema level over a matrix `ok` — `ok` carries the rulings, `invalid` the
54
+ * schema's own reason verbatim, and a second-level `absent` is a read RACE (the file
55
+ * left between the two levels), never "there is no sidecar" (spec §4.5). */
56
+ #compose(read, carrier, digest) {
57
+ const verdict = CarrierRulings.verdict(read.path, this.#carrierPathOf(carrier), this.#findingIdsOf(carrier, digest));
58
+ switch (verdict.kind) {
59
+ case "ok":
60
+ return { read, rulings: verdict.rulings };
61
+ case "absent":
62
+ return { read: { kind: "invalid", path: read.path, reason: "unreadable" }, rulings: [] };
63
+ case "invalid":
64
+ return { read: { kind: "invalid", path: read.path, reason: verdict.reason }, rulings: [] };
65
+ }
66
+ }
67
+ /** The reviewed round's identity — delegated to the matrix's ONE entry
68
+ * (`ArtifactRegistry#reviewedIdentityOf`: `attribute(basename(carrier))` with `op`
69
+ * fixed to `review`), or null when the carrier attributes to no round coordinate at
70
+ * all. The seam owns the COMPOSITION, the matrix owns the identity: neither spelling
71
+ * is repeated here. */
72
+ #identityOf(carrier) {
73
+ return this.#artifacts.reviewedIdentityOf(carrier);
74
+ }
75
+ /** The carrier's absolute path — the ONE erasure from the repo-relative carrier
76
+ * faces onto the syscall form both the sidecar judgment and the digest read use. */
77
+ #carrierPathOf(carrier) {
78
+ return path.resolve(this.#base.root.repoRoot, carrier);
79
+ }
80
+ /** The carrier's engine-written finding ids (`F1`, `F2` …) — the id set a ruling must
81
+ * name, read through the ONE checked carrier read. An absent or unparseable carrier
82
+ * declares no ids, so any ruling beside it is refused by the strict schema rather
83
+ * than accepted against an empty set. */
84
+ #findingIdsOf(carrier, digest) {
85
+ const ids = new Set();
86
+ let carrierJson;
87
+ try {
88
+ const bytes = CarrierIntegrity.read(this.#carrierPathOf(carrier), digest);
89
+ if (bytes === null)
90
+ return ids;
91
+ carrierJson = JSON.parse(bytes);
92
+ }
93
+ catch (raw) {
94
+ if (raw instanceof CarrierMismatchError)
95
+ throw raw;
96
+ return ids;
97
+ }
98
+ const findings = carrierJson?.findings;
99
+ if (!Array.isArray(findings))
100
+ return ids;
101
+ for (const finding of findings) {
102
+ const id = finding?.id;
103
+ if (typeof id === "string")
104
+ ids.add(id);
105
+ }
106
+ return ids;
107
+ }
108
+ }
@@ -1,76 +1,89 @@
1
1
  // packages/cdd-engine/src-next/session/carrier-rulings.ts
2
2
  // P31 T2 — the orchestrator's RULINGS sidecar: the one supported landing point for a
3
3
  // ruling on an engine-persisted carrier (design spec §2.1/§2.6). The engine's carrier
4
- // bytes are frozen at persist time, so a ruling never edits them: it is written beside
5
- // the carrier at the same stem, `<carrier>.json` → `<carrier>.rulings.json`, and read
6
- // back through the strict schema below. The file is the orchestrator's; the judgment
7
- // is the engine's — a sidecar the schema refuses is a hard stop BEFORE the fix child is
8
- // spawned, so a written ruling can never be silently invisible to the round that
9
- // consumes it.
4
+ // bytes are frozen at persist time, so a ruling never edits them: it is its own file,
5
+ // rendered by the artifact matrix's `rulings` row from the REVIEWED round's identity
6
+ // (P36 §2.10), and read back through the strict schema below. The file is the
7
+ // orchestrator's; the judgment is the engine's — a sidecar the schema refuses is a hard
8
+ // stop BEFORE the fix child is spawned, so a written ruling can never be silently
9
+ // invisible to the round that consumes it.
10
10
  //
11
11
  // Two levels, both strict (unknown keys are refused, never ignored): the top level
12
12
  // carries `carrier` (optional; when present it must name the carrier file) and
13
- // `rulings` (required array); each ruling carries `finding` + `ruling` (both required
14
- // strings) and the optional `at` / `by`. A ruling's `finding` must name a finding of
15
- // the carrier it sits beside — the id set is the caller's fact, injected.
13
+ // `rulings` (required array); each ruling carries ONE identifier — `finding`, or its
14
+ // `id` alias, normalized to `finding` on the way in — plus `ruling` (both required
15
+ // strings) and the optional `at` / `by`. A ruling's identifier must name a finding of
16
+ // the carrier it answers — the id set is the caller's fact, injected.
17
+ //
18
+ // The sidecar PATH is not minted here: it is the artifact matrix's `rulings` row
19
+ // rendered from the reviewed round's identity and resolved by the caller's workspace
20
+ // (`render(identity, "rulings")`). Only the NAME is the matrix's; the `carrier` key's
21
+ // comparison still reads the carrier's own basename, so neither direction of the
22
+ // relationship is derived from the other side's string.
16
23
  //
17
24
  // The sidecar is NEVER sealed by the engine: only the engine's own carriers are.
18
25
  import { existsSync, readFileSync } from "node:fs";
19
26
  import path from "node:path";
27
+ import { ArtifactRegistry } from "./round-artifacts.js";
20
28
  /** The top-level keys the schema declares — anything else is refused. */
21
29
  const TOP_KEYS = new Set(["carrier", "rulings"]);
22
- /** The keys one ruling declares — anything else is refused. */
23
- const RULING_KEYS = new Set(["finding", "ruling", "at", "by"]);
24
- /** CarrierRulings — the sidecar path rule, the lenient read and the strict judgment.
25
- * Stateless: every call takes the carrier path (and, for the judgment, the carrier's
26
- * own finding-id set), so the class holds no per-round state. */
30
+ /** The ruling schema's NON-identifier fields — the verdict text and the orchestrator's
31
+ * optional stamp. The identifier field is deliberately absent from this list: its
32
+ * acceptance set is the artifact matrix's `rulings` row declaration alone (§2.8), so
33
+ * `finding` / `id` are never enumerated a second time here. */
34
+ const RULING_FIELDS = ["ruling", "at", "by"];
35
+ /** CarrierRulings — the lenient read and the strict judgment of a rulings sidecar.
36
+ * Stateless: every call takes the sidecar's own path AND the carrier it answers (the
37
+ * strict schema's `carrier` key speaks the carrier's fact; the id set is the caller's).
38
+ * The path itself is the artifact matrix's render — this class never derives one. */
27
39
  // biome-ignore lint/complexity/noStaticOnlyClass: the plan-mandated sidecar read surface — the zero-bare-function discipline admits no standalone predicate functions.
28
40
  export class CarrierRulings {
29
- /** The sidecar path of a carrier — its trailing `.json` replaced by `.rulings.json`
30
- * (a path that does not end in `.json` gains the suffix as-is, never a guess). */
31
- static pathFor(carrierPath) {
32
- return carrierPath.endsWith(".json")
33
- ? `${carrierPath.slice(0, -".json".length)}.rulings.json`
34
- : `${carrierPath}.rulings.json`;
35
- }
36
- /** The sidecar's rulings as recorded — null when the file is absent, unparsable or
37
- * does not carry a rulings array. The lenient read is for callers that render a
38
- * ruling, never for the gate: the dispatch gate judges through `verdict`. */
39
- static read(carrierPath) {
40
- const parsed = CarrierRulings.#parse(CarrierRulings.pathFor(carrierPath));
41
+ /** The sidecar's rulings as recorded — null when the file is absent, unparsable, does
42
+ * not carry a rulings array, or carries a `carrier` key naming another file. The
43
+ * lenient side is the TOLERANCE of unknown keys / unknown finding ids; the carrier
44
+ * fact is judged here too, so neither consumer can read a sidecar that answers a
45
+ * different carrier. The dispatch gate judges through `verdict`; the read face that
46
+ * renders the ruling bodies takes this one. */
47
+ static read(sidecarPath, carrierPath) {
48
+ const parsed = CarrierRulings.#parse(sidecarPath);
41
49
  if (parsed.kind !== "ok")
42
50
  return null;
43
- return CarrierRulings.#lenientRulings(parsed.value);
51
+ const record = CarrierRulings.#recordOf(parsed.value);
52
+ if (record === null)
53
+ return null;
54
+ if (CarrierRulings.#carrierRefusal(record, carrierPath) !== null)
55
+ return null;
56
+ return CarrierRulings.#lenientRulings(record);
44
57
  }
45
58
  /** The strict judgment — the fix dispatch's pre-spawn gate. `findingIds` is the
46
59
  * carrier's own finding-id set: a ruling on a finding the carrier does not carry is
47
60
  * refused, never carried into the round as a phantom. */
48
- static verdict(carrierPath, findingIds) {
49
- const sidecar = CarrierRulings.pathFor(carrierPath);
50
- const parsed = CarrierRulings.#parse(sidecar);
61
+ static verdict(sidecarPath, carrierPath, findingIds) {
62
+ const parsed = CarrierRulings.#parse(sidecarPath);
51
63
  if (parsed.kind !== "ok")
52
64
  return parsed;
53
65
  const record = CarrierRulings.#recordOf(parsed.value);
54
66
  if (record === null) {
55
- return CarrierRulings.#invalid(sidecar, "the sidecar is not a JSON object");
67
+ return CarrierRulings.#invalid(sidecarPath, "the sidecar is not a JSON object");
56
68
  }
57
69
  if (!CarrierRulings.#keysWithin(record, TOP_KEYS)) {
58
- return CarrierRulings.#invalid(sidecar, `unknown top-level key(s) — the schema declares ${[...TOP_KEYS].join(" / ")}`);
70
+ return CarrierRulings.#invalid(sidecarPath, `unknown top-level key(s) — the schema declares ${[...TOP_KEYS].join(" / ")}`);
59
71
  }
60
72
  const carrierRefusal = CarrierRulings.#carrierRefusal(record, carrierPath);
61
73
  if (carrierRefusal !== null)
62
- return CarrierRulings.#invalid(sidecar, carrierRefusal);
74
+ return CarrierRulings.#invalid(sidecarPath, carrierRefusal);
63
75
  if (!("rulings" in record)) {
64
- return CarrierRulings.#invalid(sidecar, "the sidecar carries no `rulings` array");
76
+ return CarrierRulings.#invalid(sidecarPath, "the sidecar carries no `rulings` array");
65
77
  }
66
78
  if (!Array.isArray(record.rulings)) {
67
- return CarrierRulings.#invalid(sidecar, "`rulings` is not an array");
79
+ return CarrierRulings.#invalid(sidecarPath, "`rulings` is not an array");
68
80
  }
69
81
  const rulings = [];
82
+ const vocabulary = CarrierRulings.#identifier();
70
83
  for (const [index, entry] of record.rulings.entries()) {
71
- const ruling = CarrierRulings.#rulingOf(entry, index, findingIds);
84
+ const ruling = CarrierRulings.#rulingOf(entry, index, findingIds, vocabulary);
72
85
  if (typeof ruling === "string")
73
- return CarrierRulings.#invalid(sidecar, ruling);
86
+ return CarrierRulings.#invalid(sidecarPath, ruling);
74
87
  rulings.push(ruling);
75
88
  }
76
89
  return { kind: "ok", rulings };
@@ -111,18 +124,27 @@ export class CarrierRulings {
111
124
  }
112
125
  return null;
113
126
  }
114
- /** One ruling entry — the narrowed record, or the refusal's reason string. */
115
- static #rulingOf(entry, index, findingIds) {
127
+ /** One ruling entry — the narrowed record with its identifier NORMALIZED to the
128
+ * canonical spelling, or the refusal's reason string. The accepted spellings are the
129
+ * matrix row's declaration (`finding` · `id`), so a sidecar written either way is one
130
+ * ruling, and an unknown key is still a whole-file refusal. */
131
+ static #rulingOf(entry, index, findingIds, vocabulary) {
116
132
  const record = CarrierRulings.#recordOf(entry);
117
133
  if (record === null)
118
134
  return `ruling #${index + 1} is not a JSON object`;
119
- const unknown = Object.keys(record).filter((key) => !RULING_KEYS.has(key));
135
+ const declared = new Set([...vocabulary.accepts, ...RULING_FIELDS]);
136
+ const unknown = Object.keys(record).filter((key) => !declared.has(key));
120
137
  if (unknown.length > 0) {
121
138
  return `ruling #${index + 1} carries unknown key(s) — ${unknown.join(", ")}`;
122
139
  }
123
- const { finding, ruling, at, by } = record;
124
- if (typeof finding !== "string")
125
- return `ruling #${index + 1} carries no string \`finding\``;
140
+ const spelling = CarrierRulings.#identifierKeyOf(record, index, vocabulary);
141
+ if (typeof spelling !== "string")
142
+ return spelling.reason;
143
+ const finding = record[spelling];
144
+ const { ruling, at, by } = record;
145
+ if (typeof finding !== "string") {
146
+ return `ruling #${index + 1} carries no string \`${vocabulary.canonical}\``;
147
+ }
126
148
  if (typeof ruling !== "string")
127
149
  return `ruling #${index + 1} carries no string \`ruling\``;
128
150
  if (at !== undefined && typeof at !== "string") {
@@ -141,18 +163,49 @@ export class CarrierRulings {
141
163
  ...(by === undefined ? {} : { by }),
142
164
  };
143
165
  }
166
+ /** The identifier key ONE ruling carries — exactly one of the accepted spellings
167
+ * (`finding` · `id`). None is a refusal naming the canonical spelling; two is an
168
+ * ambiguity the schema settles by refusing the file, never by picking a winner. */
169
+ static #identifierKeyOf(record, index, vocabulary) {
170
+ const present = vocabulary.accepts.filter((key) => key in record);
171
+ if (present.length === 1)
172
+ return present[0];
173
+ if (present.length === 0) {
174
+ return { reason: `ruling #${index + 1} carries no string \`${vocabulary.canonical}\`` };
175
+ }
176
+ return {
177
+ reason: `ruling #${index + 1} carries both ${present.map((key) => `\`${key}\``).join(" and ")} — one identifier per ruling`,
178
+ };
179
+ }
180
+ /** The `rulings` row's identifier vocabulary — the matrix's OWN declaration (§2.8).
181
+ * A matrix that lost the row refuses loudly here: a second hand-written acceptance
182
+ * set is exactly the double expression this consumes away. */
183
+ static #identifier() {
184
+ const declared = ArtifactRegistry.identifierOf("rulings");
185
+ if (declared === null) {
186
+ throw new Error("the artifact matrix's `rulings` row declares no identifier vocabulary");
187
+ }
188
+ return declared;
189
+ }
144
190
  /** The lenient rulings read — null unless every entry carries the two required
145
- * strings (an unknown key is tolerated here; the strict gate owns that refusal). */
191
+ * strings (an unknown key is tolerated here; the strict gate owns that refusal). The
192
+ * identifier is read through the SAME acceptance set, so both faces accept `id` and
193
+ * both hand back the canonical `finding`. */
146
194
  static #lenientRulings(value) {
147
195
  const record = CarrierRulings.#recordOf(value);
148
196
  if (record === null || !Array.isArray(record.rulings))
149
197
  return null;
198
+ const vocabulary = CarrierRulings.#identifier();
150
199
  const rulings = [];
151
200
  for (const entry of record.rulings) {
152
201
  const row = CarrierRulings.#recordOf(entry);
153
202
  if (row === null)
154
203
  return null;
155
- const { finding, ruling, at, by } = row;
204
+ const spelling = CarrierRulings.#identifierKeyOf(row, rulings.length, vocabulary);
205
+ if (typeof spelling !== "string")
206
+ return null;
207
+ const finding = row[spelling];
208
+ const { ruling, at, by } = row;
156
209
  if (typeof finding !== "string" || typeof ruling !== "string")
157
210
  return null;
158
211
  rulings.push({
@@ -260,7 +260,7 @@ export class DispatchAuthority {
260
260
  * carries its document in `plan`, every other shape in `id`. */
261
261
  static #docDriftPair(target, facts) {
262
262
  const doc = target.type === "branch" ? (target.plan ?? null) : target.id;
263
- return doc === null ? null : facts.ledger.docDriftHashes(target.type, doc, target.type);
263
+ return doc === null ? null : facts.ledger.docDriftHashes(target.type, doc);
264
264
  }
265
265
  /** The refusal line's reason head — the token alone, or the token plus the mandatory
266
266
  * diagnosis (§2.5): `layer=` · `line=` · `recorded=` · `current=` with a stable hash
@@ -431,8 +431,7 @@ export class DispatchAuthority {
431
431
  * holds no station: the request face is the pipeline's own first entry. */
432
432
  static #docEntered(ledger, line) {
433
433
  const lead = targetFaces[line.type].product.reviewLead;
434
- return (ledger.roundCount(line.key, lead, line.type) > 0 ||
435
- ledger.roundCount(line.key, "fix", line.type) > 0);
434
+ return ledger.roundCount(line.key, lead) > 0 || ledger.roundCount(line.key, "fix") > 0;
436
435
  }
437
436
  }
438
437
  _a = DispatchAuthority;