@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.
@@ -88,7 +88,10 @@ export class DispatchAuthority {
88
88
  : `${reason} · ${render.detail}`;
89
89
  }
90
90
  const command = render.command === undefined ? "" : render.command(verdict.next);
91
- return `${reason} · next: ${command}`;
91
+ // The reopen flag rides the command the renderer produced — the SAME review
92
+ // command, one flag added (`--recover`), never a second literal (P30 §2.3).
93
+ const recover = verdict.recover === true ? " --recover" : "";
94
+ return `${reason} · next: ${command}${recover}`;
92
95
  }
93
96
  /** The structure leg's verdict — the seam's refusal re-expressed as this chain's
94
97
  * first row. Its token is the refusing gate's own id (the table's structure rows:
@@ -210,9 +213,10 @@ export class DispatchAuthority {
210
213
  const ruling = request.type === "wave" ? this.#waveRuling(request) : this.#docRuling(request);
211
214
  if (ruling.kind === "allowed")
212
215
  return { allowed: true };
213
- const next = this.#hopOf(request.line);
216
+ const next = ruling.kind === "row" && ruling.hop !== undefined ? ruling.hop : this.#hopOf(request.line);
214
217
  const reason = ruling.kind === "row" ? ruling.reason : next.reason;
215
- return this.#refusal("line", reason, next, request.line);
218
+ const recover = ruling.kind === "row" ? ruling.recover : undefined;
219
+ return this.#refusal("line", reason, next, request.line, recover);
216
220
  }
217
221
  /** One refusal, with its drift diagnosis attached when the reason is a drift token
218
222
  * (§2.5 — one construction point, so no refusal has a second path to print by). The
@@ -220,13 +224,16 @@ export class DispatchAuthority {
220
224
  * second lookup of which line moved. It is absent exactly when the target records no
221
225
  * pair — a diagnosis never invents a fact, so an underivable identity prints the
222
226
  * bare token. */
223
- #refusal(leg, reason, next, facts) {
227
+ #refusal(leg, reason, next, facts, recover) {
224
228
  const drift = _a.#isDriftReason(reason)
225
229
  ? _a.#driftOf(next, facts)
226
230
  : undefined;
227
- return drift === undefined
228
- ? { allowed: false, leg, reason, next }
229
- : { allowed: false, leg, reason, next, drift };
231
+ const base = { allowed: false, leg, reason, next };
232
+ return {
233
+ ...base,
234
+ ...(drift === undefined ? {} : { drift }),
235
+ ...(recover === true ? { recover: true } : {}),
236
+ };
230
237
  }
231
238
  /** Whether a token names a moved reviewed identity — the two rows whose refusal line
232
239
  * must carry the diagnosis (§2.5). */
@@ -321,9 +328,15 @@ export class DispatchAuthority {
321
328
  return { kind: "allowed" };
322
329
  }
323
330
  // A pending fix is the line's own row: the fix it awaits is a present fact, and
324
- // the refusal names it whatever the requested verb was.
325
- if (phase.phase === "fix")
326
- return { kind: "row", reason: DISPATCH_REASON.pendingFix.token };
331
+ // the refusal names it whatever the requested verb was. On a DRIFTED line the same
332
+ // row is reopenable — the `next:` is then the review round the `--recover` flag
333
+ // reopens (P30 §2.3), never the fix the old design already outran.
334
+ if (phase.phase === "fix") {
335
+ const reopen = _a.#reopenHop(facts, request.type);
336
+ return reopen === null
337
+ ? { kind: "row", reason: DISPATCH_REASON.pendingFix.token }
338
+ : { kind: "row", reason: DISPATCH_REASON.pendingFix.token, recover: true, hop: reopen };
339
+ }
327
340
  if (phase.phase !== null)
328
341
  return { kind: "hop" };
329
342
  // The closed line: the doc shapes name their unchanged reviewed identity (the
@@ -334,6 +347,41 @@ export class DispatchAuthority {
334
347
  reason: unchanged ? DISPATCH_REASON.unchanged.token : DISPATCH_REASON.faceClosed.token,
335
348
  };
336
349
  }
