@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.
@@ -15,18 +15,23 @@ var _a;
15
15
  // The module exports the shared seams + the lifecycle class — zero behavior-carrying
16
16
  // bare functions.
17
17
  import { existsSync, readFileSync } from "node:fs";
18
+ import path from "node:path";
18
19
  import process from "node:process";
19
20
  import { printParseErrorCode } from "jsonc-parser";
20
21
  import { CompletionCriteria, FixDispositions } from "../contract/completion-criterion.js";
22
+ import { PlanTaskBlocksReader } from "../contract/task-blocks.js";
23
+ import { CarrierSeal } from "../infra/carrier-seal.js";
21
24
  import { GitClient } from "../infra/git.js";
22
25
  import { ProcessFacts } from "../infra/proc.js";
23
26
  import { RoundLog } from "../infra/round-log.js";
24
27
  import { BriefRenderer } from "../render/brief.js";
25
28
  import { TemplateAssembler } from "../render/templates.js";
29
+ import { CarrierIntegrity, CarrierMismatchError } from "../session/carrier-integrity.js";
30
+ import { CarrierRulings } from "../session/carrier-rulings.js";
26
31
  import { TargetFaceTable } from "../session/faces.js";
27
32
  import { HandoffSchema } from "../session/handoff-schema.js";
28
33
  import { InFlight } from "../session/inflight.js";
29
- import { Ledger, RoundViolation, } from "../session/ledger.js";
34
+ import { Ledger, RoundRecords, RoundViolation, } from "../session/ledger.js";
30
35
  import { RoundNaming } from "../session/round-naming.js";
31
36
  import { PlanStructure } from "../session/run.js";
32
37
  import { DISPATCH, HOSTS, HostDetect, REFS } from "./host.js";
@@ -40,6 +45,10 @@ const STDOUT_TAIL_MAX = 40;
40
45
  * set or a task's `DependsOn` set moved inside the round (design spec §7.3). The
41
46
  * vanished / unreadable document cases name their own damage instead. */
42
47
  const STRUCTURE_CHANGED = "the plan's structure changed inside this round (the Task id set or a task's DependsOn set) — the structure face belongs to the orchestrator and lands as its own commit";
48
+ /** The abort fold's ONE hard entry (spec §2.2) — the killed round's grade, cause
49
+ * (`interrupted`, the vocabulary's new literal) and prose. One entry, one cause: the
50
+ * fold records WHY the round has no conclusion, never a second diagnosis. */
51
+ const ABORT_INTERRUPTED = RoundViolation.hard("the dispatch was interrupted outside the engine — its in-flight record named a dead holder at takeover, so the round concluded nothing (the same command re-offers it)", "interrupted");
43
52
  /**
44
53
  * CliLifecycle — the lifecycle's dispatch-seam production default (the split contract's
45
54
  * lifecycle face; face/cli.ts re-exports it as HarnessDispatch so the composition
@@ -72,6 +81,9 @@ export class CliLifecycle {
72
81
  * frame derives here (the report/evidence/brief names + the family op), so the
73
82
  * lifecycle and the dry-run preview name the same artifacts by one rule. */
74
83
  #naming;
84
+ /** The plan's task-block read face — the `Files` declaration the implement
85
+ * criterion's verification cell derives from (P30 §2.4). */
86
+ #blocks = new PlanTaskBlocksReader();
75
87
  /** The handoff-schema face — stateless, one shared instance (the read-back
76
88
  * validator + the injected prompt text). */
77
89
  #handoffSchema = new HandoffSchema();
