@oscaner-skills/cdd-engine 4.7.0 → 4.9.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,110 @@
1
+ // packages/cdd-engine/src-next/infra/carrier-seal.ts
2
+ // P31 T5 — the write-protection bit of the engine's own carriers (design spec §2.4):
3
+ // a carrier lands READ-ONLY, the dispatch that owns it opens exactly its own two names
4
+ // (the child's draft, the engine's final), and every terminal seals again. The
5
+ // orchestrator's rulings ride a sidecar (`CarrierRulings`) that is never sealed, so a
6
+ // sealed carrier never blocks a ruling.
7
+ //
8
+ // The sweep is the recovery leg of the invariant: a carrier left writable by a process
9
+ // killed outside the engine is sealed by the NEXT dispatch's preflight. Its scope is
10
+ // the carrier NAME shapes `RoundNaming.isCarrierName` mints — never the directory's
11
+ // other JSON (`progress.json` · `base.json` · `*-test-evidence.json` · the crash
12
+ // records) and never a `.rulings.json` sidecar.
13
+ //
14
+ // Module-level exports are the class — zero behavior-carrying bare functions.
15
+ import { chmodSync, readdirSync, statSync } from "node:fs";
16
+ import path from "node:path";
17
+ import { RoundNaming } from "../session/round-naming.js";
18
+ /** The ruling sidecar's suffix — a sidecar is written AFTER its carrier is sealed and
19
+ * is never sealed itself (spec §2.1). The name rule lives with `CarrierRulings`; this
20
+ * is the sweep's own belt-and-braces skip, so a future widening of the carrier
21
+ * predicate can never sweep a sidecar. */
22
+ const RULINGS_SUFFIX = ".rulings.json";
23
+ /**
24
+ * CarrierSeal — the permission-bit face of the engine's carriers. Stateless by
25
+ * construction (every method is a judgment over a path), so the whole surface is
26
+ * static: no instance could hold a different fact.
27
+ */
28
+ // biome-ignore lint/complexity/noStaticOnlyClass: every method is a judgment over a path argument; there is no per-instance state to hold.
29
+ export class CarrierSeal {
30
+ /** The mode a carrier lands in: owner, group and other all read-only — the engine
31
+ * rewrites a carrier by unsealing it first, never by writing through the sealed bit. */
32
+ static SEALED = 0o444;
33
+ /** The mode a dispatch opens its OWN names with (the child writes the draft, the
34
+ * materialization rewrites the final). */
35
+ static WRITABLE = 0o644;
36
+ /** Seal one carrier — idempotent, and a name that was never written (a failed round
37
+ * whose draft/final never landed) is not an error: the absence is the round's own
38
+ * fact, never a seal failure. */
39
+ static seal(target) {
40
+ CarrierSeal.#chmod(target, CarrierSeal.SEALED);
41
+ }
42
+ /** Open one carrier for writing — the preflight half of a dispatch's own paths. */
43
+ static unseal(target) {
44
+ CarrierSeal.#chmod(target, CarrierSeal.WRITABLE);
45
+ }
46
+ /** Seal every ORPHAN carrier of one directory and return the names actually sealed.
47
+ * An orphan is an engine carrier (the two name shapes `RoundNaming.isCarrierName`
48
+ * mints) that is still writable — left behind by a process killed outside the
49
+ * engine. `keep` names files the caller holds open itself (this round's own paths);
50
+ * a `.rulings.json` sidecar is never touched. Everything else in the directory is
51
+ * invisible to the sweep, and an already-sealed carrier is zero churn: not returned,
52
+ * not rewritten, so an empty array means there was nothing to recover. */
53
+ static sweep(directory, keep) {
54
+ const strays = CarrierSeal.#strays(directory, keep);
55
+ for (const name of strays)
56
+ CarrierSeal.seal(path.join(directory, name));
57
+ return strays;
58
+ }
59
+ /** The directory's orphan carrier NAMES — the sweep's judgment, before any chmod. */
60
+ static #strays(directory, keep) {
61
+ const strays = [];
62
+ for (const entry of CarrierSeal.#entries(directory)) {
63
+ if (!entry.isFile())
64
+ continue;
65
+ const target = path.join(directory, entry.name);
66
+ if (!CarrierSeal.#isStray(target, entry.name, keep))
67
+ continue;
68
+ strays.push(entry.name);
69
+ }
70
+ return strays;
71
+ }
72
+ /** Whether one directory entry is an orphan carrier the sweep must recover: a minted
73
+ * carrier name, not held open by the caller, not a ruling sidecar, and NOT already
74
+ * sealed. An unreadable entry (a vanished race) is not a stray — the sweep never
75
+ * invents a recovery it did not make. */
76
+ static #isStray(target, name, keep) {
77
+ if (!RoundNaming.isCarrierName(name))
78
+ return false;
79
+ if (keep.includes(name) || name.endsWith(RULINGS_SUFFIX))
80
+ return false;
81
+ try {
82
+ return (statSync(target).mode & 0o777) !== CarrierSeal.SEALED;
83
+ }
84
+ catch {
85
+ return false;
86
+ }
87
+ }
88
+ /** The directory's entries — an unreadable directory (never created) holds no
89
+ * orphans, so the sweep is a no-op rather than a failure. */
90
+ static #entries(directory) {
91
+ try {
92
+ return readdirSync(directory, { withFileTypes: true });
93
+ }
94
+ catch {
95
+ return [];
96
+ }
97
+ }
98
+ /** The one chmod seam — a missing target is the round's own absence, not an error;
99
+ * every other failure (a permissions problem the engine cannot fix) is surfaced. */
100
+ static #chmod(target, mode) {
101
+ try {
102
+ chmodSync(target, mode);
103
+ }
104
+ catch (raw) {
105
+ if (raw.code === "ENOENT")
106
+ return;
107
+ throw raw;
108
+ }
109
+ }
110
+ }
package/dist/infra/git.js CHANGED
@@ -45,6 +45,32 @@ export class GitClient {
45
45
  return null;
46
46
  }