350
+ /** Whether the line sits at the REOPENABLE face — `reviewGate` open (the document
351
+ * drifted past what the review bound) AND a fix still owed (P30 §2.3's condition
352
+ * pair ①②). Read from the ledger's own derivations (`reviewGate` · `pendingFix`),
353
+ * never a second walk: the refusal's `--recover` hint and the CLI's reopen leg judge
354
+ * the same pair. */
355
+ static #reopenable(facts, type) {
356
+ const { lineKey: key, doc, ledger } = facts;
357
+ if (key === null || doc === null)
358
+ return false;
359
+ if (type === "wave")
360
+ return false;
361
+ return ledger.reviewGate(key, doc, type).kind === "open" && ledger.pendingFix(key, type);
362
+ }
363
+ /** The reopenable line's REVIEW hop — the round `--recover` makes dispatchable, built
364
+ * through the ONE hop assembly (`Ledger#nextHopOf`) so the refusal's `next:` is the
365
+ * same command the capsule and the board render (P30 §2.3). Null when the line is
366
+ * not reopenable (the refusal then keeps the frontier's own hop). */
367
+ static #reopenHop(facts, type) {
368
+ if (!_a.#reopenable(facts, type))
369
+ return null;
370
+ const { lineKey: key, doc } = facts;
371
+ if (key === null || doc === null)
372
+ return null;
373
+ // The render target's own shape (a branch line carries its plan as `plan`, every
374
+ // doc shape carries the document as `id`) — the frontier's own construction.
375
+ const target = type === "branch" ? { type: "branch", id: "branch", plan: doc } : { type, id: doc };
376
+ return facts.ledger.nextHopOf({
377
+ type,
378
+ key,
379
+ route: { kind: "review" },
380
+ target,
381
+ doc,
382
+ docClassOf: facts.docClassOf,
383
+ });
384
+ }
337
385
  /** The phase the requested verb dispatches on this face — the review verb asks for
338
386
  * the face's OWN review lead (the branch line's `branch-review`). */
339
387
  #expectedPhase(type, verb) {
@@ -28,11 +28,18 @@
28
28
  // behavior-carrying bare functions (the plan's zero-bare-function discipline).
