@oscaner-skills/cdd-engine 4.2.0 → 4.3.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.
Files changed (55) hide show
  1. package/README.md +38 -9
  2. package/README.zh-CN.md +43 -9
  3. package/dist/contract/completion-criterion.js +351 -0
  4. package/dist/contract/declare.js +181 -43
  5. package/dist/contract/doc.js +84 -271
  6. package/dist/contract/frontmatter.js +2 -1
  7. package/dist/contract/home-extractors.js +49 -316
  8. package/dist/contract/invariants.js +400 -296
  9. package/dist/contract/judge.js +74 -49
  10. package/dist/contract/lint.js +3 -2
  11. package/dist/contract/liveness-signal.js +103 -0
  12. package/dist/contract/markdown-document.js +410 -0
  13. package/dist/contract/markdown-tree-types.js +6 -0
  14. package/dist/contract/markdown-tree.js +137 -0
  15. package/dist/contract/project.js +1 -1
  16. package/dist/contract/rules.js +106 -0
  17. package/dist/contract/selector-engine.js +332 -0
  18. package/dist/contract/selector-spec.js +74 -0
  19. package/dist/contract/skill-anatomy.js +29 -1
  20. package/dist/contract/task-block-grammar.js +285 -0
  21. package/dist/contract/task-blocks.js +65 -0
  22. package/dist/contract/translate.js +21 -0
  23. package/dist/contract/wave-width.js +15 -0
  24. package/dist/face/board-view.js +401 -131
  25. package/dist/face/capsule.js +66 -89
  26. package/dist/face/cli.js +116 -35
  27. package/dist/face/declare.js +36 -18
  28. package/dist/face/gate.js +117 -40
  29. package/dist/face/init.js +1 -1
  30. package/dist/face/lifecycle.js +540 -123
  31. package/dist/face/preview.js +43 -10
  32. package/dist/face/route-render.js +51 -21
  33. package/dist/face/termination.js +135 -261
  34. package/dist/face/words.js +134 -12
  35. package/dist/infra/atomic.js +15 -0
  36. package/dist/infra/git.js +25 -0
  37. package/dist/infra/proc.js +150 -0
  38. package/dist/infra/round-log.js +104 -0
  39. package/dist/infra/runtime.js +16 -4
  40. package/dist/infra/workspace.js +7 -2
  41. package/dist/render/brief.js +15 -17
  42. package/dist/render/skeleton.js +41 -28
  43. package/dist/render/templates.js +128 -84
  44. package/dist/session/faces.js +47 -20
  45. package/dist/session/graph.js +13 -37
  46. package/dist/session/handoff-schema.js +16 -8
  47. package/dist/session/inflight.js +282 -0
  48. package/dist/session/ledger.js +581 -136
  49. package/dist/session/line-identity.js +33 -0
  50. package/dist/session/next.js +138 -80
  51. package/dist/session/preflight.js +276 -68
  52. package/dist/session/round-naming.js +56 -8
  53. package/dist/session/run.js +317 -78
  54. package/dist/session/wave.js +94 -14
  55. package/package.json +13 -3
@@ -22,23 +22,118 @@
22
22
  // carrying bare functions (the plan's zero-bare-function discipline).
23
23
  var _a;
24
24
  import { createHash } from "node:crypto";
25
- import { readFileSync } from "node:fs";
25
+ import { readdirSync, readFileSync } from "node:fs";
26
26
  import { BriefRenderer } from "../render/brief.js";
27
27
  import { targetFaces } from "./faces.js";
28
28
  import { HandoffSchema } from "./handoff-schema.js";
29
+ import { LineIdentity } from "./line-identity.js";
29
30
  import { NextStepRouter } from "./next.js";
31
+ import { RoundNaming } from "./round-naming.js";
30
32
  import { EMPTY_RUN_STATE } from "./run.js";
33
+ /** The graded-violation literals' ONE construction point — the cause vocabulary is
34
+ * a declared convergence point, so its shape is held here rather than copied per
35
+ * call site. `cause` defaults to `contract-violation`, the ledger's existing row
36
+ * for a self-authored entry; a death fact passes its own cause. */
37
+ export const RoundViolation = {
38
+ hard: (message, cause = "contract-violation") => ({
39
+ grade: "hard",
40
+ cause,
41
+ message,
42
+ }),
43
+ soft: (message, cause = "contract-violation") => ({
44
+ grade: "soft",
45
+ cause,
46
+ message,
47
+ }),
48
+ };
31
49
  // ---------------------------------------------------------------------------
32
50
  // progress — the fixed key set
33
51
  // ---------------------------------------------------------------------------
34
- /** The fixed counter key set — the five engine-config failure-category counters, verbatim. */
52
+ /** The fixed counter key set — the failure-category counters the engine still WRITES,
53
+ * verbatim. */
35
54
  export const PROGRESS_COUNTER_ZERO = {
36
55
  timeoutCount: 0,
37
- contractViolationCount: 0,
38
56
  engineSelfWrittenCount: 0,
39
57
  engineRecoveryCount: 0,
40
58
  harnessAbortCount: 0,
41
59
  };
60
+ /** The retired counter keys — still READABLE through `counterOf` (its callers name
61
+ * them), never written: their value derives from the round records
62
+ * (`Ledger#softViolations`), and a legacy scalar left on disk is ignored — zero
63
+ * migration, zero rewrite of history. */
64
+ export const PROGRESS_COUNTER_RETIRED = {
65
+ contractViolationCount: 0,
66
+ };
67
+ /**
68
+ * RoundRecords — the ONE read-time normalizer of a progress row's `rounds` plane.
69
+ * The stored form is a record array; the two legacy forms (a per-mode cycle-number
70
+ * array / a bare numeric cycle count) fold into completed records (the old write
71
+ * recorded only `!blocked` rounds, so every legacy cycle IS a completed round).
72
+ * Every reader (the ledger, the board, the dry-run preview, the pre-flight gate)
73
+ * normalizes here — zero second read seam, zero migration write-back.
74
+ */
75
+ // biome-ignore lint/complexity/noStaticOnlyClass: the normalization single point — the zero-bare-function discipline admits no standalone predicate functions.
76
+ export class RoundRecords {
77
+ /** The row's round records, legacy forms folded — [] when the row carries none. */
78
+ static of(row) {
79
+ const raw = row?.rounds;
80
+ if (raw === undefined)
81
+ return [];
82
+ if (Array.isArray(raw)) {
83
+ return raw.filter((entry) => typeof entry === "object" &&
84
+ entry !== null &&
85
+ typeof entry.op === "string");
86
+ }
87
+ const records = [];
88
+ for (const [mode, value] of Object.entries(raw)) {
89
+ const op = RoundRecords.opOf(mode);
90
+ if (op === null)
91
+ continue;
92
+ const cycles = Array.isArray(value) ? value : RoundRecords.#contiguous(value);
93
+ for (const cycle of cycles)
94
+ records.push(RoundRecords.completed(op, cycle));
95
+ }
96
+ return records.sort((left, right) => left.cycle - right.cycle);
97
+ }
98
+ /** One completed record of an op/cycle — the legacy fold and the test/seed form. */
99
+ static completed(op, cycle) {
100
+ return {
101
+ op,
102
+ cycle,
103
+ attempt: 1,
104
+ dispatchBase: null,
105
+ verdict: { treeClean: true, targetAction: true },
106
+ violations: [],
107
+ carrierPath: null,
108
+ };
109
+ }
110
+ /** The op a recorded mode key belongs to — branch-review rides the review family;
111
+ * an unknown mode key reads null (a hand-written row is not a round record). */
112
+ static opOf(mode) {
113
+ if (mode === "branch-review")
114
+ return "review";
115
+ return mode === "implement" || mode === "review" || mode === "fix" ? mode : null;
116
+ }
117
+ /** `n` as the contiguous identity list `1..n` (the retired numeric-count form). */
118
+ static #contiguous(count) {
119
+ return Array.from({ length: count }, (_unused, index) => index + 1);
120
+ }
121
+ }
122
+ /** The retired phase-spec row key — the spelling the round records carried before the
123
+ * target vocabulary unified on `phase-spec` (P22 D73). Rows already on disk keep it
124
+ * byte-frozen; the row read normalizes it (see `Ledger.rowFor`). */
125
+ const RETIRED_SPEC_KEY = "spec";
126
+ /** The identity-DOCUMENT line words a retired `spec` row may belong to — the words a
127
+ * workspace's document line keys under after the vocabulary unification. A workspace
128
+ * holds at most ONE identity document, so a retired `spec` row is exactly that
129
+ * document's line: `phase-spec` (the pre-rename default), a charter's `overall`, or a
130
+ * standalone `single-spec`. The plan line carried `plan` before the rename too and
131
+ * never lived under `spec`, so it stays out. */
132
+ const RETIRED_SPEC_LINE_KEYS = new Set([
133
+ "phase-spec",
134
+ "overall",
135
+ "single-spec",
136
+ ]);
42
137
  /**
43
138
  * ReviewRefs — the review-reference face (T25): the two-layer bindings (`docRevision`
44
139
  * — the doc hash from its content · `briefRevision` — the rendered brief's hash from
@@ -99,13 +194,22 @@ export class Ledger {
99
194
  /** The review-reference face (T25) — the refKind classification + the same-ref
100
195
  * reject, one instance per ledger (the run's bound refs). */