47
47
  }
48
+ /** The paths the commits after `base` touched — `git log --name-only
49
+ * --pretty=format: <base>..HEAD`, deduped and blank-free (P31 §2.7: the write-back's
50
+ * "did this round touch the document" evidence). Three facts, never two: a readable
51
+ * range with no change yields `[]`, an absent base / non-repo / unreadable git yields
52
+ * `null` — "nothing changed" and "cannot tell" are different, and collapsing the
53
+ * second into the first would silently claim a round touched nothing. */
54
+ async pathsSince(cwd, base) {
55
+ if (base === null)
56
+ return null;
57
+ try {
58
+ const raw = await this.#git(cwd).raw([
59
+ "log",
60
+ "--name-only",
61
+ "--pretty=format:",
62
+ `${base}..HEAD`,
63
+ ]);
64
+ const paths = raw
65
+ .split("\n")
66
+ .map((line) => line.trim())
67
+ .filter((line) => line !== "");
68
+ return [...new Set(paths)];
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
48
74
  /** The commits added after `base`, oldest first, each as `{sha} {subject}` — the
49
75
  * work a crashed child left behind. An absent base or an unreadable repo yields
50
76
  * the empty list (fail-open: the diagnostic fact never breaks a crash record). */
@@ -13,11 +13,17 @@
13
13
  // child-path single fact. Document identity is NOT derived here: the workspace
14
14
  // key is the document's declared `slug:`, judged by the ONE identity index
15
15
  // (infra/slug-index.ts).
16
+ import { createHash } from "node:crypto";
16
17
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
17
18
  import path from "node:path";
18
19
  import { parse } from "jsonc-parser";
19
20
  import { AtomicWriter } from "./atomic.js";
20
21
  import { RepoRoot } from "./root.js";