@@ -85,10 +97,11 @@ export class CliLifecycle {
85
97
  * (`ProcessFacts.startOf`; injected by the tests to span a long session). */
86
98
  #proc;
87
99
  /** Whether this invocation asked to take over a dead holder's record (the
88
- * `--steal-stale` flag — the only takeover path). */
89
- #stealStale;
100
+ * `--recover` flag — the only takeover path). */
101
+ #recover;
90
102
  /** The HEAD the current dispatch started from (null off a repo / before a spawn) —
91
- * the postmortem baseline of `commitsSince`. */
103
+ * the postmortem baseline of `commitsSince` AND the in-flight record's
104
+ * `dispatchBase` cell (the killed round's group baseline a takeover restores, §2.2). */
92
105
  #dispatchBase = null;
93
106
  /** The commits added after `#dispatchBase` (computed once the child returned). */
94
107
  #commitsSince = [];
@@ -112,7 +125,7 @@ export class CliLifecycle {
112
125
  opts.inflight ?? new InFlight(opts.scene.workspace.root, opts.scene.workspace.slug);
113
126
  this.#git = opts.git ?? new GitClient();
114
127
  this.#proc = opts.proc ?? ProcessFacts;
115
- this.#stealStale = opts.stealStale ?? false;
128
+ this.#recover = opts.recover ?? false;
116
129
  this.#sync = opts.sync ?? new Terminator();
117
130
  this.#template = opts.template ?? new TemplateAssembler();
118
131
  this.#brief = opts.brief ?? new BriefRenderer();
@@ -134,6 +147,76 @@ export class CliLifecycle {
134
147
  step() {
135
148
  return (frame) => this.#dispatch(frame);
136
149
  }
150
+ /** The `--recover` abort leg (spec §2.1①/§2.2) — take over a stale in-flight record
151
+ * and, when the record can still name the killed round, fold that round into the
152
+ * ledger as an abort: `targetAction: false` plus ONE hard `interrupted` entry, the
153
+ * record's own cycle / attempt / `dispatchBase`. The group baseline therefore returns
154
+ * to before the killed round, so a recovery commit lands inside the next dispatch's
155
+ * window instead of being invisible.
156
+ *
157
+ * The three stale morphologies are judged HERE, exactly as `acquire({ recover })`
158
+ * judges them: a dead holder's readable record, a corrupt record with a leftover
159
+ * lock, a lock with no record behind it. Only the first carries a record back, so
160
+ * only it is booked — the other two have no op / cycle / baseline to read, and an
161
+ * invented identity is worse than no record (zero invention, same discipline as the
162
+ * `treeClean` pin below). A live holder is never displaced.
163
+ *
164
+ * Writes NO `crash-*.json` and promotes no draft: the crash record is the death face's
165
+ * (`#reject`), and this is the postmortem fold of a dispatch killed outside the
166
+ * engine — the two paths never mix. Returns whether an abort record was written. */
167
+ async foldAbort() {
168
+ const stale = await this.#inflight.staleState();
169
+ if (stale === null)
170
+ return false;
171
+ if (stale.kind === "held") {
172
+ const record = await this.#inflight.steal(InFlight.STEAL_REASON.deadHolder);
173
+ return record === null ? false : this.#bookAbort(record);
174
+ }
175
+ // The two record-less morphologies: the takeover is the whole effect (no op /
176
+ // cycle / baseline is readable, and an invented identity would be worse).
177
+ await this.#inflight.steal(stale.kind === "corrupt"
178
+ ? InFlight.STEAL_REASON.corruptRecord
179
+ : InFlight.STEAL_REASON.lockOnly);
180
+ return false;
181
+ }
182
+ /** Book one taken-over record as the killed round's abort fact — the cells are the
183
+ * record's OWN (op from its phase through the ledger's one mode mapping, cycle /
184
+ * attempt / baseline verbatim). `treeClean` is pinned TRUE explicitly: the fold makes
185
+ * no dispatch-after observation, so leaving the ledger's default to be re-read would
186
+ * let two implementations book different facts (`#softOf` folds
187
+ * `treeClean === false` into a dirty-tree observation).
188
+ *
189
+ * A record that cannot name its whole identity — the row key, the op, the cycle or the
190
+ * attempt — is NOT booked: the takeover happens, and no identity is made up for it. An
191
+ * allocated cycle or a defaulted attempt would be invented facts, and either could
192
+ * overwrite a real round's record on the same `(op, cycle, attempt)`. */
193
+ #bookAbort(record) {
194
+ const op = RoundRecords.opOf(record.phase ?? "");
195
+ const { wave: key, cycle, attempt } = record;
196
+ if (op === null || key === null || cycle === null || attempt === null)
197
+ return false;
198
+ this.#scene.ledger.recordRound(key, {
199
+ op,
200
+ cycle,
201
+ attempt,
202
+ dispatchBase: record.dispatchBase,
203
+ verdict: { treeClean: true, targetAction: false },
204
+ violations: [ABORT_INTERRUPTED],
205
+ carrierPath: null,
206
+ }, "wave");
207
+ // P31 T5 §2.4 — the killed round's carrier names close with its abort record: the
208
+ // draft the dead child may have left writable and the final it never materialized.
209
+ // The identity is the record's OWN (the same op/cycle the abort booked), never a
210
+ // re-derivation from the current frontier.
211
+ this.#sealRoundCarriersOf(op, "wave", _a.#waveParams(key, cycle, op));
212
+ return true;
213
+ }
214
+ /** The handoff params of a wave round, replayed from a dead holder's record — the
215
+ * same shaping the frame builder applies (the implement family is round-less, the
216
+ * review / fix families carry the cycle). */
217
+ static #waveParams(key, cycle, op) {
218
+ return op === "implement" ? { tasks: key } : { tasks: key, round: cycle };
219
+ }
137
220
  /** One dispatch — the round's work, the observation facts every record carries (the
138
221
  * dispatch baseline HEAD captured before the spawn, the dispatch-after
139
222
  * `treeClean` observation) and the TERMINAL VERDICT the round is booked under
@@ -160,6 +243,9 @@ export class CliLifecycle {
160
243
  ...drafted,
161
244
  dispatchBase: this.#dispatchBase,
162
245
  treeClean: await this.#git.isClean(this.#scene.workspace.root.repoRoot),
246
+ // P31 §2.7 — whether THIS round's commits touched the document its write-back
247
+ // binds. Measured once, here, from the same baseline the postmortem reads.
248
+ touchedDoc: await this.#touchedDocOf(carried),
163
249
  };
164
250
  const judged = await this.#verdictOf(carried, observed);
165
251
  // The death faces author their own entry AND emit their own line (`#reject`), so
@@ -179,6 +265,31 @@ export class CliLifecycle {
179
265
  violations: judged.violations,
180
266
  };
181
267
  }
268
+ /** The document path the round's write-back would bind (P31 §2.7) — the doc leg's
269
+ * target document, the branch leg's plan document. The wave leg binds a brief
270
+ * PROJECTION rather than a document, so it does not participate (null). */
271
+ #reviewedDocTargetOf(frame) {
272
+ if (frame.target.kind === "plan" || frame.target.kind === "spec")
273
+ return frame.target.doc;
274
+ if (frame.type === "branch")
275
+ return this.#scene.planPath;
276
+ return null;
277
+ }
278
+ /** Whether this round's own commits touched that document — `true` / `false` read off
279
+ * the `dispatchBase..HEAD` path set, `null` when the range cannot be read (no
280
+ * baseline / unreadable repo), `undefined` when the leg binds no document. The four
281
+ * states stay distinct all the way to the bookkeep: only `false` may skip the bind,
282
+ * and `null` books its own soft observation. */
283
+ async #touchedDocOf(frame) {
284
+ const target = this.#reviewedDocTargetOf(frame);
285
+ if (target === null)
286
+ return undefined;
287
+ const repoRoot = this.#scene.workspace.root.repoRoot;
288
+ const touched = await this.#git.pathsSince(repoRoot, this.#dispatchBase);
289
+ if (touched === null)
290
+ return null;
291
+ return touched.includes(path.relative(repoRoot, path.resolve(repoRoot, target)));
292
+ }
182
293
  /** The round's concluded status under its verdict — a done round keeps its handoff
183
294
  * conclusion (APPROVED when the handoff was never written: the completion criterion
184
295
  * concluded it), and a hard-failed round concludes BLOCKED — or keeps TIMEOUT, the
@@ -221,10 +332,14 @@ export class CliLifecycle {
221
332
  ],
222
333
  };
223
334
  }
335
+ // The evidence gate is judged ONCE: its graded entries ride the verdict AND its
336
+ // result feeds the criterion's read-only `evidenceOk` cell (P30 §2.4) — the round
337
+ // pays for one evidence read, never two.
338
+ const evidence = this.#evidenceViolations(frame);
224
339
  const violations = [
225
340
  ...(outcome.violations ?? []),
226
- ...(await this.#criterionViolations(frame, outcome)),
227
- ...this.#evidenceViolations(frame),
341
+ ...(await this.#criterionViolations(frame, outcome, evidence)),
342
+ ...evidence,
228
343
  ...this.#structureViolations(frame),
229
344
  ...logEntries,
230
345
  ];
@@ -237,8 +352,13 @@ export class CliLifecycle {
237
352
  };
238
353
  }
239
354
  /** The verb's completion-criterion verdict as graded entries — the criterion's own
240
- * hard violation plus its SOFT observations (design spec §3.2/§3.3). */
241
- async #criterionViolations(frame, outcome) {
355
+ * hard violation plus its SOFT observations (design spec §3.2/§3.3).
356
+ *
357
+ * The verification cells (P30 §2.4) are filled HERE, the single point: the wave's
358
+ * empty-`Files` task ids come from the plan document the dispatch already reads
359
+ * (`#emptyFileTasks`), and `evidenceOk` is the evidence judgment the round already
360
+ * ran — the gate's own result, never a second disk read. */
361
+ async #criterionViolations(frame, outcome, evidence) {
242
362
  const scene = this.#scene;