101
196
  #refs = new ReviewRefs();
197
+ /** The three-line drift judgment (P21 §4.1) — the ONE identity face the doc line
198
+ * and the wave line both read (the branch line binds its plan's doc-revision
199
+ * through the same face). Injected with this ledger's own ref face, so the
200
+ * same-ref predicate keeps one definition. */
201
+ #identity = new LineIdentity(this.#refs);
102
202
  /** The task-brief renderer (D30) — the wave line's judgment-input derivation:
103
203
  * the wave's reviewed basis is the RENDERED brief's content, never the whole
104
204
  * plan (a backfill touching other tasks must not void a reviewed wave). */
105
205
  #brief = new BriefRenderer();
206
+ /** The round-naming single source over this ledger's workspace — the crash
207
+ * artifact names derive here (zero second derivation). */
208
+ #naming;
106
209
  constructor(workspace, config) {
107
210
  this.#workspace = workspace;
108
211
  this.#families = config.handoffNamespace().families;
212
+ this.#naming = new RoundNaming(workspace);
109
213
  }
110
214
  /** The review-reference face — the refKind three-type derivation + binding (T25). */
111
215
  refs() {
@@ -158,73 +262,145 @@ export class Ledger {
158
262
  this.#persist("progress.json", data);
159
263
  }
160
264
  /** The ledger-row lookup single point — a scalar key (or the single-task wave key
161
- * `"1"`) resolves the `{ task }` row; a multi-task wave key (`"1,2"`) the `{ wave }` row. */
162
- rowFor(data, key) {
163
- return data.waves.find((row) => row.wave === String(key));
265
+ * `"1"`) resolves the `{ task }` row; a multi-task wave key (`"1,2"`) the `{ wave }` row.
266
+ * A DOCUMENT-line lookup falls back to a row still carrying the retired `spec` key —
267
+ * the read-time alias keeps an in-flight line's recorded reviews/fixes on its board
268
+ * (the normalization is never written back: the stored key stays byte-frozen). The
269
+ * alias keys on the workspace's DECLARED line word (`identity` — the caller's
270
+ * declaration), never on the requested word alone: the retired row IS the line whose
271
+ * declaration names it (`phase-spec` / `overall` / `single-spec`). A caller holding no
272
+ * declaration keeps the pre-rename default (the `phase-spec` line). A row read is a
273
+ * pure function of the progress data, so every face — this class and the board's
274
+ * read-only line face — enters through this ONE lookup (no second key spelling). */
275
+ static rowFor(data, key, identity = null) {
276
+ const literal = data.waves.find((row) => row.wave === String(key));
277
+ if (literal !== undefined || !_a.#retiredSpecApplies(key, identity))
278
+ return literal;
279
+ return data.waves.find((row) => row.wave === RETIRED_SPEC_KEY);
280
+ }
281
+ /** Whether a retired `spec` row IS the requested line — the requested word must be a
282
+ * document-line word and, when the declaration is known, BE that declaration. */
283
+ static #retiredSpecApplies(key, identity) {
284
+ const word = String(key);
285
+ if (!RETIRED_SPEC_LINE_KEYS.has(word))
286
+ return false;
287
+ return identity === null ? word === "phase-spec" : word === identity;
164
288
  }
165
289
  /** The fresh row for an absent key — always the wave form (a single trivial
166
290
  * wave `"1"` is still the `{ wave: "1" }` row — one row form, T26). */
167
291
  entryFor(key) {
168
292
  return { wave: String(key) };
169
293
  }
170
- /** One mode's recorded cycle numbers on a row — the raw identity list, normalizing a
171
- * legacy numeric count (`fix: 1`) to its assumed contiguous identity (`[1]`, the old
172
- * 1:1 assumption). Absent/empty → `[]`. */
294
+ /** One op's recorded cycle numbers on a row — every DISPATCHED cycle (legacy forms
295
+ * normalized through `RoundRecords`). A cycle re-dispatched several times is one
296
+ * cycle: the attempt count never widens the identity set. Absent/empty → `[]`. */
173
297
  #cyclesOf(row, mode) {
174
- const raw = row?.rounds?.[mode];
175
- if (raw === undefined)
298
+ const op = RoundRecords.opOf(mode);
299
+ if (op === null)
300
+ return [];
301
+ return [
302
+ ...new Set(RoundRecords.of(row)
303
+ .filter((record) => record.op === op)
304
+ .map((record) => record.cycle)),
305
+ ];
306
+ }
307
+ /** The row's round records — the ONE read face the ledger's consumers share. A
308
+ * caller holding the line's DECLARED word passes it, so the retired `spec` row
309
+ * resolves as that line (the same basis as `rowFor`'s). */
310
+ recordsOf(key, identity = null) {
311
+ const data = this.readProgress();
312
+ if (data === null)
176
313
  return [];
177
- return Array.isArray(raw) ? raw : Array.from({ length: raw }, (_unused, index) => index + 1);
314
+ return RoundRecords.of(_a.rowFor(data, key, identity));
178
315
  }