22
+ /** The raw-bytes sha256 (hex) — the workspace plane's ONE digest primitive. The
23
+ * session plane's carrier rule (`CarrierIntegrity.sha256`) delegates HERE, so the
24
+ * engine holds one hashing implementation: the carrier's payload rule is layered over
25
+ * it, never re-spelled. */
26
+ export const sha256Hex = (bytes) => createHash("sha256").update(bytes, "utf8").digest("hex");
21
27
  /** The persisted path-field keys — the JSON fields whose value is a PATH (the
22
28
  * progress.json `reviewedRevision.doc` / `.plan` layers · the base.json `plan`
23
29
  * field). The read-time normalization (P9 T4 §2.11) relativizes exactly these
@@ -157,10 +163,21 @@ export class Workspace {
157
163
  * normalizes any straggler). The written bytes carry exactly one trailing `\n`
158
164
  * (the repo's EOF rule), so an engine-written file is byte-canonical and the
159
165
  * one-time migration leaves it byte-identical (zero churn). */
160
- writeJson(name, value) {
166
+ /** Write a JSON child and hand back the digest of exactly the bytes that landed —
167
+ * the ONE serialization point (`writeJson` is this method's thin shell, so the
168
+ * written bytes and the returned digest can never describe two different
169
+ * documents). The digest is the sha256 hex of the written string; for a carrier
170
+ * with no top-level `contentSha256` key it equals
171
+ * `CarrierIntegrity.digestOf(value)` — whose payload rule is the session plane's
172
+ * single carrier-digest rule (this seam owns the bytes primitive only). */
173
+ writeJsonHashed(name, value) {
161
174
  this.ensure();
162
- const normalized = this.#normalizePaths(value);
163
- this.#atomic.write(this.resolve(name), `${JSON.stringify(normalized, null, 2)}\n`);
175
+ const bytes = `${JSON.stringify(this.#normalizePaths(value), null, 2)}\n`;
176
+ this.#atomic.write(this.resolve(name), bytes);
177
+ return sha256Hex(bytes);
178
+ }
179
+ writeJson(name, value) {
180
+ this.writeJsonHashed(name, value);
164
181
  }
165
182
  /** Write a text child — mkdir before write (the text twin of `writeJson`; the
166
183
  * engine-rendered brief is the one text artifact the engine authors itself).
@@ -121,7 +121,7 @@ const FIX_SHELL = [
121
121
  WORK_CAPABILITY,
122
122
  ...FIX_TYPED_INSTRUCTIONS,
123
123
  "**fix:** read `INPUT_REVIEWS` (open findings) + the plan context (`INPUT_WAVE_BRIEF` on a wave line — the complete plan mirror; `INPUT_PLAN` on the plan/branch lines — the plan document; `INPUT_SPEC` on the spec line — the spec 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).",
124
- '**Dispositions:** every requested finding needs a disposition keyed by its own summary text (verbatim), valued `{ "status": "fixed" | "rejected", "reason"?: "…" }` — a missing or mis-keyed disposition fails the round.',
124
+ '**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.',
125
125
  EVIDENCE_ITEM,
126
126
  ...LICENSE_ITEMS,
127
127
  // T5 (v0.3) — The work plane's ONE strict-schema sentence: every top-level draft
@@ -144,7 +144,10 @@ const DOCS_FIX_SHELL = [
144
144
  ...FRAME_ITEMS,
145
145
  WORK_CAPABILITY,
146
146
  "**docs-fix:** apply `INPUT_REVIEWS` (all severities) directly to the judged doc — `INPUT_PLAN` on a plan-doc line, `INPUT_SPEC` on a spec-doc line — removing fixed findings; record the path in `artifacts.doc` and report the round in `status` (APPROVED once every finding is applied, else BLOCKED + the reason in `notes`). Fix + write the draft at `OUTPUT_HANDOFF` per `## Handoff schema` in one process; retry = full re-run (idempotent).",
147
- '**Dispositions:** every requested finding needs a disposition keyed by its own summary text (verbatim), valued `{ "status": "fixed" | "rejected", "reason"?: "…" }` — a missing or mis-keyed disposition fails the round.',
147
+ "**Change-history rows:** a new `## Change history` row bumps the front-matter `version:` in the same edit — the header version is the lineage's newest numeric version, and the two can never disagree.",
148
+ "**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.",
149
+ "**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.",
150
+ '**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.',
148
151
  ...LICENSE_ITEMS,
149
152
  // The generic strict-schema sentence — the SAME one the work shells carry: the
150
153
  // injected declaration is the draft's single field source, zero per-mode field
@@ -209,6 +212,7 @@ const MODE_PROMPTS = {
209
212
  "- `INPUT_SPEC`: {{INPUT_SPEC}}",
210
213
  "- `INPUT_OVERALL`: {{INPUT_OVERALL}}",
211
214
  "- `INPUT_REVIEWS`: {{INPUT_REVIEWS}}",
215
+ "- `INPUT_RULINGS`: {{INPUT_RULINGS}}",
212
216
  "- `OUTPUT_REPORT`: {{OUTPUT_REPORT}}",
213
217
  "- `OUTPUT_EVIDENCE`: {{OUTPUT_EVIDENCE}}",
214
218
  "- `OUTPUT_HANDOFF`: {{OUTPUT_HANDOFF}}",
@@ -228,6 +232,7 @@ const MODE_PROMPTS = {
228
232
  "- `INPUT_SPEC`: {{INPUT_SPEC}}",
229
233
  "- `INPUT_OVERALL`: {{INPUT_OVERALL}}",
230
234
  "- `INPUT_REVIEWS`: {{INPUT_REVIEWS}}",
235
+ "- `INPUT_RULINGS`: {{INPUT_RULINGS}}",
231
236
  "- `OUTPUT_REPORT`: {{OUTPUT_REPORT}}",
232
237
  "- `OUTPUT_HANDOFF`: {{OUTPUT_HANDOFF}}",
233
238
  "- `WORKSPACE_DIR`: {{WORKSPACE_DIR}}",
@@ -267,6 +272,13 @@ export const reviewGuideOf = (key) => {
267
272
  const text = REVIEW_BODY_TEXT[key];
268
273
  return SEVERITY_RUBRIC.replaceAll(SEVERITY_RUBRIC_SLOTS.artifact, text.artifact).replaceAll(SEVERITY_RUBRIC_SLOTS.audience, text.audience);
269
274
  };
275
+ /** The closed-wave discipline's ONE sentence (P30 §2.7) — the document review axes'
276
+ * shared body: a finding on an already-closed task block's content face is answered
277
+ * by the document, never by moving the work. Both document criteria bodies select
278
+ * it, so the duty cannot fork between the plan variant and the spec shapes; the
279
+ * engine routes nothing on it (no finding classification, no dispatch branch) — it is
280
+ * prompt text, judged by the reviewer. */
281
+ export const CLOSED_WAVE_DISCIPLINE = "Closed waves are history: a finding on the content face of an already-closed task block is answered by amending the document to align with the delivered split — never by carrying work into or out of a closed task, and a finding that would rewrite the historical split is not raised.";
270
282
  /** The spec-shaped documents' narrative criteria body — the phase-spec line's URC
271
283
  * + its program-conformance clause, the ONE body both spec-shaped target rows
272
284
  * select (the filled rubric is what differs per row). The charter's own criteria
@@ -276,7 +288,7 @@ export const reviewGuideOf = (key) => {
276
288
  * today's tree happens to have: a line number is not a pin, a prose count is the
277
289
  * guard's business, and a present-tense description of today's shape belongs to the
278
290
  * plan. Nothing gates the writing moment — the review is where a violation surfaces. */
279
- const docNarrativeAxes = (guide) => `Follow URC: single-cycle, lens-tagged findings (completeness/consistency/clarity) + 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 by module path + symbol name — a line number is not a pin; a count ("N places" · "N rows" · "N modules") must be stated as pinned by the named guard or test; a present-tense description of today's shape belongs to the plan — in a design spec a measurement input is a lens-tagged finding unless restated as a condition that must hold — the review checks every claim against its pin, claim by claim; a pinless claim is a lens-tagged finding + program conformance — judge the phase against its parent overall at \`INPUT_OVERALL\` (the charter its \`program:\` names): the phase must sit inside the scope the overall's Phase inventory registered for it, and a phase that reaches beyond it is a completeness finding. ${guide}`;
291
+ const docNarrativeAxes = (guide) => `Follow URC: single-cycle, lens-tagged findings (completeness/consistency/clarity) + 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 by module path + symbol name — a line number is not a pin; a count ("N places" · "N rows" · "N modules") must be stated as pinned by the named guard or test; a present-tense description of today's shape belongs to the plan — in a design spec a measurement input is a lens-tagged finding unless restated as a condition that must hold — the review checks every claim against its pin, claim by claim; a pinless claim is a lens-tagged finding + program conformance — judge the phase against its parent overall at \`INPUT_OVERALL\` (the charter its \`program:\` names): the phase must sit inside the scope the overall's Phase inventory registered for it, and a phase that reaches beyond it is a completeness finding. ${CLOSED_WAVE_DISCIPLINE} ${guide}`;
280
292
  /** The charter's criteria body — the six things a program charter owns, and only
281
293
  * those. It carries none of the implementation-face evidence duty the narrative
282
294
  * body carries (running the repository's commands, pinning every claim): a charter
@@ -306,7 +318,7 @@ export const REVIEWS = {
306
318
  },
307
319
  plan: {
308
320
  lensEnum: ["completeness", "decomposition", "buildability"],
309
- 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. ${reviewGuideOf("plan")}`,
321
+ 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")}`,
310
322
  },
311
323
  };
312
324
  /** The criteria-body selection — the ONE target → criteria map. Four targets select
@@ -374,6 +386,9 @@ const TOKENS = [
374
386
  { name: "INPUT_SPEC", zone: "round-context" },
375
387
  { name: "INPUT_OVERALL", zone: "round-context" },
376
388
  { name: "INPUT_REVIEWS", zone: "round-context" },
389
+ // P31 — the fix round's ruling sidecar (the source carrier's `.rulings.json`
390
+ // sibling); a review writes its own draft, so its round context never carries it.
391
+ { name: "INPUT_RULINGS", zone: "round-context" },
377
392
  { name: "INPUT_WAVE_BRIEF", zone: "round-context" },
378
393
  // find #5 — the prescribed artifact write paths (the {family}-{key}-{artifact}
379
394
  // single naming; the brief is a pure read input with no write slot).
@@ -0,0 +1,128 @@
1
+ // packages/cdd-engine/src-next/session/carrier-integrity.ts
2
+ // P31 §2.2 — the carrier content digest and its ONE checked read.
3
+ //
4
+ // A carrier is the engine's own artifact (handoff draft or finalized round carrier):
5
+ // the engine writes it, the round's `RoundRecord` remembers the digest of the payload
6
+ // it wrote, and every engine seam that READS a carrier again compares the bytes it
7
+ // finds against that record. A mismatch is a hard stop (`CDD_BLOCKED`, the
8
+ // `carrier-mismatch` line, no child) — the tampered carrier is never judged as if the
9
+ // round had produced those bytes.
10
+ //
11
+ // The rule is single-sourced here, never re-spelled at a call site:
12
+ // · `digestOf` is THE payload-digest rule — the payload re-serialized exactly as the
13
+ // workspace write seam serializes it, minus the optional top-level `contentSha256`
14
+ // key (a FINAL carrier's own embedded digest must not fold itself into its own
15
+ // value; a draft carries no such key, so for a draft `digestOf` equals the sha256
16
+ // of the written bytes).
17
+ // · `read` is THE checked read — absent (`null`), ok (bytes), or mismatch (a thrown
18
+ // `CarrierMismatchError`). A record that predates the digest column is a
19
+ // present-facts read: its bytes are returned with zero comparison (zero migration).
20
+ //
21
+ // The class depends on no session module (the ledger never enters this import graph), so
22
+ // the contract plane and the face plane can both read through it without a cycle: the
23
+ // payload rule here is layered over the workspace plane's one digest primitive.
24
+ import { readFileSync } from "node:fs";
25
+ import { sha256Hex } from "../infra/workspace.js";
26
+ /** The shasum prefix the diagnostic line prints — the `doc-drift` form's recorded /
27
+ * current pair, shortened to the 8 hex chars a human can actually compare. */
28
+ const PREFIX_LENGTH = 8;
29
+ /** The carrier-read refusal — the bytes at `line` no longer digest to the value the
30
+ * round recorded. The message IS the diagnostic line (one shape, one station):
31
+ * `carrier-mismatch · line=<path> · recorded=<sha8> · current=<sha8>`. */
32
+ export class CarrierMismatchError extends Error {
33
+ /** The carrier's path (absolute, as recorded) — the `line` the message names. */
34
+ line;
35
+ /** The digest the round's record carries (full hex). */
36
+ recorded;
37
+ /** The digest the bytes on disk compute to now (full hex). */
38
+ current;
39
+ constructor(line, recorded, current) {
40
+ super(`carrier-mismatch · line=${line} · recorded=${CarrierIntegrity.sha8(recorded)} · current=${CarrierIntegrity.sha8(current)}`);
41
+ this.name = "CarrierMismatchError";
42
+ this.line = line;
43
+ this.recorded = recorded;
44
+ this.current = current;
45
+ }
46
+ }
47
+ // biome-ignore lint/complexity/noStaticOnlyClass: the plan-mandated carrier read surface — the zero-bare-function discipline admits no standalone predicate functions.
48
+ export class CarrierIntegrity {
49
+ /** The raw-bytes sha256 (hex) — the workspace plane's single primitive, delegated
50
+ * here so a caller of this class need not know where the bytes live. */
51
+ static sha256(bytes) {
52
+ return sha256Hex(bytes);
53
+ }
54
+ /** The first 8 hex chars — the diagnostic line's recorded / current pair. */
55
+ static sha8(digest) {
56
+ return digest.slice(0, PREFIX_LENGTH);
57
+ }
58
+ /** THE carrier payload digest — the payload re-serialized exactly as the workspace
59
+ * write seam does (`JSON.stringify(payload, null, 2)` + one trailing newline),
60
+ * minus the optional top-level `contentSha256` key. Single rule: a final carrier's
61
+ * embedded digest covers its payload, never the file bytes that hold it. */
62
+ static digestOf(value) {
63
+ return CarrierIntegrity.sha256(`${JSON.stringify(CarrierIntegrity.#payloadOf(value), null, 2)}\n`);
64
+ }
65
+ /** The recorded / current pair when the two digests disagree — null when either side
66
+ * is unknown (a legacy record: nothing to compare) or when they agree. */
67
+ static mismatch(recorded, current) {
68
+ if (recorded === null || current === null)
69
+ return null;
70
+ return recorded === current ? null : { recorded, current };
71
+ }
72
+ /** THE checked read — three distinct outcomes, never folded together:
73
+ * · the file is absent → `null` (a present-facts absence, never a throw);
74
+ * · no recorded digest (a legacy round) → the bytes verbatim, zero comparison;
75
+ * · both known → the bytes when the recomputed payload digest equals the recorded
76
+ * one, a `CarrierMismatchError` when it does not.
77
+ * Any other read error (EACCES, EISDIR …) propagates: a present-but-unreadable
78
+ * carrier is the caller's own unreadable fact, never a silent absence. */
79
+ static read(path, recordedDigest) {
80
+ const bytes = CarrierIntegrity.#bytesAt(path);
81
+ if (bytes === null || recordedDigest === null)
82
+ return bytes;
83
+ const gap = CarrierIntegrity.mismatch(recordedDigest, CarrierIntegrity.#currentOf(bytes));
84
+ if (gap === null)
85
+ return bytes;
86
+ throw new CarrierMismatchError(path, gap.recorded, gap.current);
87
+ }
88
+ /** The record-shaped thin shell — the `RoundRecord`'s own two cells, so a caller
89
+ * holding a record never re-derives "which digest belongs to this path". A record
90
+ * with no carrier path reads `null` without touching the disk. */
91
+ static readFor(record) {
92
+ if (record.carrierPath === null)
93
+ return null;
94
+ return CarrierIntegrity.read(record.carrierPath, record.carrierDigest ?? null);
95
+ }
96
+ /** The payload view `digestOf` hashes — a shallow copy with the top-level
97
+ * `contentSha256` key dropped (a non-object payload is returned as it stands). */
98
+ static #payloadOf(value) {
99
+ if (value === null || typeof value !== "object" || Array.isArray(value))
100
+ return value;
101
+ const payload = { ...value };
102
+ delete payload.contentSha256;
103
+ return payload;
104
+ }
105
+ /** The carrier's bytes; `null` when the path holds no file. Any other I/O failure
106
+ * propagates (the caller names it unreadable — never absent). */
107
+ static #bytesAt(path) {
108
+ try {
109
+ return readFileSync(path, "utf8");
110
+ }
111
+ catch (raw) {
112
+ if (raw.code === "ENOENT")
113
+ return null;
114
+ throw raw;
115
+ }
116
+ }
117
+ /** The digest of one carrier's bytes — the payload rule when the bytes parse, the
118
+ * raw-bytes digest when they do not (an unparseable payload matches no recorded
119
+ * payload digest, and the raw digest still names the difference honestly). */
120
+ static #currentOf(bytes) {
121
+ try {
122
+ return CarrierIntegrity.digestOf(JSON.parse(bytes));
123
+ }
124
+ catch {
125
+ return CarrierIntegrity.sha256(bytes);
126
+ }
127
+ }
128
+ }
@@ -0,0 +1,167 @@
1
+ // packages/cdd-engine/src-next/session/carrier-rulings.ts
2
+ // P31 T2 — the orchestrator's RULINGS sidecar: the one supported landing point for a
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.
10
+ //
11
+ // Two levels, both strict (unknown keys are refused, never ignored): the top level
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.
16
+ //
17
+ // The sidecar is NEVER sealed by the engine: only the engine's own carriers are.
18
+ import { existsSync, readFileSync } from "node:fs";
19
+ import path from "node:path";
20
+ /** The top-level keys the schema declares — anything else is refused. */
21
+ 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. */
27
+ // biome-ignore lint/complexity/noStaticOnlyClass: the plan-mandated sidecar read surface — the zero-bare-function discipline admits no standalone predicate functions.
28
+ 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
+ if (parsed.kind !== "ok")
42
+ return null;
43
+ return CarrierRulings.#lenientRulings(parsed.value);
44
+ }
45
+ /** The strict judgment — the fix dispatch's pre-spawn gate. `findingIds` is the
46
+ * carrier's own finding-id set: a ruling on a finding the carrier does not carry is
47
+ * 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);
51
+ if (parsed.kind !== "ok")
52
+ return parsed;
53
+ const record = CarrierRulings.#recordOf(parsed.value);
54
+ if (record === null) {
55
+ return CarrierRulings.#invalid(sidecar, "the sidecar is not a JSON object");
56
+ }
57
+ if (!CarrierRulings.#keysWithin(record, TOP_KEYS)) {
58
+ return CarrierRulings.#invalid(sidecar, `unknown top-level key(s) — the schema declares ${[...TOP_KEYS].join(" / ")}`);
59
+ }
60
+ const carrierRefusal = CarrierRulings.#carrierRefusal(record, carrierPath);
61
+ if (carrierRefusal !== null)
62
+ return CarrierRulings.#invalid(sidecar, carrierRefusal);
63
+ if (!("rulings" in record)) {
64
+ return CarrierRulings.#invalid(sidecar, "the sidecar carries no `rulings` array");
65
+ }
66
+ if (!Array.isArray(record.rulings)) {
67
+ return CarrierRulings.#invalid(sidecar, "`rulings` is not an array");
68
+ }
69
+ const rulings = [];
70
+ for (const [index, entry] of record.rulings.entries()) {
71
+ const ruling = CarrierRulings.#rulingOf(entry, index, findingIds);
72
+ if (typeof ruling === "string")
73
+ return CarrierRulings.#invalid(sidecar, ruling);
74
+ rulings.push(ruling);
75
+ }
76
+ return { kind: "ok", rulings };
77
+ }
78
+ /** Parse the file at one path — absent vs unparsable are different facts. */
79
+ static #parse(sidecar) {
80
+ if (!existsSync(sidecar))
81
+ return { kind: "absent" };
82
+ try {
83
+ return { kind: "ok", value: JSON.parse(readFileSync(sidecar, "utf8")) };
84
+ }
85
+ catch {
86
+ return { kind: "invalid", reason: `${sidecar}: the sidecar is not JSON` };
87
+ }
88
+ }
89
+ /** One refusal — the path is named so the operator sees WHICH sidecar was refused. */
90
+ static #invalid(sidecar, reason) {
91
+ return { kind: "invalid", reason: `${sidecar}: ${reason}` };
92
+ }
93
+ /** The value narrowed to a plain object (arrays and null are not records). */
94
+ static #recordOf(value) {
95
+ if (value === null || typeof value !== "object" || Array.isArray(value))
96
+ return null;
97
+ return value;
98
+ }
99
+ /** Whether every own key of `record` is declared by `declared`. */
100
+ static #keysWithin(record, declared) {
101
+ return Object.keys(record).every((key) => declared.has(key));
102
+ }
103
+ /** The `carrier` key's refusal — absent is fine; present must name this carrier. */
104
+ static #carrierRefusal(record, carrierPath) {
105
+ if (!("carrier" in record))
106
+ return null;
107
+ const declared = record.carrier;
108
+ const expected = path.basename(carrierPath);
109
+ if (typeof declared !== "string" || declared !== expected) {
110
+ return `\`carrier\` names ${JSON.stringify(declared)} ≠ the carrier ${expected}`;
111
+ }
112
+ return null;
113
+ }
114
+ /** One ruling entry — the narrowed record, or the refusal's reason string. */
115
+ static #rulingOf(entry, index, findingIds) {
116
+ const record = CarrierRulings.#recordOf(entry);
117
+ if (record === null)
118
+ return `ruling #${index + 1} is not a JSON object`;
119
+ const unknown = Object.keys(record).filter((key) => !RULING_KEYS.has(key));
120
+ if (unknown.length > 0) {
121
+ return `ruling #${index + 1} carries unknown key(s) — ${unknown.join(", ")}`;
122
+ }
123
+ const { finding, ruling, at, by } = record;
124
+ if (typeof finding !== "string")
125
+ return `ruling #${index + 1} carries no string \`finding\``;
126
+ if (typeof ruling !== "string")
127
+ return `ruling #${index + 1} carries no string \`ruling\``;
128
+ if (at !== undefined && typeof at !== "string") {
129
+ return `ruling #${index + 1} carries a non-string \`at\``;
130
+ }
131
+ if (by !== undefined && typeof by !== "string") {
132
+ return `ruling #${index + 1} carries a non-string \`by\``;
133
+ }
134
+ if (!findingIds.has(finding)) {
135
+ return `ruling #${index + 1} answers ${finding}, which is not a finding of the carrier`;
136
+ }
137
+ return {
138
+ finding,
139
+ ruling,
140
+ ...(at === undefined ? {} : { at }),
141
+ ...(by === undefined ? {} : { by }),
142
+ };
143
+ }
144
+ /** 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). */
146
+ static #lenientRulings(value) {
147
+ const record = CarrierRulings.#recordOf(value);
148
+ if (record === null || !Array.isArray(record.rulings))
149
+ return null;
150
+ const rulings = [];
151
+ for (const entry of record.rulings) {
152
+ const row = CarrierRulings.#recordOf(entry);
153
+ if (row === null)
154
+ return null;
155
+ const { finding, ruling, at, by } = row;
156
+ if (typeof finding !== "string" || typeof ruling !== "string")
157
+ return null;
158
+ rulings.push({
159
+ finding,
160
+ ruling,
161
+ ...(typeof at === "string" ? { at } : {}),
162
+ ...(typeof by === "string" ? { by } : {}),
163
+ });
164
+ }
165
+ return { rulings };
166
+ }
167
+ }