29
29
  /** One finding row — the shared base declaration of the judge plane (severity +
30
30
  * lens + summary required; the extra review columns — section / line / fix — are
31
- * declared optional, and unknown extra fields ride along). */
31
+ * declared optional, and unknown extra fields ride along).
32
+ *
33
+ * `id` is declared OPTIONAL on purpose (P30 §2.5): the engine writes the stable key
34
+ * (`F1`, `F2` … in carrier order) at materialize and overwrites whatever the child
35
+ * put there, so the prompt shows the field exists while the child owes nothing. A
36
+ * required `id` would push an engine-owned value onto the child and add a pointless
37
+ * read-back BLOCK face for a field the engine always rewrites. */
32
38
  const FINDING = {
33
39
  type: "object",
34
40
  required: ["severity", "lens", "summary"],
35
41
  properties: {
42
+ id: { type: "string" },
36
43
  severity: { type: "string", enum: ["blocker", "warn", "nit"] },
37
44
  lens: { type: "string" },
38
45
  section: { type: "string" },
@@ -29,6 +29,7 @@
29
29
  //
30
30
  // Module-level exports are types / the error class / the class — zero
31
31
  // behavior-carrying bare functions.
32
+ var _a;
32
33
  import { existsSync, mkdirSync, readFileSync, rmSync } from "node:fs";
33
34
  import path from "node:path";
34
35
  import lockfile from "proper-lockfile";
@@ -63,6 +64,15 @@ export class InFlight {
63
64
  static LOCK_STALE_MS = 12 * 60 * 60 * 1000;
64
65
  /** The lock's refresh interval (ms). */
65
66
  static LOCK_UPDATE_MS = 60 * 1000;
67
+ /** The three takeover reasons of a stale tree — ONE literal per morphology (spec
68
+ * §2.1①: a dead holder, a corrupt record with a leftover lock, a lock with no record
69
+ * behind it). Shared by `acquire({ recover })`'s pre-step and the abort fold, so a
70
+ * takeover can never be named two ways. */
71
+ static STEAL_REASON = {
72
+ deadHolder: "the holder is dead",
73
+ corruptRecord: "the record is corrupt and the lock is left behind",
74
+ lockOnly: "a lock without a record",
75
+ };
66
76
  #root;
67
77
  #slug;
68
78
  #liveness;
@@ -76,7 +86,7 @@ export class InFlight {
76
86
  }
77
87
  /** The record's absolute path (`<workspaceRoot>/in-flight.json`). */
78
88
  path() {
79
- return path.join(this.#root.path, InFlight.FILE);
89
+ return path.join(this.#root.path, _a.FILE);
80
90
  }
81
91
  /** The lock directory's absolute path (`proper-lockfile`'s default carrier). */
82
92
  lockPath() {
@@ -96,19 +106,19 @@ export class InFlight {
96
106
  * → live-holder guard → lock → record. The guard is the class's OWN fail-closed
97
107
  * check that a standing record is never displaced while its holder lives: the
98
108
  * pre-flight gate is the primary guard, this one keeps the invariant true for any
99
- * other write point. `stealStale` only acts HERE: a standing record whose holder is
109
+ * other write point. `recover` only acts HERE: a standing record whose holder is
100
110
  * dead (or a corrupt record with a leftover lock) is taken over first; a live holder
101
111
  * is never displaced. A failed lock throws `HoldingError` carrying the holder's
102
112
  * facts and leaves the record bytes untouched. */
103
113
  async acquire(record, options = {}) {
104
114
  this.ensureMarker();
105
- if (options.stealStale === true)
115
+ if (options.recover === true)
106
116
  await this.#stealIfDead();
107
117
  await this.#refuseLiveHolder();
108
118
  try {
109
119
  this.#unlock = await lockfile.lock(this.path(), {
110
- stale: InFlight.LOCK_STALE_MS,
111
- update: InFlight.LOCK_UPDATE_MS,
120
+ stale: _a.LOCK_STALE_MS,
121
+ update: _a.LOCK_UPDATE_MS,
112
122
  realpath: false,
113
123
  retries: 0,
114
124
  });
@@ -187,7 +197,22 @@ export class InFlight {
187
197
  return { kind: "absent" };
188
198
  return { kind: "corrupt", locked: existsSync(this.lockPath()) };
189
199
  }
190
- /** Take the record over explicitly — the `--steal-stale` path. The precondition is
200
+ /** The tree's STALE in-flight — the three takeover morphologies of spec §2.1①
201
+ * define the answer, so every reader names the same stale face: a dead holder's
202
+ * readable record, a corrupt record with a leftover lock, or a lock with no record
203
+ * behind it. Null when the tree is FREE or a LIVE holder stands (a live holder is
204
+ * never displaced). ONE predicate for `acquire({ recover })`'s pre-step, the abort
205
+ * fold and the composition root's reopen judgment — a stale tree can never be
206
+ * named two ways. */
207
+ async staleState() {
208
+ const state = await this.inspect();
209
+ if (state.kind === "held")
210
+ return state.alive ? null : state;
211
+ if (state.kind === "corrupt")
212
+ return state.locked ? state : null;
213
+ return existsSync(this.lockPath()) ? state : null;
214
+ }
215
+ /** Take the record over explicitly — the `--recover` path. The precondition is
191
216
  * that the holder cannot be alive: a readable record whose pid is live is refused
192
217
  * (the flag never crosses "alive → no takeover"); a corrupt record has no live
193
218
  * fact to honor and is cleared. Clears the lock, then the record. */
@@ -209,22 +234,21 @@ export class InFlight {
209
234
  rmSync(this.path(), { force: true });
210
235
  return record;
211
236
  }
212
- /** The `stealStale` pre-step of acquire: take over a standing record whose holder is
237
+ /** The `recover` pre-step of acquire: take over a standing record whose holder is
213
238
  * dead, a corrupt record with a leftover lock, or a lock remnant with no record —
214
- * and do nothing while the holder is alive (the lock then refuses the acquire). */
239
+ * and do nothing while the holder is alive (the lock then refuses the acquire).
240
+ * The morphology predicate is `staleState()`; this only names the takeover. */
215
241
  async #stealIfDead() {
216
- const state = await this.inspect();
217
- if (state.kind === "held" && !state.alive) {
218
- await this.steal("the holder is dead");
242
+ const stale = await this.staleState();
243
+ if (stale === null)
219
244
  return;
220
- }
221
- if (state.kind === "corrupt" && state.locked) {
222
- await this.steal("the record is corrupt and the lock is left behind");
245
+ if (stale.kind === "held") {
246
+ await this.steal(_a.STEAL_REASON.deadHolder);
223
247
  return;
224
248
  }
225
- if (state.kind === "absent" && existsSync(this.lockPath())) {
226
- await this.steal("a lock without a record");
227
- }
249
+ await this.steal(stale.kind === "corrupt"
250
+ ? _a.STEAL_REASON.corruptRecord
251
+ : _a.STEAL_REASON.lockOnly);
228
252
  }
229
253
  /** The refusal message — the holder's identity facts as plain text (the words
230
254
  * table owns the CLI's held report; this is the thrown carrier's own summary). */
@@ -232,7 +256,7 @@ export class InFlight {
232
256
  if (holder === null) {
233
257
  return `another dispatch holds the in-flight lock under ${this.#root.path} — the standing record is unreadable (dispatch ${this.#slug} refuses to overwrite it)`;
234
258
  }
235
- return `another dispatch is in flight: pid ${holder.pid} (${holder.command}), slug ${holder.slug}, started ${new Date(holder.startedAt).toISOString()} — it must finish, or its record must be taken over with --steal-stale`;
259
+ return `another dispatch is in flight: pid ${holder.pid} (${holder.command}), slug ${holder.slug}, started ${new Date(holder.startedAt).toISOString()} — it must finish, or its record must be taken over with --recover`;
236
260
  }
237
261
  /** The record write — the JSON shape through the ONE atomic write seam, with the
238
262
  * repo's single trailing newline. */
@@ -275,8 +299,10 @@ export class InFlight {
275
299
  attempt: typeof row.attempt === "number" ? row.attempt : null,
276
300
  briefHash: typeof row.briefHash === "string" ? row.briefHash : null,
277
301
  plan: typeof row.plan === "string" ? row.plan : null,
302
+ dispatchBase: typeof row.dispatchBase === "string" ? row.dispatchBase : null,
278
303
  sampledAt: typeof row.sampledAt === "number" ? row.sampledAt : null,
279
304
  verdict: typeof row.verdict === "string" ? row.verdict : null,
280
305
  };
281
306
  }
282
307
  }
308
+ _a = InFlight;
@@ -24,7 +24,9 @@ var _a;
24
24
  import { createHash } from "node:crypto";
25
25
  import { readdirSync, readFileSync } from "node:fs";
26
26
  import { DocBodyProjection } from "../contract/doc-body.js";
27
+ import { CarrierSeal } from "../infra/carrier-seal.js";
27
28
  import { BriefRenderer } from "../render/brief.js";
29
+ import { CarrierIntegrity } from "./carrier-integrity.js";
28
30
  import { targetFaces } from "./faces.js";
29
31
  import { HandoffSchema } from "./handoff-schema.js";
30
32
  import { LineIdentity } from "./line-identity.js";
@@ -245,9 +247,10 @@ export class Ledger {
245
247
  return this.#basis().resolve(this.#basis().relativize(value));
246
248
  }
247
249
  // ---- the single author's write/read primitives ----
248
- /** Persist a JSON artifact — the ledger's single write point (engine sole author). */
250
+ /** Persist a JSON artifact — the ledger's single write point (engine sole author).
251
+ * Returns the digest of the written bytes (the carrier record's `carrierDigest`). */
249
252
  #persist(name, data) {
250
- this.#workspace.writeJson(name, data);
253
+ return this.#workspace.writeJsonHashed(name, data);
251
254
  }
252
255
  /** Read a JSON artifact; null when missing/corrupt (the ledger's read face keeps the
253
256
  * collapsed contract — the tri-state discrimination lives at the read-back
@@ -385,6 +388,11 @@ export class Ledger {
385
388
  verdict: init.verdict ?? { treeClean: true, targetAction: true },
386
389
  violations: init.violations ?? [],
387
390
  carrierPath: init.carrierPath ?? null,
391
+ // The digest column exists only on rounds that recorded one (a legacy record
392
+ // keeps no key at all — the read then compares nothing, zero migration).
393
+ ...(init.carrierDigest === undefined ? {} : { carrierDigest: init.carrierDigest }),
394
+ // …and the same for the draft path column (P31 §2.3).
395
+ ...(init.draftPath === undefined ? {} : { draftPath: init.draftPath }),
388
396
  };
389
397
  const existing = records.findIndex((candidate) => candidate.op === record.op &&
390
398
  candidate.cycle === record.cycle &&
@@ -617,9 +625,13 @@ export class Ledger {
617
625
  // The fix-awaited face — a drifted wave BRIEF reopens at review (D30/D16), else fix.
618
626
  if (this.briefDrifted(waveKey))
619
627
  return { kind: "review" };
628
+ // The `--reviews` identity is the ROUTE's own (P31 §2.3): the round read resolves
629
+ // the FINAL carrier the record names, so a draft beside it never becomes the input
630
+ // — the board's `next:` and the dispatch's read the same file by construction.
620
631
  return {
621
632
  kind: "fix",
622
- reviews: this.handoffPath("review", "wave", { tasks: waveKey, round: latestReview }),
633
+ reviews: route.reviews ??
634
+ this.resolveHandoffPath("review", "wave", { tasks: waveKey, round: latestReview }),
623
635
  };
624
636
  }
625
637
  return null;
@@ -688,7 +700,10 @@ export class Ledger {
688
700
  * (a recorded round is a present fact — the same-doc re-review stays refused until
689
701
  * its fix lands). A completed fix (the latest review cycle IS in the fix
690
702
  * completion set) is NOT the pending face — the completed-fix line's re-review
691
- * reopens through the fix round's C5 route (the legacy judgment). */
703
+ * reopens through the fix round's C5 route (the legacy judgment).
704
+ *
705
+ * A SUPERSEDED review (P30 §2.3) is not a candidate: the reopen replaced its
706
+ * judgment, so the fix it awaited is no longer owed. */
692
707
  #pendingFix(key, type) {
693
708
  const data = this.readProgress();
694
709
  if (data === null)
@@ -696,7 +711,7 @@ export class Ledger {
696
711
  const row = _a.rowFor(data, key, type);
697
712
  if (row === undefined)
698
713
  return false;
699
- const reviews = this.#latestCompletedCycleOfRow(row, "review");
714
+ const reviews = this.#latestLiveCycleOfRow(row, "review");
700
715
  if (reviews === 0)
701
716
  return false;
702
717
  if (this.#completedCyclesOfRow(row, "fix").includes(reviews))
@@ -707,6 +722,12 @@ export class Ledger {
707
722
  // stores no status field · D27), never a second read of the carrier here.
708
723
  return carried === null || carried.status === undefined || carried.status !== "APPROVED";
709
724
  }
725
+ /** The line's derived pending-fix fact — the PUBLIC read face of `#pendingFix`
726
+ * (the `--recover` reopen's condition ②, P30 §2.3). One derivation, two readers;
727
+ * never a second walk from the face. */
728
+ pendingFix(key, type) {
729
+ return this.#pendingFix(key, type);
730
+ }
710
731
  /** Read one counter — a failure-category count on record (0 when the file is
711
732
  * missing). The RETIRED key derives from the round records: the soft entries of
712
733
  * every row plus the one each dirty-tree observation derives (design spec §3.3) —
@@ -831,7 +852,7 @@ export class Ledger {
831
852
  if (row === undefined)
832
853
  return { kind: "review" };
833
854
  const reviewLead = targetFaces[type].product.reviewLead;
834
- const reviews = this.#latestCompletedCycleOfRow(row, reviewLead);
855
+ const reviews = this.#latestLiveCycleOfRow(row, reviewLead);
835
856
  if (reviews === 0)
836
857
  return { kind: "review" };
837
858
  if (!this.#completedCyclesOfRow(row, "fix").includes(reviews)) {
@@ -960,6 +981,44 @@ export class Ledger {
960
981
  const cycles = this.#completedCyclesOfRow(row, mode);
961
982
  return cycles.length > 0 ? Math.max(...cycles) : 0;
962
983
  }
984
+ /** The latest completed cycle of a row + mode that no later round SUPERSEDED — the
985
+ * active-hop read of a reopenable line (P30 §2.3: `--recover` replaced the old
986
+ * review's judgment, so it may no longer lead this line's hop). Deliberately a
987
+ * SEPARATE reader from `#latestCompletedCycleOfRow`: closure is a ledger-wide-order
988
+ * fact, and a supersede must never make a closed line look open (`#rowClosed` and the
989
+ * wave-line closure judgment keep the unfiltered read). 0 when none. */
990
+ #latestLiveCycleOfRow(row, mode) {
991
+ const op = RoundRecords.opOf(mode);
992
+ if (op === null)
993
+ return 0;
994
+ const cycles = RoundRecords.of(row)
995
+ .filter((record) => record.op === op && record.verdict.targetAction && record.supersededBy === undefined)
996
+ .map((record) => record.cycle);
997
+ return cycles.length > 0 ? Math.max(...cycles) : 0;
998
+ }
999
+ /** Stamp a completed review round as SUPERSEDED (P30 §2.3) — the `--recover` reopen'
1000
+ * s ONE write. It writes no fake completed fix: the old review keeps its own verdict
1001
+ * and gains `supersededBy: { cycle, cause: "recover" }`, and the fix identity stays
1002
+ * with its requesting review's cycle (D28 unchanged). Idempotent: a second stamp of
1003
+ * the same record is a no-op rewrite. Returns whether a completed review of that
1004
+ * cycle was stamped. */
1005
+ supersedeReview(key, type, cycle, byCycle) {
1006
+ const data = this.readProgress();
1007
+ if (data === null)
1008
+ return false;
1009
+ const row = _a.rowFor(data, key, type);
1010
+ if (row === undefined)
1011
+ return false;
1012
+ const records = [...RoundRecords.of(row)];
1013
+ const index = records.findIndex((record) => record.op === "review" && record.cycle === cycle && record.verdict.targetAction);
1014
+ const target = records[index];
1015
+ if (target === undefined)
1016
+ return false;
1017
+ records[index] = { ...target, supersededBy: { cycle: byCycle, cause: "recover" } };
1018
+ row.rounds = records;
1019
+ this.writeProgress(data);
1020
+ return true;
1021
+ }
963
1022
  /** One mode's completed cycles on a row — the row-level twin of `completedCycles`. */
964
1023
  #completedCyclesOfRow(row, mode) {
965
1024
  const op = RoundRecords.opOf(mode);
@@ -1011,11 +1070,40 @@ export class Ledger {
1011
1070
  carrier.findings = init.findings;
1012
1071
  return carrier;
1013
1072
  }
1014
- /** Persist a handoff payload at the canonical name — the single-author full-replace
1015
- * write (never a merge: the engine owns the file). Returns the written path. */
1073
+ /** Persist a handoff payload as the round's FINAL carrier — the engine's single-author
1074
+ * write, at a name the child's DRAFT never occupies (P31 §2.3). Returns the final
1075
+ * path (what the round is judged by), the draft path it landed beside, and the
1076
+ * payload's digest, so the round record can remember all three.
1077
+ *
1078
+ * The digest covers the PAYLOAD, never the file bytes that hold it: `H = sha256(JSON
1079
+ * containing H)` is unsatisfiable, so the value is taken BEFORE the `contentSha256`
1080
+ * key joins the payload — the key is appended LAST and the payload is written once
1081
+ * (the read recomputes by the same rule: drop the key, re-serialize, sha256). The
1082
+ * draft is neither written nor deleted here: it is the child's artifact, and the
1083
+ * final is the engine's answer to it.
1084
+ *
1085
+ * P31 §2.4 — the write CLOSES the carrier: the final and the draft name beside it
1086
+ * land at `0o444` in the same step, so a carrier is read-only from the instant the
1087
+ * engine authored it. A name that never landed (a round whose child wrote no draft,
1088
+ * a round-less family whose draft IS the final) is not an error — the seal is
1089
+ * idempotent and absence is the round's own fact. */
1016
1090
  persistHandoff(op, type, params, data) {
1017
- this.#persist(this.handoffName(op, type, params), data);
1018
- return this.handoffPath(op, type, params);
1091
+ const draftName = this.handoffName(op, type, params);
1092
+ const payload = { ...data };
1093
+ // The engine owns this key — a caller-supplied value never seeds a self-covering digest.
1094
+ delete payload.contentSha256;
1095
+ const digest = CarrierIntegrity.digestOf(payload);
1096
+ payload.contentSha256 = digest;
1097
+ const finalName = this.#naming.finalName(draftName, params.round);
1098
+ this.#persist(finalName, payload);
1099
+ // The carrier is read-only the moment it exists; the draft beside it closes with it.
1100
+ CarrierSeal.seal(this.#workspace.resolve(finalName));
1101
+ CarrierSeal.seal(this.#workspace.resolve(draftName));
1102
+ return {
1103
+ path: this.#workspace.resolve(finalName),
1104
+ draftPath: this.#workspace.resolve(draftName),
1105
+ digest,
1106
+ };
1019
1107
  }
1020
1108
  /** The handoff file NAME a read actually resolves — the canonical family name, or a
1021
1109
  * DOCUMENT line's retired `spec` twin when the canonical file is absent (the
@@ -1028,6 +1116,13 @@ export class Ledger {
1028
1116
  * spelling). */
1029
1117
  resolveHandoffName(op, type, params = {}) {
1030
1118
  const canonical = this.handoffName(op, type, params);
1119
+ // P31 §2.3 — the FINAL carrier wins the read whenever the round has one: it is the
1120
+ // round's finalized answer, and the draft beside it is the child's raw input (an
1121
+ // un-materialized payload whose findings carry no engine id). A round-less family
1122
+ // (implement) has one name only, so `final` equals the canonical spelling.
1123
+ const final = this.#naming.finalName(canonical, params.round);
1124
+ if (final !== canonical && this.#read(final) !== null)
1125
+ return final;
1031
1126
  if (!RETIRED_SPEC_LINE_KEYS.has(type) || this.#read(canonical) !== null) {
1032
1127
  return canonical;
1033
1128
  }
@@ -1046,9 +1141,55 @@ export class Ledger {
1046
1141
  * alias keys on the line's declared word (`phase-spec` / `overall` / `single-spec`,
1047
1142
  * the same basis as `rowFor`'s) and never covers the node shapes. Every WRITE goes
1048
1143
  * through `persistHandoff`'s current spelling — the alias is read-only, and the name
1049
- * it resolves is `resolveHandoffName`'s ONE answer. */
1144
+ * it resolves is `resolveHandoffName`'s ONE answer.
1145
+ *
1146
+ * P31 §2.2 — the read is CHECKED: the (op, type, round) round's latest recorded
1147
+ * attempt supplies the digest the engine wrote, and `CarrierIntegrity.read` compares
1148
+ * the bytes against it before they are parsed (a mismatch throws
1149
+ * `CarrierMismatchError`, never a silently-judged tampered carrier). A legacy record
1150
+ * with no digest — or no record at all — reads as present facts, zero comparison. */
1050
1151
  readHandoff(op, type, params) {
1051
- return this.#read(this.resolveHandoffName(op, type, params));
1152
+ const name = this.resolveHandoffName(op, type, params);
1153
+ const bytes = CarrierIntegrity.read(this.#workspace.resolve(name), this.#carrierDigestOf(op, type, params));
1154
+ if (bytes === null)
1155
+ return null;
1156
+ try {
1157
+ return JSON.parse(bytes);
1158
+ }
1159
+ catch {
1160
+ return null;
1161
+ }
1162
+ }
1163
+ /** The digest the round recorded for the carrier this read resolves — its LATEST
1164
+ * attempt of the (op, type, round) identity (a re-dispatch supersedes its
1165
+ * predecessor, the same rule the round-read gate applies). Null when no record
1166
+ * carries one: the present-facts face (legacy rows, and reads of a round that never
1167
+ * booked its own carrier). */
1168
+ #carrierDigestOf(op, type, params) {
1169
+ return this.#latestRecordOf(op, type, params)?.carrierDigest ?? null;
1170
+ }
1171
+ /** The latest recorded attempt of an (op, type, round) identity — null when the line
1172
+ * carries no record for it (a legacy row, or a round never dispatched). ONE basis for
1173
+ * every "what did that round record" question (the digest the read compares against,
1174
+ * the carrier path `--reviews` names). */
1175
+ #latestRecordOf(op, type, params) {
1176
+ const mode = RoundRecords.opOf(op) ?? op;
1177
+ const round = params.round === undefined ? null : Number(params.round);
1178
+ return this.recordsOf(this.#roundKey(type, params), type)
1179
+ .filter((record) => record.op === mode)
1180
+ .filter((record) => round === null || record.cycle === round)
1181
+ .reduce((newest, record) => (newest === null || record.attempt >= newest.attempt ? record : newest), null);
1182
+ }
1183
+ /** The review carrier a round's fix leg reads as `--reviews` — the round's OWN
1184
+ * recorded carrier path (the FINAL carrier, P31 §2.3) when the record names one, and
1185
+ * the resolved family name (the draft spelling — legacy rows, and a round that
1186
+ * persisted no carrier) otherwise. Record-present means final-wins: a draft sitting
1187
+ * beside a final never becomes the judged input. */
1188
+ #reviewsPathOf(type, params, round) {
1189
+ const recorded = this.#latestRecordOf("review", type, { ...params, round })?.carrierPath;
1190
+ if (typeof recorded === "string" && recorded !== "")
1191
+ return recorded;
1192
+ return this.resolveHandoffPath("review", type, { ...params, round });
1052
1193
  }
1053
1194
  /** The retired document-line carrier name of one round — `spec-review-{round}.json` /
1054
1195
  * `spec-fix-{round}.json`. It lives here, never in the family table: it is a read
@@ -1104,10 +1245,13 @@ export class Ledger {
1104
1245
  * `{line}-{op}-{round}.json`, plus a document line's retired `spec` twin (the
1105
1246
  * pre-rename name a still-unbooked draft can carry). Null for a non-handoff file. */
1106
1247
  static #handoffOwner(name, families) {
1248
+ // A FINAL carrier (`<stem>.c{round}.json`, P31 §2.3) is the same artifact as its
1249
+ // draft — the cycle is the name's own suffix, never a second family.
1250
+ const draft = name.replace(/\.c\d+\.json$/, ".json");
1107
1251
  for (const [family, record] of Object.entries(families)) {
1108
1252
  const [op = "", type = ""] = family.split(".");
1109
1253
  for (const spelling of _a.#familySpellings(record.name, type)) {
1110
- const captures = _a.#familyCaptures(spelling, name);
1254
+ const captures = _a.#familyCaptures(spelling, draft);
1111
1255
  if (captures === null)
1112
1256
  continue;
1113
1257
  const key = type === "wave" ? (captures.tasks ?? "") : type;
@@ -1261,7 +1405,7 @@ export class Ledger {
1261
1405
  // source shared with the fix leg below (`HandoffSchema.conclusionOf`).
1262
1406
  status: this.#handoffSchema.conclusionOf("judge", carrier),
1263
1407
  findings: this.#findingsOf(carrier),
1264
- reviewsPath: this.resolveHandoffPath("review", type, reviewParams),
1408
+ reviewsPath: this.#reviewsPathOf(type, params, round),
1265
1409
  consecutiveS1: this.#consecutiveS1Run(type, params, round),
1266
1410
  };
1267
1411
  }
@@ -1281,7 +1425,7 @@ export class Ledger {
1281
1425
  // work plane reads its status) — the same `conclusionOf` single source (D27).
1282
1426
  status: this.#handoffSchema.conclusionOf(this.planeOf("fix"), fixCarrier),
1283
1427
  findings: this.#findingsOf(reviewCarrier),
1284
- reviewsPath: this.resolveHandoffPath("review", type, reviewParams),
1428
+ reviewsPath: this.#reviewsPathOf(type, params, round),
1285
1429
  consecutiveS1: this.#consecutiveS1Run(type, params, round),
1286
1430
  };
1287
1431
  }
@@ -134,15 +134,16 @@ export const NEXT_HOP_REASON = {
134
134
  /** The review-cycle soft-cap suggestion (the C5-0 suggestion face — user adjudicates). */
135
135
  export const SOFT_CAP_SUGGESTION = "BLOCKED: review-cycle-cap — user adjudicates";
136
136
  /** The fix-route readback suffix — appended verbatim to the fix findings path on the
137
- * route's `next:` render (`(confirm the reviews handoff · if a finding needs a
138
- * ruling, record the ruling in the handoff file)`), a pure wording prompt: the
139
- * anti-blind-fix mechanical guard is the ledger round / C5-1, the suffix only
140
- * reminds the orchestrator to confirm the captured findings and, when a finding
141
- * needs a user ruling, record that ruling back into the reviews handoff the fix
142
- * round consumes. `annotate` names the carrier action alone — distinct from
143
- * `backfill` (a durable fact landed into its owning doc), which stays the
144
- * ruling's destination when it asserts a project-level fact. */
145
- export const FIX_READBACK_SUFFIX = "(confirm the reviews handoff · if a finding needs a ruling, record the ruling in the handoff file)";
137
+ * route's `next:` render (`(confirm the reviews handoff · if a finding needs a ruling,
138
+ * record it beside that handoff — same path with .json replaced by .rulings.json)`), a
139
+ * pure wording prompt: the anti-blind-fix mechanical guard is the ledger round / C5-1,
140
+ * the suffix only reminds the orchestrator to confirm the captured findings and, when a
141
+ * finding needs a user ruling, to record it in the SIDECAR beside the reviews handoff
142
+ * (the carrier's bytes are frozen — the ruling never edits them; P31 §2.1/§2.5).
143
+ * `annotate` names the carrier action alone — distinct from `backfill` (a durable fact
144
+ * landed into its owning doc), which stays the ruling's destination when it asserts a
145
+ * project-level fact. */
146
+ export const FIX_READBACK_SUFFIX = "(confirm the reviews handoff · if a finding needs a ruling, record it beside that handoff — same path with .json replaced by .rulings.json)";
146
147
  /** The failure face — a BLOCKED/TIMEOUT round goes the stderr CDD_BLOCKED channel and
147
148
  * produces no `next:` line on any op. Exported as the ONE failure-status set: the
148
149
  * skill-anatomy contract's `edgeConditionWords` derivation reads it to exclude the
@@ -79,7 +79,7 @@ export class PreFlight {
79
79
  gates.push("in-flight");
80
80
  const inFlight = await ctx.inflight.inspect();
81
81
  checked.push(this.#inFlightRow(inFlight));
82
- const held = this.#inFlightRefusal(inFlight, ctx.stealStale === true);
82
+ const held = this.#inFlightRefusal(inFlight, ctx.recover === true);
83
83
  if (held !== null) {
84
84
  return this.#refusal({
85
85
  ok: false,
@@ -223,9 +223,9 @@ export class PreFlight {
223
223
  }
224
224
  /** The in-flight gate's refusal — the three-state judgment + the explicit takeover
225
225
  * flag. A live holder is always refused (the flag never crosses "alive"); a dead
226
- * holder or a corrupt-record-with-lock passes only under `stealStale`; a corrupt
226
+ * holder or a corrupt-record-with-lock passes only under `recover`; a corrupt
227
227
  * record with no lock behind it is no holder at all (pass, named on the row). */
228
- #inFlightRefusal(state, stealStale) {
228
+ #inFlightRefusal(state, recover) {
229
229
  if (state.kind === "held") {
230
230
  if (state.alive) {
231
231
  return {
@@ -233,14 +233,14 @@ export class PreFlight {
233
233
  message: this.#words.inFlightBlocked(state.record, true),
234
234
  };
235
235
  }
236
- if (stealStale)
236
+ if (recover)
237
237
  return null;
238
238
  return {
239
239
  reason: "held",
240
240
  message: this.#words.inFlightBlocked(state.record, false),
241
241
  };
242
242
  }
243
- if (state.kind === "corrupt" && state.locked && !stealStale) {
243
+ if (state.kind === "corrupt" && state.locked && !recover) {
244
244
  return {
245
245
  reason: "corrupt-record",
246
246
  message: this.#words.inFlightWords().corruptLocked,