243
363
  const judged = await CompletionCriteria.of(this.#opOf(frame)).judge({
244
364
  record: this.#judgedRecordOf(frame, outcome),
@@ -248,12 +368,36 @@ export class CliLifecycle {
248
368
  reviewsPath: this.#reviewsPath(frame),
249
369
  git: this.#git,
250
370
  repoRoot: scene.workspace.root.repoRoot,
371
+ emptyFileTasks: this.#emptyFileTasks(),
372
+ evidenceOk: evidence.length === 0,
251
373
  });
252
374
  return [
253
375
  ...(judged.violation === null ? [] : [judged.violation]),
254
376
  ...(judged.observations ?? []),
255
377
  ];
256
378
  }
379
+ /** The plan tasks whose `Files` declaration names no path — the verification-wave
380
+ * cell. The PLAN document is the only source (never the diff): an absent plan, a
381
+ * plan path pointing at no document or an unreadable one declares no empty row, so
382
+ * a wave can never read as verification on a plan this dispatch could not see. */
383
+ #emptyFileTasks() {
384
+ const planPath = this.#scene.planPath;
385
+ if (planPath === null)
386
+ return new Set();
387
+ let content;
388
+ try {
389
+ content = readFileSync(planPath, "utf8");
390
+ }
391
+ catch {
392
+ return new Set();
393
+ }
394
+ const empty = new Set();
395
+ for (const block of this.#blocks.parse(content)) {
396
+ if (this.#blocks.filePathsOf(block).length === 0)
397
+ empty.add(block.id);
398
+ }
399
+ return empty;
400
+ }
257
401
  /** The round IDENTITY the criterion judges from — its op / cycle / attempt, the
258
402
  * group baseline and the carrier path the round writes. Deliberately verdict-free:
259
403
  * this judgment PRODUCES the verdict, so a verdict cell here would be a
@@ -370,6 +514,34 @@ export class CliLifecycle {
370
514
  this.#io.stderr("CDD_BLOCKED: no host harness detected (run cdd from within a supported harness)\n");
371
515
  return { status: "BLOCKED" };
372
516
  }
517
+ // P31 T5 §2.4 — the preflight half of the seal cycle: the workspace's ORPHAN
518
+ // carriers first (a process killed outside the engine leaves a writable carrier
519
+ // behind), then this round's OWN two names become writable — its draft for the
520
+ // child, its final for the materialization. The scope is the round's own paths,
521
+ // never the directory or the slug: an input carrier of an earlier round (the fix
522
+ // leg's `--reviews`) stays 0o444 for the whole dispatch.
523
+ this.#openRoundCarriers(frame);
524
+ // P31 T3 — the carrier-integrity gate: the fix round's requesting carrier is
525
+ // compared against the digest its round recorded BEFORE the in-flight record and
526
+ // the child, so a tampered input never reaches a child (the read-back and the CLI
527
+ // catch are the fallbacks, never the gate). It runs BEFORE the ruling gate: the
528
+ // integrity diagnostic is the fact, and a sidecar judged against tampered bytes
529
+ // would name a ruling reason for a carrier whose bytes simply changed.
530
+ const carrierRefusal = this.#carrierRefusal(frame);
531
+ if (carrierRefusal !== null) {
532
+ this.#sealRoundCarriers(frame);
533
+ this.#blocked(carrierRefusal, false);
534
+ return { status: "BLOCKED", violations: [RoundViolation.hard(carrierRefusal)] };
535
+ }
536
+ // P31 T2 — the ruling sidecar gate: a sidecar the strict schema refuses stops the
537
+ // round HERE, before the in-flight record is acquired and before any child exists
538
+ // (a written-but-invisible ruling is the defect this gate removes).
539
+ const rulingsRefusal = this.#rulingsRefusal(frame);
540
+ if (rulingsRefusal !== null) {
541
+ this.#sealRoundCarriers(frame);
542
+ this.#blocked(rulingsRefusal, false);
543
+ return { status: "BLOCKED", violations: [RoundViolation.hard(rulingsRefusal)] };
544
+ }
373
545
  const prompt = this.#template.render(this.#valuesOf(frame));
374
546
  const row = HOSTS[host];
375
547
  const cliName = row.cli;
@@ -381,7 +553,17 @@ export class CliLifecycle {
381
553
  // A sibling dispatch that won the lock in between makes `acquire` throw
382
554
  // `HoldingError` (carrying the holder's facts), which rides the CLI's held BLOCK.
383
555
  this.#dispatchBase = await this.#git.head(this.#scene.workspace.root.repoRoot);
384
- await this.#inflight.acquire(await this.#recordOf(frame), { stealStale: this.#stealStale });
556
+ try {
557
+ await this.#inflight.acquire(await this.#recordOf(frame), { recover: this.#recover });
558
+ }
559
+ catch (raw) {
560
+ // P31 T5 §2.4 — the preflight half already opened this round's two names, so
561
+ // EVERY exit after it closes them, including this one: a losing dispatch (the
562
+ // gate→acquire race the CLI renders as the held BLOCK) must not leave a
563
+ // writable carrier behind for the next preflight sweep to recover.
564
+ this.#sealRoundCarriers(frame);
565
+ throw raw;
566
+ }
385
567
  // The round's own log file — created BEFORE the spawn (append stream open, zero
386
568
  // bytes), so the channel exists from the dispatch's first millisecond. A create
387
569
  // failure is a named soft observation and the round continues on the CPU leg
@@ -488,6 +670,7 @@ export class CliLifecycle {
488
670
  attempt: frame.attempt ?? 1,
489
671
  briefHash: this.#briefHashOf(frame),
490
672
  plan: scene.planPath === null ? null : this.#rel(scene.planPath),
673
+ dispatchBase: this.#dispatchBase,
491
674
  sampledAt: null,
492
675
  verdict: null,
493
676
  };
@@ -611,6 +794,11 @@ export class CliLifecycle {
611
794
  // carrier; a review writes its own draft (INPUT_REVIEWS === OUTPUT_HANDOFF
612
795
  // would be a short-circuit).
613
796
  INPUT_REVIEWS: op === "fix" ? this.#rel(this.#reviewsPath(frame) ?? "") : "",
797
+ // P31 T2 — the ruling sidecar rides the fix input side alone (the review round's
798
+ // own context has no sidecar yet). The path derives from the requesting carrier
799
+ // by the ONE `.json` → `.rulings.json` rule; an absent sidecar leaves the slot
800
+ // empty, so the assembler drops the line entirely.
801
+ INPUT_RULINGS: this.#rulingsInputOf(frame),
614
802
  // The kind-named judged-doc anchors (the semantic retirement of the generic
615
803
  // INPUT_DOC): the plan/branch lines carry the plan document (INPUT_PLAN — the
616
804
  // doc path on a plan line, the plan path on a branch line, whose review/fix
@@ -695,6 +883,47 @@ export class CliLifecycle {
695
883
  return lines.slice(-STDOUT_TAIL_MAX);
696
884
  }
697
885
  // -------------------------------------------------------------------------
886
+ // the carrier seal cycle (P31 T5 §2.4) — the round's own write window
887
+ // -------------------------------------------------------------------------
888
+ /** P31 §2.4 preflight — recover the workspace's orphans, then open THIS round's own
889
+ * two names. The sweep runs FIRST so a carrier this round is about to own (a stale
890
+ * draft of a retried round) is already closed when it is reopened here: the window
891
+ * is the two names, never a third file. */
892
+ #openRoundCarriers(frame) {
893
+ CarrierSeal.sweep(this.#scene.workspace.path, []);
894
+ for (const name of this.#roundCarrierNames(frame))
895
+ CarrierSeal.unseal(name);
896
+ }
897
+ /** P31 §2.4 terminal — close the round's own write window. Every exit path that ran
898
+ * the preflight half calls this (a gate refusal, a death face, an abort fold), so no
899
+ * terminal leaves an engine carrier writable. */
900
+ #sealRoundCarriers(frame) {
901
+ this.#sealRoundCarriersOf(this.#opOf(frame), frame.type, frame.params);
902
+ }
903
+ /** The seal of one (op, type, params) identity — the frame-shaped callers and the
904
+ * dead-holder fold share this ONE derivation. */
905
+ #sealRoundCarriersOf(op, type, params) {
906
+ for (const name of this.#roundCarrierNamesOf(op, type, params))
907
+ CarrierSeal.seal(name);
908
+ }
909
+ /** A frame's own carrier paths — the child's draft (`Ledger#handoffPath`, the family
910
+ * table's fill) and the engine's final (`RoundNaming#finalPath`, `.c{N}` suffixed).
911
+ * A round-less family (implement) resolves both to the same path — one name, sealed
912
+ * once. */
913
+ #roundCarrierNames(frame) {
914
+ return this.#roundCarrierNamesOf(this.#opOf(frame), frame.type, frame.params);
915
+ }
916
+ /** `#roundCarrierNames` over an identity — the abort fold's entry (it holds a dead
917
+ * holder's op/cycle, never a frame). */
918
+ #roundCarrierNamesOf(op, type, params) {
919
+ const ledger = this.#scene.ledger;
920
+ const draftName = ledger.handoffName(op, type, params);
921
+ return [
922
+ this.#scene.workspace.resolve(draftName),
923
+ this.#naming.finalPath(draftName, params.round),
924
+ ];
925
+ }
926
+ // -------------------------------------------------------------------------
698
927
  // the read-back reconstruct (§3.6) — the draft is the round's content