179
- /** The last completed round of a dispatch key + mode — 0 when none on record (the
180
- * round COUNT: the length of the recorded cycle set — for a contiguous review line
181
- * this equals the latest cycle, but the identity is the cycle list, never the count). */
182
- roundCount(key, mode) {
316
+ /** One op's COMPLETED cycles on a key — only `verdict.targetAction === true` records.
317
+ * The completion questions read this face; the dispatch-number allocation reads
318
+ * `roundCount` (every in-register cycle). The caller holding the line's DECLARED
319
+ * word passes it, so a migrated row is judged as that line (one basis with
320
+ * `rowFor`'s). */
321
+ completedCycles(key, op, identity = null) {
322
+ const data = this.readProgress();
323
+ if (data === null)
324
+ return [];
325
+ return RoundRecords.of(_a.rowFor(data, key, identity))
326
+ .filter((record) => record.op === op && record.verdict.targetAction)
327
+ .map((record) => record.cycle);
328
+ }
329
+ /** The number of DISTINCT cycles on a dispatch key + mode — 0 when none on record
330
+ * (the round COUNT: the length of the recorded cycle identity set — for a
331
+ * contiguous review line this equals the latest cycle, but the identity is the
332
+ * cycle list, never the count, and a re-attempt at an existing cycle adds none). */
333
+ roundCount(key, mode, identity = null) {
183
334
  const data = this.readProgress();
184
335
  if (data === null)
185
336
  return 0;
186
- return this.#cyclesOf(this.rowFor(data, key), mode).length;
337
+ return this.#cyclesOf(_a.rowFor(data, key, identity), mode).length;
187
338
  }
188
- /** Whether a dispatch key + mode has a round recorded for a given CYCLE — the
189
- * identity test the round-read gate uses (a fix cycle that skipped a number is
190
- * present at its own number, not at its ordinal — D28). */
191
- roundRecorded(key, mode, cycle) {
339
+ /** Whether a dispatch key + mode has a round REGISTERED for a given CYCLE — the
340
+ * identity test for the register (a fix cycle that skipped a number is present at
341
+ * its own number, not at its ordinal — D28). This is the test/seeding face: it
342
+ * answers register membership, NOT completion (a hard-failed round is registered),
343
+ * so no production completion question reads it — those read `completedCycles`. */
344
+ roundRecorded(key, mode, cycle, identity = null) {
192
345
  const data = this.readProgress();
193
346
  if (data === null)
194
347
  return false;
195
- return this.#cyclesOf(this.rowFor(data, key), mode).includes(cycle);
196
- }
197
- /** Record a completed round — the on-disk done record (the ledger edge of the
198
- * ExecutionState carrier: TaskGraph in memory, the ledger on disk). The round's
199
- * CYCLE is its identity (fix-K ⟷ review-K · D28), so a skipped cycle records its
200
- * own number, never a flattened ordinal. The production caller passes the frame's
201
- * own `round`; the default (the next cycle after the latest) records a sequential
202
- * round. Creates the row on demand; the write is idempotent per cycle (a re-record
203
- * of the same cycle does not double it). */
204
- recordRound(key, mode, cycle) {
348
+ return this.#cyclesOf(_a.rowFor(data, key, identity), mode).includes(cycle);
349
+ }
350
+ /** Record a dispatched round — the on-disk round record (the ledger edge of the
351
+ * ExecutionState carrier: TaskGraph in memory, the ledger on disk). Every dispatched
352
+ * round lands, failed rounds included; "completed" is the record's
353
+ * `verdict.targetAction`, never the write. The round's CYCLE is its identity
354
+ * (fix-K ⟷ review-K · D28), so a skipped cycle records its own number, never a
355
+ * flattened ordinal. The production caller passes the frame's whole identity
356
+ * (`Run`); the seeding form allocates the next cycle after the latest in-register
357
+ * one. The write is idempotent per (op, cycle, attempt): a re-record of the same
358
+ * identity does not double it. A caller holding the line's DECLARED word passes it
359
+ * too, so a migrated row is APPENDED TO rather than forked into a second identity
360
+ * row (the same one basis `rowFor` reads by). */
361
+ recordRound(key, init, identity = null) {
205
362
  const data = this.readProgress() ?? this.emptyProgress();
206
- let row = this.rowFor(data, key);
363
+ let row = _a.rowFor(data, key, identity);
207
364
  if (row === undefined) {
208
365
  row = this.entryFor(key);
209
366
  data.waves.push(row);
210
367
  }
211
- const cycles = [...this.#cyclesOf(row, mode)];
212
- const recorded = cycle ?? (cycles.length > 0 ? Math.max(...cycles) + 1 : 1);
213
- if (!cycles.includes(recorded))
214
- cycles.push(recorded);
215
- cycles.sort((a, b) => a - b);
216
- row.rounds = { ...row.rounds, [mode]: cycles };
368
+ const records = [...RoundRecords.of(row)];
369
+ const cycle = init.cycle ?? this.#nextCycle(records, init.op);
370
+ const record = {
371
+ op: init.op,
372
+ cycle,
373
+ attempt: init.attempt ?? 1,
374
+ dispatchBase: init.dispatchBase ?? null,
375
+ verdict: init.verdict ?? { treeClean: true, targetAction: true },
376
+ violations: init.violations ?? [],
377
+ carrierPath: init.carrierPath ?? null,
378
+ };
379
+ const existing = records.findIndex((candidate) => candidate.op === record.op &&
380
+ candidate.cycle === record.cycle &&
381
+ candidate.attempt === record.attempt);
382
+ if (existing === -1)
383
+ records.push(record);
384
+ else
385
+ records[existing] = record;
386
+ records.sort((left, right) => left.cycle === right.cycle ? left.attempt - right.attempt : left.cycle - right.cycle);
387
+ row.rounds = records;
217
388
  this.writeProgress(data);
218
- return cycles.length;
389
+ return record;
390
+ }
391
+ /** The next un-registered cycle of an op — latest in-register + 1 (1 when none). */
392
+ #nextCycle(records, op) {
393
+ const cycles = records.filter((record) => record.op === op).map((record) => record.cycle);
394
+ return cycles.length > 0 ? Math.max(...cycles) + 1 : 1;
219
395
  }
220
396
  /** Record a line's reviewed identity — the identity-aware gate's basis (written
221
397
  * when the review round completes: the line reopens on drift from this recorded
222
398
  * revision, and BLOCKs revision-aware when unchanged). The kind IS part of the
223
399
  * identity: a doc line binds a doc-revision (T7), a wave line a brief-revision
224
400
  * (D30) — one row, one reviewed identity. */
225
- recordReviewedRevision(key, revision) {
401
+ recordReviewedRevision(key, revision, identity = null) {
226
402
  const data = this.readProgress() ?? this.emptyProgress();
227
- let row = this.rowFor(data, key);
403
+ let row = _a.rowFor(data, key, identity);
228
404
  if (row === undefined) {
229
405
  row = this.entryFor(key);
230
406
  data.waves.push(row);
@@ -262,17 +438,43 @@ export class Ledger {
262
438
  /** A line's recorded reviewed identity — null when none on record (a line with no
263
439
  * reviewed identity keeps the legacy closed face). Callers narrow by `kind`: a doc
264
440
  * line binds a doc-revision, a wave line a brief-revision (the kinds never mix). */
265
- reviewedRevisionOf(key) {
441
+ reviewedRevisionOf(key, identity = null) {
266
442
  const data = this.readProgress();
267
443
  if (data === null)
268
444
  return null;
269
- return this.rowFor(data, key)?.reviewedRevision ?? null;
445
+ return _a.rowFor(data, key, identity)?.reviewedRevision ?? null;
446
+ }
447
+ /** Record a wave row's plan-task snapshot — the task set the plan carried at the
448
+ * instant the wave CLOSED. The write is IDEMPOTENT: an existing snapshot is never
449
+ * overwritten, because the fact it records is historical (the plan may gain tasks
450
+ * afterwards; re-deriving would erase the append-vs-stall evidence). */
451
+ recordPlanTasks(waveKey, planTasks) {
452
+ const data = this.readProgress() ?? this.emptyProgress();
453
+ let row = _a.rowFor(data, waveKey);
454
+ if (row === undefined) {
455
+ row = this.entryFor(waveKey);
456
+ data.waves.push(row);
457
+ }
458
+ if (row.planTasks !== undefined)
459
+ return;
460
+ row.planTasks = [...planTasks];
461
+ this.writeProgress(data);
462
+ }
463
+ /** A wave row's plan-task snapshot — null on a historical row (recorded before the
464
+ * snapshot existed) and on a wave that never closed (no snapshot taken yet). The
465
+ * callers treat null conservatively: an absent snapshot never authorizes the
466
+ * append reading. */
467
+ planTasksOf(waveKey) {
468
+ const data = this.readProgress();
469
+ if (data === null)
470
+ return null;
471
+ return _a.rowFor(data, waveKey)?.planTasks ?? null;
270
472
  }
271
473
  /** The doc line's recorded reviewed doc revision — the doc-revision narrowing of
272
474
  * `reviewedRevisionOf` (null when none on record, or when a non-doc kind sits on
273
475
  * the row — a doc line is never a wave line). */
274
- reviewedDocRevisionOf(key) {
275
- const reviewed = this.reviewedRevisionOf(key);
476
+ reviewedDocRevisionOf(key, identity = null) {
477
+ const reviewed = this.reviewedRevisionOf(key, identity);
276
478
  return reviewed !== null && reviewed.kind === "doc-revision" ? reviewed : null;
277
479
  }
278
480
  /** The doc line's identity verdict (T7) — the current doc revision vs the line's
@@ -283,8 +485,8 @@ export class Ledger {
283
485
  * `same` → unchanged (the revision-aware BLOCK). Null when no reviewed revision
284
486
  * is on record or the doc is unreadable (the legacy closed face keeps its
285
487
  * generic message — only present facts land). */
286
- docLineVerdict(key, doc) {
287
- const reviewed = this.reviewedDocRevisionOf(key);
488
+ docLineVerdict(key, doc, identity = null) {
489
+ const reviewed = this.reviewedDocRevisionOf(key, identity);
288
490
  if (reviewed === null)
289
491
  return null;
290
492
  try {
@@ -293,33 +495,31 @@ export class Ledger {
293
495
  // false-drift comparison never reads one document as two.
294
496
  const rel = this.#rel(doc);
295
497
  const current = this.#refs.docRevision(rel, readFileSync(this.#abs(doc), "utf8"));
296
- return this.#refs.sameRef(reviewed, current) ? "same" : "drift";
498
+ return this.#identity.verdict(reviewed, { ref: current }) === "same" ? "same" : "drift";
297
499
  }
298
500
  catch {
299
501
  return null;
300
502
  }
301
503
  }
302
504
  /** The review-gate method (T8 · §3.5) — the doc line's review request judgment +
303
- * the phase advance, doc-revision FIRST: the shared docLineVerdict comparison is
304
- * the PRIMARY criterion — a drifted doc OPENS the review lead regardless of the
305
- * round/route state (fix / backfill / user-decision are one case: the stuck
306
- * "next round is fix after an aborted fix" gate never freezes a revised doc);
307
- * an unchanged doc yields the `same` verdict (review Convergence anti-spin:
505
+ * the phase advance: the shared docLineVerdict comparison reports the drift, and
506
+ * the REOPEN's scope is the callers' ONE judgment (`Ledger#docReopens` — an
507
+ * exit-side route is replaced by the review lead, while an already-pending fix
508
+ * keeps its round, §5.5 ②).
509
+ * An unchanged doc yields the `same` verdict (review Convergence anti-spin:
308
510
  * the callers' reject/reopen decision — the derived pending fix opens the fix
309
511
  * face only, while the no-pending face falls back to the legacy rounds/routes
310
512
  * judgment: a completed-fix line's C5-1 route reopens the review lead). The OPEN
311
513
  * side performs no disk advance: the round + the revision snapshot land with the
312
514
  * round's completion (Ledger#recordRound + the T7 write-back), so a BLOCKED
313
515
  * re-review resumes the same round (nothing pre-binds). `unbound` (no identity on
314
- * record / an unreadable doc) keeps the legacy round/route judgment. The
315
- * judgment order change is the whole gate: the old rounds/routes-first read made
316
- * the round/route state shadow the doc movement (the pre-T8 stuck path). */
516
+ * record / an unreadable doc) keeps the legacy round/route judgment. */
317
517
  reviewGate(key, doc, type) {
318
- const verdict = this.docLineVerdict(key, doc);
518
+ const verdict = this.docLineVerdict(key, doc, type);
319
519
  if (verdict === "drift")
320
520
  return { kind: "open" };
321
521
  if (verdict === "same") {
322
- const reviewed = this.reviewedDocRevisionOf(key);
522
+ const reviewed = this.reviewedDocRevisionOf(key, type);
323
523
  if (reviewed === null)
324
524
  return { kind: "unbound" };
325
525
  return { kind: "same", pending: this.#pendingFix(key, type), reviewed };
@@ -346,12 +546,12 @@ export class Ledger {
346
546
  * the board's `next:` derivation reads the route itself (D40 — the active hop, never
347
547
  * a bare face handoff). */
348
548
  waveLineRoute(waveKey) {
349
- const implemented = this.roundCount(waveKey, "implement");
350
- if (implemented === 0)
549
+ const implemented = this.completedCycles(waveKey, "implement");
550
+ if (implemented.length === 0)
351
551
  return { kind: "next-wave", tasks: waveKey };
352
552
  const data = this.readProgress();
353
- const row = data === null ? undefined : this.rowFor(data, waveKey);
354
- const latestReview = row === undefined ? 0 : this.#latestCycleOfRow(row, "review");
553
+ const row = data === null ? undefined : _a.rowFor(data, waveKey);
554
+ const latestReview = row === undefined ? 0 : this.#latestCompletedCycleOfRow(row, "review");
355
555
  if (latestReview === 0)
356
556
  return { kind: "review" };
357
557
  // The latest recorded round is a fix iff a fix is recorded at the latest review's
@@ -360,7 +560,7 @@ export class Ledger {
360
560
  // ⇒ pending fix" short-circuit read a re-review-closed line (`review=[1,2] · fix=[1]`)
361
561
  // as forever at `fix`, missing the closing review-2 — the router read below is the
362
562
  // single judge (the `waveLineRoute` twin of `#rowClosed`).
363
- const fixRecorded = row !== undefined && this.#cyclesOf(row, "fix").includes(latestReview);
563
+ const fixRecorded = row !== undefined && this.#completedCyclesOfRow(row, "fix").includes(latestReview);
364
564
  const carried = this.round(fixRecorded ? "fix" : "review", "wave", { tasks: waveKey }, latestReview);
365
565
  if (carried === null)
366
566
  return null;
@@ -410,23 +610,35 @@ export class Ledger {
410
610
  const current = this.#briefRevision(waveKey, reviewed.plan);
411
611
  if (current === null)
412
612
  return false;
413
- return !this.#refs.sameRef(reviewed, current);
613
+ return this.#identity.verdict(reviewed, { ref: current }) === "drift";
414
614
  }
415
615
  /** The pending-fix derivation — the "doc same + not APPROVED" face (T8): the
416
616
  * latest review round has an outstanding fix AND its conclusion was not an
417
617
  * approval. The identity test is the operable leg (D28): the latest review cycle
418
- * is ABSENT from the fix cycle set (`roundRecorded(key, "fix", reviews)`) — a
618
+ * is ABSENT from the fix COMPLETION set (`#completedCyclesOfRow(row, "fix")`) — a
419
619
  * membership test, never a `reviews > fixes` count comparison, which would read a
420
620
  * phantom pending fix when a cycle was skipped (a drift-voided review-1 → the first
421
- * fix is cycle 2, present at its own number, not ordinal 1). The status read keeps
422
- * the derivation's second leg explicit, degrading to the conservative pending on a
423
- * missing carrier (a recorded round is a present fact — the same-doc re-review
424
- * stays refused until its fix lands). A completed fix (the latest review cycle IS
425
- * in the fix set) is NOT the pending face — the completed-fix line's re-review
621
+ * fix is cycle 2, present at its own number, not ordinal 1). The completion set —
622
+ * not bare register membership (`roundRecorded`, the test/seeding face) — is the
623
+ * judging face: every dispatched round is registered, so a hard-failed `fix-K` IS
624
+ * in register while NOT completed, and a register test would read that failure as
625
+ * a done fix and strand the line forever. The status read keeps the derivation's
626
+ * second leg explicit, degrading to the conservative pending on a missing carrier
627
+ * (a recorded round is a present fact — the same-doc re-review stays refused until
628
+ * its fix lands). A completed fix (the latest review cycle IS in the fix
629
+ * completion set) is NOT the pending face — the completed-fix line's re-review
426
630
  * reopens through the fix round's C5 route (the legacy judgment). */
427
631
  #pendingFix(key, type) {
428
- const reviews = this.roundCount(key, "review");
429
- if (reviews === 0 || this.roundRecorded(key, "fix", reviews))
632
+ const data = this.readProgress();
633
+ if (data === null)
634
+ return false;
635
+ const row = _a.rowFor(data, key, type);
636
+ if (row === undefined)
637
+ return false;
638
+ const reviews = this.#latestCompletedCycleOfRow(row, "review");
639
+ if (reviews === 0)
640
+ return false;
641
+ if (this.#completedCyclesOfRow(row, "fix").includes(reviews))
430
642
  return false;
431
643
  const carried = this.round("review", type, { round: reviews }, reviews);
432
644
  // `carried.status` is the review round's DERIVED conclusion — `round()` sets it
@@ -434,10 +646,39 @@ export class Ledger {
434
646
  // stores no status field · D27), never a second read of the carrier here.
435
647
  return carried === null || carried.status === undefined || carried.status !== "APPROVED";
436
648
  }
437
- /** Read one counter — a failure-category count on record (0 when the file is missing). */
649
+ /** Read one counter — a failure-category count on record (0 when the file is
650
+ * missing). The RETIRED key derives from the round records: the soft entries of
651
+ * every row plus the one each dirty-tree observation derives (design spec §3.3) —
652
+ * one read exit, `counterOf`, never a second stored scalar. */
438
653
  counterOf(key) {
654
+ if (key === "contractViolationCount")
655
+ return this.softViolations();
439
656
  return this.readProgress()?.[key] ?? 0;
440
657
  }
658
+ /** One key's SOFT violation count — the row's soft entries across its records plus
659
+ * the single row the `treeClean === false` observation derives (at most one per
660
+ * round: the verdict field IS that fact, never a second copy of it). Hard entries
661
+ * are the round's failure verdict (exit + `targetAction: false`), never a count. */
662
+ softViolationsOf(key) {
663
+ const data = this.readProgress();
664
+ if (data === null)
665
+ return 0;
666
+ return this.#softOf(_a.rowFor(data, key));
667
+ }
668
+ /** The session's SOFT violation count — the derived `contractViolationCount` read
669
+ * face (`counterOf`'s retired key). A legacy scalar on disk is ignored. */
670
+ softViolations() {
671
+ const data = this.readProgress();
672
+ if (data === null)
673
+ return 0;
674
+ return data.waves.reduce((total, row) => total + this.#softOf(row), 0);
675
+ }
676
+ /** One row's soft count — one derivation, both read faces above. */
677
+ #softOf(row) {
678
+ return RoundRecords.of(row).reduce((total, record) => total +
679
+ record.violations.filter((violation) => violation.grade === "soft").length +
680
+ (record.verdict.treeClean ? 0 : 1), 0);
681
+ }
441
682
  /** Increment the timeout counter — the terminated-round write point (one TIMEOUT
442
683
  * round lands, the count goes up by one). The counter's only writer. */
443
684
  incrementTimeoutCount() {
@@ -446,15 +687,6 @@ export class Ledger {
446
687
  this.writeProgress(data);
447
688
  return data.timeoutCount;
448
689
  }
449
- /** Increment the contract-violation counter — the read-back write point (one
450
- * `handoff-absent` or `contract-violation` crash lands, the count goes up by
451
- * one). The counter's only writer. */
452
- incrementContractViolationCount() {
453
- const data = this.readProgress() ?? this.emptyProgress();
454
- data.contractViolationCount += 1;
455
- this.writeProgress(data);
456
- return data.contractViolationCount;
457
- }
458
690
  // -------------------------------------------------------------------------
459
691
  // closedWaves — the closure single read face (v1.20)
460
692
  // -------------------------------------------------------------------------
@@ -486,18 +718,36 @@ export class Ledger {
486
718
  * derivation and its branch row consume (and `closedWaves()` reads through the
487
719
  * same core). The C5 route of the line's LATEST recorded round must lie on the
488
720
  * closure side ({done, next-wave}). The key is the line-type constant the round
489
- * records under ("spec" / "plan" / "branch"); a row with no review round yet
721
+ * records under (the target-type word — `"phase-spec"` / `"overall"` / `"plan"` /
722
+ * `"single-spec"` / `"branch"`); a row with no review round yet
490
723
  * (implement-only or absent) holds the line open. One judge, one source: the
491
724
  * board never re-derives closure in the face (zero second judge). */
492
725
  lineClosed(key, type) {
493
726
  const data = this.readProgress();
494
727
  if (data === null)
495
728
  return false;
496
- const row = this.rowFor(data, key);
729
+ const row = _a.rowFor(data, key, type);
497
730
  if (row === undefined)
498
731
  return false;
499
732
  return this.#rowClosed(type, type === "wave" ? { tasks: String(key) } : {}, row);
500
733
  }
734
+ /** One line's closure state AS OF its identity document — the drift-aware judge
735
+ * both board read faces consume (the branch row's mark and the pipeline facts'
736
+ * branch `closed` cell), so the mark and the `next:` line can never print two
737
+ * different facts about one state. `closed` — the recorded rounds/routes lie on
738
+ * the closure side AND the identity document still matches the revision the line
739
+ * bound, or no identity document is on hand (`doc === null`): with no document
740
+ * there is no drift evidence, so the conservative answer is closed — a false
741
+ * reopen costs a whole branch review, while a false closure is what the `next:`
742
+ * face reports separately; `reopened` — the rounds/routes say closed but the
743
+ * document moved past them, which IS the gate's reopen (`reviewGate` → `open`, the
744
+ * ruling the CLI dispatch consults), so the line is the face awaiting review;
745
+ * `open` — the rounds/routes themselves hold the line open. */
746
+ lineStateAt(key, type, doc) {
747
+ if (!this.lineClosed(key, type))
748
+ return "open";
749
+ return doc !== null && this.reviewGate(key, doc, type).kind === "open" ? "reopened" : "closed";
750
+ }
501
751
  /** The single-target line's active C5 Route — the next C5 hop the dispatch engine
502
752
  * would run on this line (the doc/branch faces: the review-lead round judges the
503
753
  * live tree; a fix-awaited review, a re-review after a blocker-carrying fix). A line
@@ -509,15 +759,21 @@ export class Ledger {
509
759
  * The pending-fix test is the latest review's IDENTITY membership in the fix cycle
510
760
  * set (D28) — a count comparison would flatten a skipped cycle into a phantom pending
511
761
  * fix. The doc-revision gate is NOT part of this walk — the callers run their own
512
- * reviewGate first (doc-drift-first ordering). `linePhase` maps this route to its
513
- * phase word (one walk), and the board's `next:` derivation reads the route itself
514
- * (D40 — the active hop, never a bare face handoff). */
762
+ * reviewGate first and scope the reopen through `Ledger#docReopens`. `linePhase`
763
+ * maps this route to its phase word (one walk), and the board's `next:` derivation
764
+ * reads the route itself (D40 — the active hop, never a bare face handoff). */
515
765
  lineRoute(key, type) {
766
+ const data = this.readProgress();
767
+ if (data === null)
768
+ return { kind: "review" };
769
+ const row = _a.rowFor(data, key, type);
770
+ if (row === undefined)
771
+ return { kind: "review" };
516
772
  const reviewLead = targetFaces[type].product.reviewLead;
517
- const reviews = this.roundCount(key, reviewLead);
773
+ const reviews = this.#latestCompletedCycleOfRow(row, reviewLead);
518
774
  if (reviews === 0)
519
775
  return { kind: "review" };
520
- if (!this.roundRecorded(key, "fix", reviews)) {
776
+ if (!this.#completedCyclesOfRow(row, "fix").includes(reviews)) {
521
777
  const route = this.#lineRoundRoute("review", type, reviews);
522
778
  return route?.kind === "fix" ? route : null;
523
779
  }
@@ -536,6 +792,44 @@ export class Ledger {
536
792
  return null;
537
793
  return route.kind === "review" ? targetFaces[type].product.reviewLead : "fix";
538
794
  }
795
+ /** One line's next hop (§5.2) — the derivation's INPUT face gathered from the
796
+ * line's OWN facts and handed to the router's ONE derivation: the drift-aware gate
797
+ * verdict, the ONE doc-class verdict (the declared station the face axis is read
798
+ * out of), the caller's route (the count table's row for a single line, the
799
+ * pipeline walk's route for the board) and the judged document. Every read face
800
+ * (capsule · CLI rejection · board · the lifecycle frontier) comes through here,
801
+ * so the four faces share one object by construction — no face assembles a second
802
+ * copy of the inputs, and no judgment is re-made here (the route is the count
803
+ * table's). The ONE exception is the drift-reopened line: the gate's `drift`
804
+ * verdict IS the reopen, and the closure-side route the count table recorded
805
+ * predates the document movement — so the assembly hands the derivation the
806
+ * reopened review hop in that case. A presentation-level substitution: the count
807
+ * table's judgment (`NextStepRouter#next`) stays the only judge, and a still-open
808
+ * hop (review / fix) is never overridden by the drift fact. */
809
+ nextHopOf(input) {
810
+ const drift = input.doc != null && input.type !== "wave"
811
+ ? this.reviewGate(input.key, input.doc, input.type).kind === "open"
812
+ : false;
813
+ // The drift-reopened line — its active hop IS the review lead (the gate's own
814
+ // ruling): the EXIT-side route the table recorded (the line's closure or a
815
+ // face-to-face handoff, or no route at all) predates the document movement, so
816
+ // the derivation receives the review hop instead. An already-open hop (review /
817
+ // fix) and the soft-cap adjudication row keep their own route — the pending-fix
818
+ // face outranks drift (§5.1 · §5.5 ②). The exit side is the ONE predicate
819
+ // (`Ledger.onExitSide`) every drift-reopen reader shares, so this assembly, the
820
+ // dispatch gate and the lifecycle frontier can never disagree on the scope.
821
+ const route = drift && _a.onExitSide(input.route) ? { kind: "review" } : input.route;
822
+ // The face axis is the ONE verdict this assembly reads (spec §5.2's doc-class
823
+ // discrimination): no target carries no judgeable class (the bare terminal).
824
+ const verdict = input.target === null ? "terminal" : input.docClassOf(input.target);
825
+ return this.#router.nextHop({
826
+ target: input.target,
827
+ gate: { drift },
828
+ verdict,
829
+ route,
830
+ nextLineOpen: input.nextLineOpen,
831
+ });
832
+ }
539
833
  /** One single-target line round's C5 route — the review-lead / fix round read back
540
834
  * through the ledger and judged by the router (null when unreadable). Single-target
541
835
  * lines key their handoff params `{ round }` (the run.ts / gate.ts shaping) — the
@@ -549,6 +843,25 @@ export class Ledger {
549
843
  static routeClosed(route) {
550
844
  return route !== null && (route.kind === "done" || route.kind === "next-wave");
551
845
  }
846
+ /** Whether a C5 route sits on the line's EXIT side — a closure, the face-to-face
847
+ * `handoff` station a pipeline consumer hands over (an exit station, not a closure
848
+ * — the closure predicate deliberately excludes it), or no route at all. This is
849
+ * the drift reopen's ONE override scope (§5.1 · §5.5 ②): only an exit-side route
850
+ * predates the document movement, so only it is replaced by the review lead; a
851
+ * still-pending fix keeps its hop, and every drift-reopen reader asks HERE. */
852
+ static onExitSide(route) {
853
+ return route === null || route.kind === "handoff" || _a.routeClosed(route);
854
+ }
855
+ /** Whether the document's drift reopens the line onto its review lead — the ONE
856
+ * drift-reopen judgment the dispatch gate and the lifecycle frontier BOTH consume
857
+ * (the gate verdict is handed in: the comparison is read once). Drift never
858
+ * outranks a pending fix (§5.5 ②): a live review/fix hop on the non-exit side
859
+ * keeps its round, so no face names a round another face refuses. */
860
+ docReopens(key, type, gate) {
861
+ if (gate.kind !== "open")
862
+ return false;
863
+ return _a.onExitSide(this.lineRoute(key, type));
864
+ }
552
865
  /** Whether one progress row's line is closed — the LATEST recorded round's C5 route
553
866
  * lies on the closure side ({done, next-wave}). The latest recorded round is a fix
554
867
  * iff a fix is recorded at the latest review's CYCLE (D28 identity — fix-K ⟷
@@ -561,18 +874,27 @@ export class Ledger {
561
874
  * review-lead mode rides the faces table (branch→branch-review, the others→review),
562
875
  * so the wave/spec/plan/branch lines share ONE judge. */
563
876
  #rowClosed(type, params, row) {
564
- const latestReview = this.#latestCycleOfRow(row, targetFaces[type].product.reviewLead);
877
+ const latestReview = this.#latestCompletedCycleOfRow(row, targetFaces[type].product.reviewLead);
565
878
  if (latestReview === 0)
566
879
  return false;
567
- const fixRecorded = this.#cyclesOf(row, "fix").includes(latestReview);
880
+ const fixRecorded = this.#completedCyclesOfRow(row, "fix").includes(latestReview);
568
881
  return _a.routeClosed(this.#roundRoute(fixRecorded ? "fix" : "review", type, params, latestReview));
569
882
  }
570
- /** The latest recorded cycle of a row + mode — 0 when none (the identity read; a
571
- * skipped cycle reports its own number, never the count). */
572
- #latestCycleOfRow(row, mode) {
573
- const cycles = this.#cyclesOf(row, mode);
883
+ /** The latest COMPLETED cycle of a row + mode — 0 when none. A failed round consumed
884
+ * its cycle but is not a carrier, so every active-hop read starts here. */
885
+ #latestCompletedCycleOfRow(row, mode) {
886
+ const cycles = this.#completedCyclesOfRow(row, mode);
574
887
  return cycles.length > 0 ? Math.max(...cycles) : 0;
575
888
  }
889
+ /** One mode's completed cycles on a row — the row-level twin of `completedCycles`. */
890
+ #completedCyclesOfRow(row, mode) {
891
+ const op = RoundRecords.opOf(mode);
892
+ if (op === null)
893
+ return [];
894
+ return RoundRecords.of(row)
895
+ .filter((record) => record.op === op && record.verdict.targetAction)
896
+ .map((record) => record.cycle);
897
+ }
576
898
  /** The C5 route of one recorded round — null when the round is unreadable (a
577
899
  * line whose round was never read cannot be judged closed: only present facts). */
578
900
  #roundRoute(op, type, params, round) {
@@ -621,31 +943,150 @@ export class Ledger {
621
943
  this.#persist(this.handoffName(op, type, params), data);
622
944
  return this.handoffPath(op, type, params);
623
945
  }
624
- /** Read a handoff carrier; null when missing/corrupt. */
946
+ /** The handoff file NAME a read actually resolves — the canonical family name, or a
947
+ * DOCUMENT line's retired `spec` twin when the canonical file is absent (the
948
+ * one-release read alias, P22 D73). The alias reports the name it RESOLVED, not the
949
+ * one it was asked for: a hop that points a later round at this carrier
950
+ * (`--reviews`, `INPUT_REVIEWS`, the criterion's input set) must name the file that
951
+ * exists — a read alias that renamed only the row would leave a never-minted path
952
+ * behind. The alias keys on the line's declared word and never covers the node
953
+ * shapes; it is READ-ONLY (every write goes through `persistHandoff`'s canonical
954
+ * spelling). */
955
+ resolveHandoffName(op, type, params = {}) {
956
+ const canonical = this.handoffName(op, type, params);
957
+ if (!RETIRED_SPEC_LINE_KEYS.has(type) || this.#read(canonical) !== null) {
958
+ return canonical;
959
+ }
960
+ const retired = _a.#retiredCarrierName(op, params);
961
+ return this.#read(retired) === null ? canonical : retired;
962
+ }
963
+ /** The resolved handoff path — `resolveHandoffName`'s on-disk form (the read face's
964
+ * single path exit; the writers keep `handoffPath`). */
965
+ resolveHandoffPath(op, type, params = {}) {
966
+ return this.#workspace.resolve(this.resolveHandoffName(op, type, params));
967
+ }
968
+ /** Read a handoff carrier; null when missing/corrupt. A DOCUMENT-line read falls
969
+ * back to the retired `spec` file name (the one-release read alias, P22 D73): the
970
+ * rounds a line recorded before the vocabulary unification stay judgeable — the
971
+ * closure walk still reads their C5 route, so a closed line does not re-open. The
972
+ * alias keys on the line's declared word (`phase-spec` / `overall` / `single-spec`,
973
+ * the same basis as `rowFor`'s) and never covers the node shapes. Every WRITE goes
974
+ * through `persistHandoff`'s current spelling — the alias is read-only, and the name
975
+ * it resolves is `resolveHandoffName`'s ONE answer. */
625
976
  readHandoff(op, type, params) {
626
- return this.#read(this.handoffName(op, type, params));
977
+ return this.#read(this.resolveHandoffName(op, type, params));
978
+ }
979
+ /** The retired document-line carrier name of one round — `spec-review-{round}.json` /
980
+ * `spec-fix-{round}.json`. It lives here, never in the family table: it is a read
981
+ * fallback for already-recorded rounds, not a name the engine can mint. */
982
+ static #retiredCarrierName(op, params) {
983
+ return `${RETIRED_SPEC_KEY}-${op}-${params.round ?? ""}.json`;
984
+ }
985
+ /** The workspace's ORPHAN handoff drafts — the `handoff` family files whose
986
+ * (line key, op, round) never landed in `progress.json` (a draft written by a
987
+ * round that never booked). The board and the `--dry-run` preview render them;
988
+ * this is a PURE READ — the engine never writes, moves or deletes a draft. The
989
+ * family names are the ledger's own single naming truth (no second pattern), and
990
+ * the owning row is read through the ONE basis `rowFor` establishes — the draft's
991
+ * own line word IS its declaration — so a migrated workspace's carrier resolves
992
+ * its retired row instead of reading as an orphan. */
993
+ orphanHandoffs() {
994
+ const progress = this.readProgress() ?? this.emptyProgress();
995
+ const orphans = [];
996
+ for (const name of this.#workspaceFiles()) {
997
+ const owner = _a.#handoffOwner(name, this.#families);
998
+ if (owner === null)
999
+ continue;
1000
+ const row = _a.rowFor(progress, owner.key, _a.#lineWord(owner.key));
1001
+ const completed = RoundRecords.of(row)
1002
+ .filter((record) => record.verdict.targetAction)
1003
+ .map((record) => `${record.op}:${record.cycle}`);
1004
+ if (!completed.includes(`${RoundRecords.opOf(owner.op) ?? owner.op}:${owner.round}`)) {
1005
+ orphans.push(name);
1006
+ }
1007
+ }
1008
+ return orphans.sort();
1009
+ }
1010
+ /** A handoff file's key as a declared line word — the three document words declare
1011
+ * themselves; every other key (a wave's tasks, `plan`, `branch`) declares nothing
1012
+ * and reads literally. */
1013
+ static #lineWord(key) {
1014
+ return RETIRED_SPEC_LINE_KEYS.has(key) ? key : null;
1015
+ }
1016
+ /** The workspace directory's file names (an absent/unreadable directory is an
1017
+ * empty fact — the orphan face degrades, never throws). */
1018
+ #workspaceFiles() {
1019
+ try {
1020
+ return readdirSync(this.#workspace.path, { withFileTypes: true })
1021
+ .filter((entry) => entry.isFile())
1022
+ .map((entry) => entry.name);
1023
+ }
1024
+ catch {
1025
+ return [];
1026
+ }
1027
+ }
1028
+ /** Which recorded round one handoff file belongs to — the family name pattern is
1029
+ * the ONE naming truth, read backwards: `tasks-{tasks}-{op}[-{round}].json` /
1030
+ * `{line}-{op}-{round}.json`, plus a document line's retired `spec` twin (the
1031
+ * pre-rename name a still-unbooked draft can carry). Null for a non-handoff file. */
1032
+ static #handoffOwner(name, families) {
1033
+ for (const [family, record] of Object.entries(families)) {
1034
+ const [op = "", type = ""] = family.split(".");
1035
+ for (const spelling of _a.#familySpellings(record.name, type)) {
1036
+ const captures = _a.#familyCaptures(spelling, name);
1037
+ if (captures === null)
1038
+ continue;
1039
+ const key = type === "wave" ? (captures.tasks ?? "") : type;
1040
+ // Each family carries the placeholder IT declares: a wave's review/fix name
1041
+ // carries `{tasks}` AND `{round}`, a document / branch line carries `{round}`
1042
+ // alone, and the fixed implement family carries `{tasks}` alone (round 1).
1043
+ const round = captures.round === null ? 1 : Number(captures.round);
1044
+ return { key, op, round };
1045
+ }
1046
+ }
1047
+ return null;
1048
+ }
1049
+ /** The name spellings one family answers to — its canonical pattern, and for a
1050
+ * document line the retired `spec` twin it was minted under before the rename. */
1051
+ static #familySpellings(name, type) {
1052
+ if (!RETIRED_SPEC_LINE_KEYS.has(type))
1053
+ return [name];
1054
+ return [name, name.replace(`${type}-`, `${RETIRED_SPEC_KEY}-`)];
1055
+ }
1056
+ /** One family spelling matched against a file name — the `{tasks}` / `{round}`
1057
+ * tokens read backwards as NAMED captures, so a family's round is read from the
1058
+ * group its own name actually carries (a document family's sole group is the
1059
+ * round; `tasks-{tasks}-implement.json`'s is the task list, never a round). A
1060
+ * positional read would resolve every `{round}`-only family to 1. */
1061
+ static #familyCaptures(spelling, name) {
1062
+ const escaped = spelling.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1063
+ const pattern = new RegExp(`^${escaped
1064
+ .replace("\\{tasks\\}", "(?<tasks>.+?)")
1065
+ .replace("\\{round\\}", "(?<round>\\d+)")}$`);
1066
+ const match = pattern.exec(name);
1067
+ if (match === null)
1068
+ return null;
1069
+ return { tasks: match.groups?.tasks ?? null, round: match.groups?.round ?? null };
627
1070
  }
628
1071
  // -------------------------------------------------------------------------
629
1072
  // crash — the lane crash → recovery record
630
1073
  // -------------------------------------------------------------------------
631
- /** The crash record file name — `crash-<lane>-<round>.json`. */
632
- crashName(lane, round) {
633
- return `crash-${lane}-${round}.json`;
634
- }
635
- /** The crash record path. */
636
- crashPath(lane, round) {
637
- return this.#workspace.resolve(this.crashName(lane, round));
638
- }
639
- /** Write a lane-crash recovery record — the resume decision source (the resume
640
- * command + the dead child's tails), never the handoff carrier. Returns the record. */
641
- writeCrash(lane, round, record) {
642
- this.#persist(this.crashName(lane, round), record);
1074
+ /** Write a crash recovery record at the name `RoundNaming` derived (the ONE
1075
+ * naming source — this face derives no name of its own). Returns the record. */
1076
+ writeCrash(name, record) {
1077
+ this.#persist(name, record);
643
1078
  return record;
644
1079
  }
645
- /** Read a crash record; null when absent/unreadable (a recordless failure round keeps
646
- * the no-next failure face). */
647
- readCrash(lane, round) {
648
- return this.#read(this.crashName(lane, round));
1080
+ /** Read a crash record by its `RoundNaming` name; null when absent/unreadable (a
1081
+ * recordless failure round keeps the no-next failure face). */
1082
+ readCrash(name) {
1083
+ return this.#read(name);
1084
+ }
1085
+ /** The round-naming single source over this ledger's workspace — the crash read /
1086
+ * write faces take the name this face derives, so the capsule's failure handoff
1087
+ * cell and the lifecycle's write point name the same file by the same rule. */
1088
+ naming() {
1089
+ return this.#naming;
649
1090
  }
650
1091
  // -------------------------------------------------------------------------
651
1092
  // round — the round carrier
@@ -690,40 +1131,44 @@ export class Ledger {
690
1131
  /** The progress key a round's dispatch records under — the same line-identity key
691
1132
  * the lifecycle records with (run.ts #lineKey): the wave task key (the only
692
1133
  * params-bearing face — every other line keys by its line-type constant:
693
- * `"branch"` / `"spec"` / `"plan"`). */
1134
+ * `"branch"` / `"phase-spec"` / `"overall"` / `"plan"` / `"single-spec"`). */
694
1135
  #roundKey(type, params) {
695
1136
  return type === "wave" ? (params.tasks ?? "") : type;
696
1137
  }
697
- /** The recorded mode one op's round records its cycle under — the review leg reads
698
- * the face table's review-lead mode (the single source: branch→branch-review, the
699
- * others→review), matching `recordRound(frame.key, frame.phase, frame.round)`; the
700
- * implement/fix legs their own name. */
701
- #recordedMode(op, type) {
702
- return op === "review" ? targetFaces[type].product.reviewLead : op;
703
- }
704
1138
  /** Read a round's concluding record as the Round the dispatch next-router judges.
705
- * A round is present ONLY when `recordRound` recorded it (the round verdict's
706
- * single source): an unrecorded round returns null whatever draft sits on disk —
707
- * a rejected child's leftover draft is never read back as a completed round
708
- * (the §2.8 gate; without it a BLOCKED round with a stale draft rendered a
709
- * contradictory `status: BLOCKED · next: done`). A fix round carries the SOURCE
710
- * review's findings (C5-1: the `--reviews` input content, never its own
1139
+ * A round is present ONLY when its recorded verdict says the round COMPLETED
1140
+ * (`targetAction === true`): a dispatched-but-failed round returns null whatever
1141
+ * draft sits on disk — a rejected child's leftover draft is never read back as a
1142
+ * completed round (the §2.8 gate; without it a BLOCKED round with a stale draft
1143
+ * rendered a contradictory `status: BLOCKED · next: done`). A fix round carries the
1144
+ * SOURCE review's findings (C5-1: the `--reviews` input content, never its own
711
1145
  * carrier); the consecutive-S1 run is walked from the review history.
712
1146
  * Missing/corrupt evaluated handoff → null too — a fix round whose source review
713
1147
  * is unreadable is never a zero-findings fabrication: a round whose blocker set
714
- * was never read must not be judged clean. */
1148
+ * was never read must not be judged clean.
1149
+ *
1150
+ * A cycle may carry several ATTEMPTS (a failed dispatch re-dispatched at the same
1151
+ * cycle); the gate reads the cycle's LATEST attempt, then judges ITS verdict.
1152
+ * Reading the first in-register record would let a failed attempt 1 shadow the
1153
+ * successful attempt 2 forever — a retry that succeeded would read as no round. */
715
1154
  round(op, type, params, round) {
716
- // §2.8 — the round-read gate: only a recorded round is a round. The test is the
1155
+ // §2.8 — the round-read gate: only a COMPLETED round is a round. The test is the
717
1156
  // round's IDENTITY (its cycle number), not a count: a fix that skipped a cycle
718
1157
  // (a drift-voided review → the first fix is cycle 2, not ordinal 1) is present at
719
1158
  // cycle 2 (D28). A count comparison would flatten that to 1 and refuse the read.
720
- if (!this.roundRecorded(this.#roundKey(type, params), this.#recordedMode(op, type), round)) {
1159
+ // Completion is the recorded VERDICT, never membership — every dispatched round
1160
+ // is recorded now, so a failed round's cycle is in register but reads no carrier.
1161
+ const recorded = this.recordsOf(this.#roundKey(type, params), type)
1162
+ .filter((record) => record.op === op && record.cycle === round)
1163
+ .reduce((latest, record) => latest === undefined || record.attempt >= latest.attempt ? record : latest, undefined);
1164
+ if (recorded === undefined || !recorded.verdict.targetAction)
721
1165
  return null;
722
- }
723
1166
  if (op === "implement") {
724
- const carrier = this.readHandoff("implement", type, params);
725
- if (carrier === null)
726
- return null;
1167
+ // An implement round is judged by its COMMITS, never by its draft (design spec
1168
+ // §3.3): the recorded verdict above is its completion face, so an absent carrier
1169
+ // is the round's soft bookkeeping observation and never a reason to refuse the
1170
+ // read. The implement round carries no carrier content — the next hop is the
1171
+ // group's review regardless — so the gate is the verdict alone.
727
1172
  return {
728
1173
  phase: "implement",
729
1174
  findings: [],
@@ -742,7 +1187,7 @@ export class Ledger {
742
1187
  // source shared with the fix leg below (`HandoffSchema.conclusionOf`).
743
1188
  status: this.#handoffSchema.conclusionOf("judge", carrier),
744
1189
  findings: this.#findingsOf(carrier),
745
- reviewsPath: this.handoffPath("review", type, reviewParams),
1190
+ reviewsPath: this.resolveHandoffPath("review", type, reviewParams),
746
1191
  consecutiveS1: this.#consecutiveS1Run(type, params, round),
747
1192
  };
748
1193
  }
@@ -762,7 +1207,7 @@ export class Ledger {
762
1207
  // work plane reads its status) — the same `conclusionOf` single source (D27).
763
1208
  status: this.#handoffSchema.conclusionOf(this.planeOf("fix"), fixCarrier),
764
1209
  findings: this.#findingsOf(reviewCarrier),
765
- reviewsPath: this.handoffPath("review", type, reviewParams),
1210
+ reviewsPath: this.resolveHandoffPath("review", type, reviewParams),
766
1211
  consecutiveS1: this.#consecutiveS1Run(type, params, round),
767
1212
  };
768
1213
  }