699
928
  // -------------------------------------------------------------------------
700
929
  /** The ONE draft-read point — the frame's handoff draft read with the lenient
@@ -815,11 +1044,24 @@ export class CliLifecycle {
815
1044
  // carriers the ledger reads back, never a schema-validated draft).
816
1045
  const status = schema.conclusionOf(plane, draft) ?? "BLOCKED";
817
1046
  const carrier = this.#materialize(frame, plane, draft, status);
1047
+ // P31 §2.2 — the disposition summary reads the REQUESTING carrier. A mismatch
1048
+ // found here (the bytes moved inside the round) is a BLOCKED outcome: the read-back
1049
+ // is the FALLBACK behind the pre-dispatch gate, never the gate itself.
1050
+ let summary;
1051
+ try {
1052
+ summary = this.#dispositionsSummary(frame, plane, carrier);
1053
+ }
1054
+ catch (raw) {
1055
+ if (!(raw instanceof CarrierMismatchError))
1056
+ throw raw;
1057
+ this.#blocked(raw.message, false);
1058
+ return { status: "BLOCKED", violations: [RoundViolation.hard(raw.message)] };
1059
+ }
818
1060
  return {
819
1061
  status,
820
1062
  findings: plane === "judge" ? schema.findingsOf(findings) : undefined,
821
1063
  carrier,
822
- dispositionsSummary: this.#dispositionsSummary(frame, plane, carrier),
1064
+ dispositionsSummary: summary,
823
1065
  };
824
1066
  }
825
1067
  /** The fix round's ONE summary line (design spec §3.4) — computed from the PERSISTED
@@ -835,14 +1077,18 @@ export class CliLifecycle {
835
1077
  const requester = FixDispositions.requesterInputOf(this.#scene.ledger.recordsOf(frame.key, frame.type), frame.round, this.#reviewsPath(frame), this.#repoRootValue().absolute);
836
1078
  if (requester.kind !== "read")
837
1079
  return undefined;
838
- const counts = new FixDispositions().summaryOf(carrier, requester.summaries);
1080
+ const counts = new FixDispositions().summaryOf(carrier, requester.findings);
839
1081
  return FIX_DISPOSITIONS_SUMMARY.replace("{fixed}", String(counts.fixed)).replace("{rejected}", String(counts.rejected));
840
1082
  }
841
1083
  /** The requesting review carrier's path — the fix round's `--reviews` input, or the
842
1084
  * ledger's resolved review handoff path when the route carried none (the ONE
843
1085
  * resolution the round context's INPUT_REVIEWS and the disposition summary share).
844
- * A migrated line resolves the carrier that EXISTS — the retired twin's name, never
845
- * the never-minted canonical spelling.
1086
+ * Four layers, ONE identity (P31 §2.3): the explicit `--reviews` flag → the
1087
+ * same-cycle review record's own `carrierPath` (the FINAL carrier the round wrote) →
1088
+ * the ledger's resolved family name (a draft, or a migrated line's retired twin —
1089
+ * the carrier that EXISTS, never the never-minted canonical spelling) → the legacy
1090
+ * `null`. Record-present means final-wins: a draft sitting beside the final never
1091
+ * becomes the judged input.
846
1092
  *
847
1093
  * A same-cycle review record that RECORDED no carrier path, with no carrier at
848
1094
  * either spelling on disk, leaves the requester input UNRECORDED: the answer is
@@ -853,6 +1099,9 @@ export class CliLifecycle {
853
1099
  #reviewsPath(frame) {
854
1100
  if (this.#reviews !== null)
855
1101
  return this.#reviews;
1102
+ const recorded = this.#requesterRecord(frame)?.carrierPath;
1103
+ if (typeof recorded === "string" && recorded !== "")
1104
+ return recorded;
856
1105
  const resolved = this.#scene.ledger.resolveHandoffPath("review", frame.type, frame.params);
857
1106
  if (existsSync(resolved))
858
1107
  return resolved;
@@ -861,6 +1110,136 @@ export class CliLifecycle {
861
1110
  .some((record) => record.op === "review" && record.cycle === frame.round && record.carrierPath === null);
862
1111
  return legacy ? null : resolved;
863
1112
  }
1113
+ /** The same-cycle review record this fix round answers — its LATEST attempt (a
1114
+ * re-dispatched review supersedes its predecessor, the same rule the round-read gate
1115
+ * applies). Null when the line records no review for this cycle. ONE basis for the
1116
+ * requesting carrier's path and its digest. */
1117
+ #requesterRecord(frame) {
1118
+ const reviewed = this.#scene.ledger
1119
+ .recordsOf(frame.key, frame.type)
1120
+ .filter((record) => record.op === "review" && record.cycle === frame.round);
1121
+ return reviewed.reduce((newest, record) => (newest === null || record.attempt >= newest.attempt ? record : newest), null);
1122
+ }
1123
+ /** The fix input's carrier-integrity gate — the `carrier-mismatch` refusal when the
1124
+ * requesting review carrier no longer digests to the value its round recorded, null
1125
+ * when the round may proceed (P31 §2.2). Only the fix face reads a carrier that
1126
+ * already existed before this dispatch (`INPUT_REVIEWS` is its own input), so every
1127
+ * other phase has no gate to set. A carrier with no recorded digest — a legacy round,
1128
+ * or a resolved path no record declared — is read as present facts: no comparison,
1129
+ * no refusal. */
1130
+ #carrierRefusal(frame) {
1131
+ if (this.#opOf(frame) !== "fix")
1132
+ return null;
1133
+ const carrier = this.#reviewsPath(frame);
1134
+ if (carrier === null)
1135
+ return null;
1136
+ const digest = this.#requesterDigest(frame);
1137
+ if (digest === null)
1138
+ return null;
1139
+ try {
1140
+ CarrierIntegrity.read(path.resolve(this.#repoRootValue().absolute, carrier), digest);
1141
+ return null;
1142
+ }
1143
+ catch (raw) {
1144
+ if (raw instanceof CarrierMismatchError)
1145
+ return raw.message;
1146
+ throw raw;
1147
+ }
1148
+ }
1149
+ /** The digest the requesting review round recorded — the same-cycle review record's
1150
+ * latest attempt (the round `#reviewsPath` resolves). Null when no record carries
1151
+ * one: the present-facts read. */
1152
+ #requesterDigest(frame) {
1153
+ return this.#requesterRecord(frame)?.carrierDigest ?? null;
1154
+ }
1155
+ /** The fix round's ruling sidecar as the round-context value — the repo-relative
1156
+ * sidecar path when a conforming sidecar sits beside the requesting carrier, plus the
1157
+ * ruling bodies it carries, the empty string otherwise (off the fix face, with no
1158
+ * resolved carrier, and when the sidecar is absent — the assembler drops the empty
1159
+ * line). The strict judgment is the dispatch gate's `#rulingsRefusal`; this cell
1160
+ * names the file the round may read AND states the verdicts (§2.5 AC: the rendered
1161
+ * text matches the sidecar), so a ruling is never merely a path the child must
1162
+ * re-open to discover. */
1163
+ #rulingsInputOf(frame) {
1164
+ if (this.#opOf(frame) !== "fix")
1165
+ return "";
1166
+ const carrier = this.#reviewsPath(frame);
1167
+ if (carrier === null)
1168
+ return "";
1169
+ const verdict = this.#rulingsVerdict(frame, carrier);
1170
+ if (verdict.kind !== "ok")
1171
+ return "";
1172
+ const sidecar = this.#rel(CarrierRulings.pathFor(carrier));
1173
+ return [sidecar, ...verdict.rulings.map((ruling) => this.#rulingLine(ruling))].join("\n");
1174
+ }
1175
+ /** One rendering of a recorded ruling — the finding id it answers and the ruling's
1176
+ * own text VERBATIM (never re-worded: the sidecar is the orchestrator's words, and
1177
+ * the round context quotes them). Indented under the sidecar path's bullet so the
1178
+ * cell reads as one input. */
1179
+ #rulingLine(ruling) {
1180
+ return ` - \`${ruling.finding}\` — ${ruling.ruling}`;
1181
+ }
1182
+ /** The pre-dispatch ruling gate — the strict sidecar verdict's refusal reason, or null
1183
+ * when the round may proceed (no fix face, no resolved carrier, an absent sidecar, or
1184
+ * a conforming one). A refusal is HARD and lands before the in-flight record and the
1185
+ * child, so a broken ruling set can never be dispatched unnoticed (§2.6).
1186
+ *
1187
+ * A `carrier-mismatch` from the sidecar's id read is the integrity refusal, never a
1188
+ * ruling reason: a tampered carrier is not judged (its id set is not a fact this
1189
+ * round may read), so the diagnostic names the bytes that changed. */
1190
+ #rulingsRefusal(frame) {
1191
+ if (this.#opOf(frame) !== "fix")
1192
+ return null;
1193
+ const carrier = this.#reviewsPath(frame);
1194
+ if (carrier === null)
1195
+ return null;
1196
+ let verdict;
1197
+ try {
1198
+ verdict = this.#rulingsVerdict(frame, carrier);
1199
+ }
1200
+ catch (raw) {
1201
+ if (!(raw instanceof CarrierMismatchError))
1202
+ throw raw;
1203
+ return raw.message;
1204
+ }
1205
+ return verdict.kind === "invalid" ? `rulings sidecar — ${verdict.reason}` : null;
1206
+ }
1207
+ /** The strict sidecar verdict over the requesting carrier's CHECKED id set — one call
1208
+ * shape for the gate and the round-context cell, so neither can read the ids by a
1209
+ * path the other does not take. */
1210
+ #rulingsVerdict(frame, carrier) {
1211
+ return CarrierRulings.verdict(carrier, this.#carrierFindingIds(frame, carrier));
1212
+ }
1213
+ /** The requesting carrier's engine-written finding ids (`F1`, `F2` …) — the id set a
1214
+ * ruling must name. The read is the ONE checked carrier read (`CarrierIntegrity.read`,
1215
+ * the digest its review round recorded): a tampered carrier is never observed at all —
1216
+ * the mismatch throws and the integrity refusal wins over any ruling reason. An absent
1217
+ * or unparseable carrier declares no ids, so any ruling beside it is refused by the
1218
+ * strict schema instead of being accepted against an empty set. */
1219
+ #carrierFindingIds(frame, carrier) {
1220
+ const ids = new Set();
1221
+ let carrierJson;
1222
+ try {
1223
+ const bytes = CarrierIntegrity.read(path.resolve(this.#repoRootValue().absolute, carrier), this.#requesterDigest(frame));
1224
+ if (bytes === null)
1225
+ return ids;
1226
+ carrierJson = JSON.parse(bytes);
1227
+ }
1228
+ catch (raw) {
1229
+ if (raw instanceof CarrierMismatchError)
1230
+ throw raw;
1231
+ return ids;
1232
+ }
1233
+ const findings = carrierJson?.findings;
1234
+ if (!Array.isArray(findings))
1235
+ return ids;
1236
+ for (const finding of findings) {
1237
+ const id = finding?.id;
1238
+ if (typeof id === "string")
1239
+ ids.add(id);
1240
+ }
1241
+ return ids;
1242
+ }
864
1243
  /** The read-back rejection face — CDD_BLOCKED reason + the crash record (the
865
1244
  * same-command resume's decision source: the attempted handoff + the resume
866
1245
  * command) + NO carrier (the bookkeep leaves the draft untouched). The crash
@@ -900,6 +1279,11 @@ export class CliLifecycle {
900
1279
  // failure is named, never a silent absence (§3.3). The cause rides the death facts'
901
1280
  // existing vocabulary (no new enum row).
902
1281
  const violations = [RoundViolation.hard(reason, cause)];
1282
+ // P31 T5 §2.4 — the death face seals the round's own names: the draft the child may
1283
+ // have written before it died, and the final the round never materialized. A seal
1284
+ // here keeps the failure face from leaving the writable window open for whatever
1285
+ // the late-landing child still tries to write.
1286
+ this.#sealRoundCarriers(frame);
903
1287
  if (death.termination === null)
904
1288
  return { status: "BLOCKED", violations };
905
1289
  return { status: "TIMEOUT", termination: death.termination, violations };
@@ -1076,10 +1460,16 @@ export class CliLifecycle {
1076
1460
  }
1077
1461
  return Object.keys(out).length > 0 ? out : undefined;
1078
1462
  }
1079
- /** The draft findings as a plain list (the materialized carrier keeps them
1080
- * verbatim; the schema validated their shape before this ran). */
1463
+ /** The draft findings as the carrier's list — the child's rows kept VERBATIM except
1464
+ * for the ONE engine-owned column: `id`, stamped from the carrier position (`F1`,
1465
+ * `F2` …) and overwriting whatever the child wrote (P30 §2.5 — the disposition
1466
+ * primary key belongs to the engine, never to the audited prose). This is the only
1467
+ * write point of a finding id in the engine. */
1081
1468
  #findingsList(findings) {
1082
- return Array.isArray(findings) ? findings : [];
1469
+ const rows = Array.isArray(findings) ? findings : [];
1470
+ return rows.map((row, index) => typeof row === "object" && row !== null && !Array.isArray(row)
1471
+ ? { ...row, id: `F${index + 1}` }
1472
+ : row);
1083
1473
  }
1084
1474
  /** The same-command resume string — the crash record's `next`, mirroring the
1085
1475
  * CLI's dispatchable form of this frame (re-run the same command per the BLOCKED
@@ -1106,7 +1496,12 @@ export class CliLifecycle {
1106
1496
  // the retained `--spec` flag.
1107
1497
  return `cdd review --type ${frame.type} --spec ${this.#docOf(frame)}`;
1108
1498
  case "fix": {
1109
- const findings = scene.ledger.resolveHandoffPath("review", frame.type, frame.params);
1499
+ // The `--reviews` input is the SAME carrier the fix prompt names (P31 §2.3): one
1500
+ // four-layer resolution, never a second family spelling spliced here. The
1501
+ // fallback fires only when the recorded face resolves to `null` (a legacy record
1502
+ // with no carrier on disk) — the never-null guard keeps a command shape.
1503
+ const findings = this.#reviewsPath(frame) ??
1504
+ scene.ledger.resolveHandoffPath("review", frame.type, frame.params);
1110
1505
  const target = frame.target.kind === "plan"
1111
1506
  ? `--plan ${frame.target.doc}`
1112
1507
  : frame.target.kind === "spec"
@@ -69,7 +69,7 @@ export class Preview {
69
69
  /** The read-only held block — the in-flight gate REFUSED this dispatch: the preview
70
70
  * renders the gate's own holder facts as a `lock:` row (the dead holder carries the
71
71
  * takeover hint), exits 1 at the caller, and touches nothing: no acquire, no steal,
72
- * no release. The `--steal-stale` flag has no write channel here. */
72
+ * no release. The `--recover` flag has no write channel here. */
73
73
  heldBlock(verb, state) {
74
74
  const lines = [`cdd ${verb}: preview (no repo changes)`, ` lock: ${this.#lockValueOf(state)}`];
75
75
  if (state.kind === "held" && !state.alive)
@@ -113,7 +113,7 @@ export const CAPSULE_WORDS = {
113
113
  inFlight: {
114
114
  free: "free — no dispatch holds this tree",
115
115
  held: "held — pid {pid}",
116
- stale: "stale holder — pid {pid} (re-run with --steal-stale to take over)",
116
+ stale: "stale holder — pid {pid} (re-run with --recover to take over)",
117
117
  corruptLocked: "unreadable record — lock on disk",
118
118
  corruptUnlocked: "unreadable record — no lock behind",
119
119
  },
@@ -133,9 +133,9 @@ export const CAPSULE_WORDS = {
133
133
  * corrupt shapes and the three canonical recovery sentences. */
134
134
  inFlight: {
135
135
  held: "a dispatch is already in flight — pid {pid} · command: {command} · started: {startedAt} · running for {uptime} · wave: {wave} · slug: {slug}",
136
- stealable: "the holding process is gone — re-run the same command with --steal-stale to take the in-flight record over",
137
- corruptLocked: "the in-flight record is unreadable and its lock is still on disk — re-run with --steal-stale to take it over",
138
- corruptUnlocked: "the in-flight record is unreadable and no lock is left behind — re-run with --steal-stale to take it over",
136
+ stealable: "the holding process is gone — re-run the same command with --recover to take the in-flight record over",
137
+ corruptLocked: "the in-flight record is unreadable and its lock is still on disk — re-run with --recover to take it over",
138
+ corruptUnlocked: "the in-flight record is unreadable and no lock is left behind — re-run with --recover to take it over",
139
139
  lockHeld: "held by pid {pid} · command: {command} · started: {startedAt} · wave: {wave} · slug: {slug}",
140
140
  lockOnly: "held by an unreadable in-flight record — the lock is still on disk",
141
141
  free: "free — no dispatch holds this tree",