@oscaner-skills/cdd-engine 1.0.0 → 3.0.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 (120) hide show
  1. package/README.md +11 -10
  2. package/README.zh-CN.md +11 -10
  3. package/package.json +16 -22
  4. package/src-next/__tests__/bin.test.ts +128 -0
  5. package/src-next/__tests__/dead-decl.guard.test.ts +39 -0
  6. package/src-next/__tests__/floor.guard.test.ts +69 -0
  7. package/src-next/__tests__/issue-body.guard.test.ts +66 -0
  8. package/src-next/__tests__/phase-suffix.guard.test.ts +72 -0
  9. package/src-next/__tests__/smoke.integration.test.ts +185 -0
  10. package/src-next/__tests__/support/strip-comments.ts +99 -0
  11. package/src-next/__tests__/zero-dep.test.ts +94 -0
  12. package/src-next/bin.ts +61 -0
  13. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +256 -0
  14. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +165 -0
  15. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +190 -0
  16. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +106 -0
  17. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +240 -0
  18. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +165 -0
  19. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +190 -0
  20. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +100 -0
  21. package/src-next/contract/__tests__/declare.test.ts +481 -0
  22. package/src-next/contract/__tests__/doc.test.ts +527 -0
  23. package/src-next/contract/__tests__/dockey.guard.test.ts +58 -0
  24. package/src-next/contract/__tests__/edge-conditions.guard.test.ts +81 -0
  25. package/src-next/contract/__tests__/frontmatter.test.ts +164 -0
  26. package/src-next/contract/__tests__/judge.test.ts +1111 -0
  27. package/src-next/contract/__tests__/lint.test.ts +324 -0
  28. package/src-next/contract/__tests__/project.test.ts +460 -0
  29. package/src-next/contract/__tests__/structure-pin.test.ts +186 -0
  30. package/src-next/contract/__tests__/translate.test.ts +96 -0
  31. package/src-next/contract/declare.ts +1071 -0
  32. package/src-next/contract/doc.ts +816 -0
  33. package/src-next/contract/frontmatter.ts +233 -0
  34. package/src-next/contract/home-extractors.ts +397 -0
  35. package/src-next/contract/invariants.ts +1413 -0
  36. package/src-next/contract/judge.ts +151 -0
  37. package/src-next/contract/lint.ts +239 -0
  38. package/src-next/contract/project.ts +656 -0
  39. package/src-next/contract/skill-anatomy.ts +301 -0
  40. package/src-next/contract/translate.ts +113 -0
  41. package/src-next/face/__tests__/board-view.test.ts +1151 -0
  42. package/src-next/face/__tests__/capsule.test.ts +300 -0
  43. package/src-next/face/__tests__/channel-closure.guard.test.ts +129 -0
  44. package/src-next/face/__tests__/cli.test.ts +4897 -0
  45. package/src-next/face/__tests__/face.test.ts +289 -0
  46. package/src-next/face/__tests__/graph-view.test.ts +61 -0
  47. package/src-next/face/__tests__/host.test.ts +24 -0
  48. package/src-next/face/__tests__/install-rows.guard.test.ts +58 -0
  49. package/src-next/face/__tests__/negation.ts +6 -0
  50. package/src-next/face/__tests__/preview.test.ts +374 -0
  51. package/src-next/face/__tests__/projection.test.ts +303 -0
  52. package/src-next/face/__tests__/repo-root.guard.test.ts +120 -0
  53. package/src-next/face/__tests__/termination.test.ts +650 -0
  54. package/src-next/face/__tests__/words.guard.test.ts +93 -0
  55. package/src-next/face/artifacts.ts +248 -0
  56. package/src-next/face/board-view.ts +652 -0
  57. package/src-next/face/capsule.ts +163 -0
  58. package/src-next/face/cli.ts +1028 -0
  59. package/src-next/face/declare.ts +323 -0
  60. package/src-next/face/gate.ts +171 -0
  61. package/src-next/face/graph-view.ts +74 -0
  62. package/src-next/face/host.ts +302 -0
  63. package/src-next/face/lifecycle.ts +725 -0
  64. package/src-next/face/preview.ts +151 -0
  65. package/src-next/face/projection.ts +285 -0
  66. package/src-next/face/route-render.ts +185 -0
  67. package/src-next/face/termination.ts +573 -0
  68. package/src-next/face/words.ts +314 -0
  69. package/src-next/infra/__tests__/infra.test.ts +333 -0
  70. package/src-next/infra/__tests__/root.test.ts +56 -0
  71. package/src-next/infra/config.ts +42 -0
  72. package/src-next/infra/doc-roots.ts +29 -0
  73. package/src-next/infra/git.ts +39 -0
  74. package/src-next/infra/process.ts +34 -0
  75. package/src-next/infra/root.ts +73 -0
  76. package/src-next/infra/runtime.ts +132 -0
  77. package/src-next/infra/workspace.ts +322 -0
  78. package/src-next/render/__tests__/render.test.ts +550 -0
  79. package/src-next/render/__tests__/skeleton.test.ts +684 -0
  80. package/src-next/render/brief.ts +121 -0
  81. package/src-next/render/issue-body.ts +162 -0
  82. package/src-next/render/skeleton.ts +502 -0
  83. package/src-next/render/templates.ts +645 -0
  84. package/src-next/session/__tests__/graph.test.ts +277 -0
  85. package/src-next/session/__tests__/handoff-plane.guard.test.ts +48 -0
  86. package/src-next/session/__tests__/handoff-schema.test.ts +310 -0
  87. package/src-next/session/__tests__/ledger.test.ts +745 -0
  88. package/src-next/session/__tests__/next.test.ts +460 -0
  89. package/src-next/session/__tests__/preflight.test.ts +545 -0
  90. package/src-next/session/__tests__/round-naming.test.ts +142 -0
  91. package/src-next/session/__tests__/run.test.ts +1026 -0
  92. package/src-next/session/__tests__/wave-line-phase.guard.test.ts +49 -0
  93. package/src-next/session/__tests__/wave.test.ts +476 -0
  94. package/src-next/session/faces.ts +110 -0
  95. package/src-next/session/graph.ts +411 -0
  96. package/src-next/session/handoff-schema.ts +373 -0
  97. package/src-next/session/ledger.ts +1076 -0
  98. package/src-next/session/next.ts +293 -0
  99. package/src-next/session/preflight.ts +271 -0
  100. package/src-next/session/round-naming.ts +84 -0
  101. package/src-next/session/run.ts +610 -0
  102. package/src-next/session/state.ts +30 -0
  103. package/src-next/session/wave.ts +139 -0
  104. package/templates/report/issue-body.json +17 -65
  105. package/dist/chunks/branch.mjs +0 -480
  106. package/dist/chunks/docs.mjs +0 -253
  107. package/dist/chunks/task.mjs +0 -913
  108. package/dist/cli.mjs +0 -5457
  109. package/dist/documents/schema/add-phase-protocol.json +0 -126
  110. package/dist/documents/schema/overall.json +0 -361
  111. package/dist/documents/schema/phase-spec.json +0 -145
  112. package/dist/documents/schema/plan.json +0 -191
  113. package/dist/documents/schema/skill-anatomy.json +0 -233
  114. package/dist/resources/harness-registry.json +0 -49
  115. package/dist/shared/cdd-engine.liioziig.mjs +0 -184
  116. package/templates/engine-config.json +0 -302
  117. package/templates/schema/cache-profile-schema.json +0 -23
  118. package/templates/schema/docs-handoff-schema.json +0 -129
  119. package/templates/schema/task-handoff-schema.json +0 -332
  120. package/templates/template-contract.json +0 -231
@@ -0,0 +1,1076 @@
1
+ // packages/cdd-engine/src-next/session/ledger.ts
2
+ // T9 — the session ledger (design spec §6.1): ONE class owns the four on-disk
3
+ // session artifacts — progress (the fixed key set), handoff (build/name/persist),
4
+ // crash (the lane-crash recovery record) and round (the round carrier). The write
5
+ // authority is the engine alone: every artifact write routes through the ledger's
6
+ // single persist point, so the engine owns the on-disk record of every round.
7
+ //
8
+ // · progress — `progress.json`, the fixed top-level key set (plan + the five
9
+ // failure-category counters, verbatim from engine-config) + the per-key rows
10
+ // (scalar task or the group key string, each carrying its rounds {}).
11
+ // · handoff — the canonical family naming (engine-config handoff namespace), the
12
+ // carrier skeleton (the schema-required identity keys), the single-author write.
13
+ // · crash — `crash-<lane>-<round>.json`, the recovery record (the same-command
14
+ // resume decision source — the resume command + the dead child's tails, never the
15
+ // handoff carrier's union).
16
+ // · round — the round carrier: the handoff presented as the Round the dispatch
17
+ // next-router judges. A fix round carries the SOURCE review's findings (the
18
+ // `--reviews` input content, C5-1), never its own; the consecutive-S1 run is
19
+ // walked from the round history (the review-cycle soft-cap basis).
20
+ //
21
+ // Module-level exports are types / constant data / the class — zero behavior-
22
+ // carrying bare functions (the plan's zero-bare-function discipline).
23
+
24
+ import { createHash } from "node:crypto";
25
+ import { readFileSync } from "node:fs";
26
+ import type { ConfigLoader } from "../infra/config.ts";
27
+ import type { RepoPath, RepoRoot } from "../infra/root.ts";
28
+ import type { HandoffFamily } from "../infra/runtime.ts";
29
+ import type { Workspace } from "../infra/workspace.ts";
30
+ import { BriefRenderer } from "../render/brief.ts";
31
+ import { type TargetType, targetFaces } from "./faces.ts";
32
+ import {
33
+ type FindingsCarrier,
34
+ HandoffSchema,
35
+ type HandoffSchemaFace,
36
+ type WorkCarrier,
37
+ } from "./handoff-schema.ts";
38
+ import type { Route } from "./next.ts";
39
+ import { NextStepRouter } from "./next.ts";
40
+ import { EMPTY_RUN_STATE } from "./run.ts";
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // the round carrier — what NextStepRouter.next (T7) judges
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /** The work face's writable init — the schema-declared optional fields a work carrier
47
+ * starts from. The round conclusion (status) rides the CALLER's set — never a
48
+ * build-time value: the skeleton holds only the schema's declared writable plane. */
49
+ type WorkInit = {
50
+ artifacts?: Record<string, string>;
51
+ };
52
+
53
+ /** The findings face's writable init — `findings` is the schema-REQUIRED field of the
54
+ * findings face (the compile-time twin of the read-back required gate — a findings
55
+ * init omitting it is a type error), artifacts optional. */
56
+ type FindingsInit = {
57
+ findings: unknown[];
58
+ artifacts?: Record<string, string>;
59
+ };
60
+
61
+ /** The review-finding severity vocabulary — the handoff findings severity enum, single-typed. */
62
+ export type FindingSeverity = "blocker" | "warn" | "nit";
63
+
64
+ /** One review finding the round carrier judges — severity + the summary prose. */
65
+ export interface RoundFinding {
66
+ /** The severity the next-hop derivation keys on. */
67
+ severity: FindingSeverity;
68
+ /** The one-line finding summary (message attribution; the router reads only severity). */
69
+ summary?: string;
70
+ }
71
+
72
+ /** The dispatch phases the round carrier distinguishes (the handoff phase vocabulary). */
73
+ export type OpType = "implement" | "review" | "fix";
74
+ export type RoundPhase = OpType | "branch-review";
75
+
76
+ /** The round-concluding statuses the router's failure face reads. */
77
+ export type RoundStatus = "APPROVED" | "BLOCKED" | "TIMEOUT" | "CHANGES_REQUESTED" | "REVIEW_FIX";
78
+
79
+ /**
80
+ * The round carrier — one session round's readable record: the canonical handoff
81
+ * presented as the facts the next-router judges. A work round carries the field
82
+ * values its dispatch concluded (status); a fix round's findings ARE the
83
+ * source review's input findings (C5-1), never the fix's own carrier.
84
+ */
85
+ export interface Round {
86
+ /** The round's dispatch phase. */
87
+ phase: RoundPhase;
88
+ /** The concluding status (review-family rounds may omit it — derived from findings). */
89
+ status?: RoundStatus;
90
+ /** The findings the next-hop derivation judges. */
91
+ findings: readonly RoundFinding[];
92
+ /** The review handoff path (fix: the `--reviews` input; review: its own handoff). */
93
+ reviewsPath?: string;
94
+ /** The consecutive-S1 run (the leading blocker-lead reviews, newest first) — the
95
+ * review-cycle soft-cap basis. */
96
+ consecutiveS1: number;
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // progress — the fixed key set
101
+ // ---------------------------------------------------------------------------
102
+
103
+ /** The fixed counter key set — the five engine-config failure-category counters, verbatim. */
104
+ export const PROGRESS_COUNTER_ZERO = {
105
+ timeoutCount: 0,
106
+ contractViolationCount: 0,
107
+ engineSelfWrittenCount: 0,
108
+ engineRecoveryCount: 0,
109
+ harnessAbortCount: 0,
110
+ } as const;
111
+
112
+ /** The counter member keys — the derived literal union (never re-typed). */
113
+ export type ProgressCounterKey = keyof typeof PROGRESS_COUNTER_ZERO;
114
+
115
+ /** One progress row — keyed by the wave key string (T26 · the wave-unitary model:
116
+ * every dispatch is a wave — `--tasks 1` is the single-task wave `"1"`, `--tasks
117
+ * 1,2` the wave `"1,2"` — one row form, never a task/wave split). */
118
+ export type ProgressRow = {
119
+ /** The wave key string — the dispatch group identity (`"1"` · `"1,2"`). */
120
+ wave: string;
121
+ /** The completed rounds per mode (implement/review/fix), each as its CYCLE NUMBER —
122
+ * the round's IDENTITY, not a count (D28 · one fact one place). A fix cycle equals
123
+ * the review cycle it addressed (fix-K ⟷ review-K), so a fix that skips a cycle
124
+ * (a drift-voided review) records its identity — `[2]` — where a count would have
125
+ * flattened it to `1` and diverged from the carrier name `fix-2`. Review cycles are
126
+ * contiguous (1..N); `implement` is `[1]`. */
127
+ rounds?: Record<string, number[]>;
128
+ /** The line's reviewed identity — the doc-revision a spec/plan line bound (T7) OR
129
+ * the brief-revision a wave line bound (D30). Written at review completion; the
130
+ * identity-aware gate reopens the closed line on drift from it. The two kinds are
131
+ * mutually exclusive per row (a line is a doc line or a wave line, never both). */
132
+ reviewedRevision?: ReviewedRevisionRef;
133
+ };
134
+
135
+ /** The progress.json data plane — the fixed top-level key set + the per-wave rows. */
136
+ export interface ProgressData {
137
+ /** The `--plan` path recorded at first create. */
138
+ plan?: string;
139
+ timeoutCount: number;
140
+ contractViolationCount: number;
141
+ engineSelfWrittenCount: number;
142
+ engineRecoveryCount: number;
143
+ harnessAbortCount: number;
144
+ waves: ProgressRow[];
145
+ }
146
+
147
+ /** The ledger lookup key — a scalar task id or the group key string. */
148
+ export type LedgerKey = number | string;
149
+
150
+ /** The dispatch-termination vocabulary — why a round was cut short (single source:
151
+ * the terminator derives the cause from the child's own result face, the crash
152
+ * record carries it as a postmortem fact, zero behavior fork — resume never routes
153
+ * on it). `stalled` = the engine's stall judgment killed the child; `over-budget` =
154
+ * the wall-clock ceiling was reached; `signal` = an external signal killed the
155
+ * child (any signal, one semantic — never the SIGTERM literal). */
156
+ export type TerminationCause = "stalled" | "over-budget" | "signal";
157
+
158
+ /** The stall judge's verdict per sample tick: `progress` (a leg advanced), `unknown`
159
+ * (a leg is unreadable — the fail-open state, never a kill), `idled` (no progress
160
+ * yet, the idle window is open) and `stalled` (no progress and the window is spent
161
+ * — the kill). */
162
+ export type StallVerdict = "progress" | "unknown" | "idled" | "stalled";
163
+
164
+ /** One sample tick's two legs — the process group's cumulative CPU (ms) and the
165
+ * newest mtime (ms) of the scanned tree. `null` = that leg is unreadable (the
166
+ * fail-open face: an unreadable leg never authorizes a kill). The field names are
167
+ * the heartbeat record's names (one naming, two references). */
168
+ export interface Sample {
169
+ groupCpuMs: number | null;
170
+ newestMtimeMs: number | null;
171
+ }
172
+
173
+ /** The recorded sample — a `Sample` extended with its tick's timestamp and the
174
+ * judge's verdict (the heartbeat file's field set; the crash record embeds it). */
175
+ export interface SampleRecord extends Sample {
176
+ sampledAt: number;
177
+ verdict: StallVerdict;
178
+ }
179
+
180
+ /** The lane-crash cause vocabulary — postmortem classification of why a dispatch
181
+ * terminated before the exit gate (zero behavior fork: resume never routes on it).
182
+ * The termination causes cover the round that was cut short; `child-exit` is the
183
+ * child's own non-zero exit, `contract-violation` the read-back face (the child
184
+ * exited 0 but produced no draft or a schema-violating one — the engine BLOCKs +
185
+ * preserves the draft + stores the same-command resume), and `unknown` the
186
+ * unattributable termination fallback. */
187
+ export type CrashCause = TerminationCause | "child-exit" | "contract-violation" | "unknown";
188
+
189
+ /** The crash record — the lane crash's recovery record (`crash-<lane>-<round>.json`):
190
+ * the same-command resume's decision source (the resume command + the dead child's
191
+ * tails), never the handoff carrier. */
192
+ export interface CrashRecord {
193
+ /** The dead child's exit code — null when the child never spawned (a broken
194
+ * command) or was terminated by a signal (a signalled child has no exit code;
195
+ * the signal semantics ride the `cause`). */
196
+ exitCode: number | null;
197
+ /** The dead child's stderr tail (the "403 / abort without trace" tail — the
198
+ * caller's captured lines, no fixed tail-length constant). */
199
+ stderrTail: readonly string[];
200
+ /** The dead child's stdout tail. */
201
+ stdoutTail: readonly string[];
202
+ /** The handoff path the dead child was expected to write (null when the lane carries none). */
203
+ attemptedHandoff: string | null;
204
+ /** The same-command resume string — emitted verbatim as `next: <resumeCommand>`. */
205
+ next: string;
206
+ /** The unified termination cause — postmortem, zero behavior fork. */
207
+ cause: CrashCause;
208
+ /** The terminated round's last observed sample (the stall face's postmortem pair) —
209
+ * null when the round was not cut short or no sample was ever taken. The sample
210
+ * rides the termination fact in memory (zero re-read of the heartbeat file the
211
+ * engine itself wrote); the on-disk heartbeat stays for a human's postmortem. */
212
+ lastSample: SampleRecord | null;
213
+ }
214
+
215
+ // ---------------------------------------------------------------------------
216
+ // handoff — the family naming params
217
+ // ---------------------------------------------------------------------------
218
+
219
+ /** Per-family handoff params — the canonical name placeholders of the handoff
220
+ * namespace families ({tasks}/{round}; the branch family keys by `branch-{op}-{round}`,
221
+ * no range token — the branch line holds no commit identity). */
222
+ export interface HandoffParams {
223
+ /** The dispatch group's key string (comma-joined task ids). */
224
+ tasks?: string;
225
+ /** The round number (increment/source families). */
226
+ round?: number | string;
227
+ }
228
+
229
+ // ---------------------------------------------------------------------------
230
+ // review references — the refKind face (T25 · P5)
231
+ // ---------------------------------------------------------------------------
232
+
233
+ /** The review-reference kind — each line-type binds its OWN reviewed identity (D30:
234
+ * honest identity, one concept one name — a `doc_hash` layer must never point at a
235
+ * non-document). `doc-revision` = the spec/plan line (the whole document file + its
236
+ * content hash); `brief-revision` = the wave line (the plan it renders FROM + the
237
+ * RENDERED brief's content hash — the wave's true judgment input, never the plan).
238
+ * The commit-bearing kinds (commit-set-ledger · commit-range) retired with the
239
+ * commit-sha surface (P7): a review judges the live tree, so no committed range
240
+ * is ever a ref. Node-level review is structurally absent (R5 · the wave-atomic
241
+ * model audits whole waves, never a single task node). */
242
+ export type RefKind = "doc-revision" | "brief-revision";
243
+
244
+ /** The doc-revision ref — the spec/plan review's two-layer ref: the document path
245
+ * AND its revision (the content-hash `doc_hash` binding — the same document
246
+ * revision reviewed twice is the same ref, rejected by the same-ref ruling). */
247
+ export interface DocRevisionRef {
248
+ kind: "doc-revision";
249
+ /** The document path — the first layer of the two-layer ref. */
250
+ doc: string;
251
+ /** The document revision — the sha1 content hash of the reviewed file. */
252
+ doc_hash: string;
253
+ }
254
+
255
+ /** The brief-revision ref (D30) — the wave line's two-layer ref: the plan path the
256
+ * brief renders FROM (the re-render pointer judgment time needs) AND the RENDERED
257
+ * brief's content hash. The wave's judgment input is the brief (§5: its task
258
+ * sections + `## Constraints`), never the whole plan — so a plan edit outside the
259
+ * wave's tasks leaves this ref identical and the reviewed wave is not reopened. */
260
+ export interface BriefRevisionRef {
261
+ kind: "brief-revision";
262
+ /** The plan path the brief renders from — the first layer (the re-render pointer). */
263
+ plan: string;
264
+ /** The RENDERED brief's revision — the sha1 content hash of the brief, the second layer. */
265
+ brief_hash: string;
266
+ }
267
+
268
+ /** The reviewed-identity ref a progress row binds — the doc-revision (a spec/plan
269
+ * line) OR the brief-revision (a wave line); the two are mutually exclusive per row. */
270
+ export type ReviewedRevisionRef = DocRevisionRef | BriefRevisionRef;
271
+
272
+ /**
273
+ * ReviewRefs — the review-reference face (T25): the two-layer bindings (`docRevision`
274
+ * — the doc hash from its content · `briefRevision` — the rendered brief's hash from
275
+ * the plan it renders from) and the same-ref predicate (the SAME identity already
276
+ * bound is refused, never silently re-reviewed). The face is the ledger's review-ref
277
+ * derivation point — typed data, zero prose.
278
+ */
279
+ export class ReviewRefs {
280
+ /** The doc-revision two-layer binding — the doc path + the content-hash revision
281
+ * (sha1 of the reviewed file content — the second layer of the doc ref). */
282
+ docRevision(doc: string, content: string | Buffer): DocRevisionRef {
283
+ return { kind: "doc-revision", doc, doc_hash: this.#hash(content) };
284
+ }
285
+
286
+ /** The brief-revision two-layer binding (D30) — the plan path the brief renders
287
+ * from + the RENDERED brief content's hash (the wave line's reviewed identity). */
288
+ briefRevision(plan: string, briefContent: string | Buffer): BriefRevisionRef {
289
+ return { kind: "brief-revision", plan, brief_hash: this.#hash(briefContent) };
290
+ }
291
+
292
+ /** The ref-identity predicate — two refs are the SAME ref when same-kind AND their
293
+ * two-layer identity matches (the layer-1 path + the layer-2 hash). Two refs of
294
+ * different kinds are never the same ref (a doc-revision never equals a
295
+ * brief-revision — the kind IS part of the identity). */
296
+ sameRef(a: ReviewedRevisionRef, b: ReviewedRevisionRef): boolean {
297
+ if (a.kind === "doc-revision" && b.kind === "doc-revision")
298
+ return a.doc === b.doc && a.doc_hash === b.doc_hash;
299
+ if (a.kind === "brief-revision" && b.kind === "brief-revision")
300
+ return a.plan === b.plan && a.brief_hash === b.brief_hash;
301
+ return false;
302
+ }
303
+
304
+ /** The content-hash revision — sha1 hex of the reviewed content. */
305
+ #hash(content: string | Buffer): string {
306
+ // The revision hash is a content digest (a fingerprint of the reviewed bytes),
307
+ // never a commit ref — the full sha1 hex stays unsliced so the bind basis covers
308
+ // the whole content, not a truncated prefix.
309
+ return createHash("sha1").update(content).digest("hex");
310
+ }
311
+ }
312
+
313
+ // ---------------------------------------------------------------------------
314
+ // the review gate — the T8 doc-revision-first verdict (spec §3.5)
315
+ // ---------------------------------------------------------------------------
316
+
317
+ /** The review-gate verdict (T8 · §3.5 · v0.12 ruled) — the doc line's review
318
+ * request judgment, doc-revision FIRST: a doc moved past the reviewed revision
319
+ * OPENS the review lead whatever the round/route state says (fix after · backfill
320
+ * after · user-decision after are the SAME case — the stuck "next round is fix
321
+ * after an aborted fix" path never freezes a revised doc); an unchanged doc stays
322
+ * REJECTED (Review Convergence anti-spin), with the pending fix DERIVED from the
323
+ * latest review's non-APPROVED conclusion — zero independent state field (the
324
+ * progress.json key set carries no pending-fix key). `unbound` = no reviewed
325
+ * identity on record or an unreadable doc — the legacy round/route judgment
326
+ * keeps the generic closed face (only present facts land). */
327
+ export type ReviewGateVerdict =
328
+ /** drift — the review lead opens (the lifecycle + the face gate dispatch review). */
329
+ | { kind: "open" }
330
+ /** same — the line stays rejected; `pending` is the derived fix-awaited face
331
+ * (the review's own fix is outstanding), `reviewed` the bound identity the
332
+ * rejection messages name (the already-reviewed block / the pending-fix note). */
333
+ | { kind: "same"; pending: boolean; reviewed: DocRevisionRef }
334
+ /** unbound — no identity on record / the doc unreadable: the legacy judgment. */
335
+ | { kind: "unbound" };
336
+
337
+ // ---------------------------------------------------------------------------
338
+ // the ledger
339
+ // ---------------------------------------------------------------------------
340
+
341
+ /**
342
+ * Ledger — the session's on-disk single author. One instance per workspace;
343
+ * every artifact write (progress / handoff / crash) routes through the same
344
+ * private persist point, so the engine owns the record of every round.
345
+ */
346
+ export class Ledger {
347
+ /** The one dispatch workspace this ledger records. */
348
+ readonly #workspace: Workspace;
349
+ /** The handoff-family records, keyed by `op.type` — the naming truth the ledger fills. */
350
+ readonly #families: Readonly<Record<string, HandoffFamily>>;
351
+ /** The C5 next router — the closure-side judge of the round carriers (stateless;
352
+ * the `closedWaves()` read face and the wave gate share the same router). */
353
+ readonly #router = new NextStepRouter();
354
+ /** The handoff-schema face — the conclusion single source (`conclusionOf`), one
355
+ * instance per ledger (the round verdict derives from the face's own plane at
356
+ * judgment time · D27). */
357
+ readonly #handoffSchema = new HandoffSchema();
358
+ /** The review-reference face (T25) — the refKind classification + the same-ref
359
+ * reject, one instance per ledger (the run's bound refs). */
360
+ readonly #refs = new ReviewRefs();
361
+ /** The task-brief renderer (D30) — the wave line's judgment-input derivation:
362
+ * the wave's reviewed basis is the RENDERED brief's content, never the whole
363
+ * plan (a backfill touching other tasks must not void a reviewed wave). */
364
+ readonly #brief = new BriefRenderer();
365
+
366
+ constructor(workspace: Workspace, config: ConfigLoader) {
367
+ this.#workspace = workspace;
368
+ this.#families = config.handoffNamespace().families;
369
+ }
370
+
371
+ /** The review-reference face — the refKind three-type derivation + binding (T25). */
372
+ refs(): ReviewRefs {
373
+ return this.#refs;
374
+ }
375
+
376
+ /** The ledger's repo-basis value object — the ONE conversion exit every persisted
377
+ * path field normalizes through (T1 `RepoRoot` · P9 T4 §2.7). The basis is the
378
+ * workspace root's OWN value object (built once at the root's boundary) — never
379
+ * re-wrapped here (branch-review-1 F2: one basis, one form). */
380
+ #basis(): RepoRoot {
381
+ return this.#workspace.root.basis;
382
+ }
383
+
384
+ /** Normalize a path value to the canonical repoRoot-relative `RepoPath` — the
385
+ * comparison/write side of the shapes fix (a persisted relative value and an
386
+ * incoming absolute argv value compare on ONE basis). */
387
+ #rel(value: string): RepoPath {
388
+ return this.#basis().relativize(value);
389
+ }
390
+
391
+ /** Erase a (possibly relative) path value to the absolute syscall string for a
392
+ * read (a legacy relative persisted value resolves against the basis, never
393
+ * `process.cwd()`). */
394
+ #abs(value: string): string {
395
+ return this.#basis().resolve(this.#basis().relativize(value));
396
+ }
397
+
398
+ // ---- the single author's write/read primitives ----
399
+
400
+ /** Persist a JSON artifact — the ledger's single write point (engine sole author). */
401
+ #persist(name: string, data: unknown): void {
402
+ this.#workspace.writeJson(name, data);
403
+ }
404
+
405
+ /** Read a JSON artifact; null when missing/corrupt (the ledger's read face keeps the
406
+ * collapsed contract — the tri-state discrimination lives at the read-back
407
+ * reconstruct, which reports a malformed draft's true cause). */
408
+ #read<T>(name: string): T | null {
409
+ const read = this.#workspace.readJson<T>(name);
410
+ return read.kind === "ok" ? read.value : null;
411
+ }
412
+
413
+ // -------------------------------------------------------------------------
414
+ // progress — the fixed key set
415
+ // -------------------------------------------------------------------------
416
+
417
+ /** The base progress object — the fixed key set at zero, for a fresh session. */
418
+ emptyProgress(): ProgressData {
419
+ return { ...PROGRESS_COUNTER_ZERO, waves: [] };
420
+ }
421
+
422
+ /** Read progress.json; null when missing/corrupt (the ledger never invents state). */
423
+ readProgress(): ProgressData | null {
424
+ return this.#read<ProgressData>("progress.json");
425
+ }
426
+
427
+ /** Write progress.json — the progress single-author write. */
428
+ writeProgress(data: ProgressData): void {
429
+ this.#persist("progress.json", data);
430
+ }
431
+
432
+ /** The ledger-row lookup single point — a scalar key (or the single-task wave key
433
+ * `"1"`) resolves the `{ task }` row; a multi-task wave key (`"1,2"`) the `{ wave }` row. */
434
+ rowFor(data: ProgressData, key: LedgerKey): ProgressRow | undefined {
435
+ return data.waves.find((row) => row.wave === String(key));
436
+ }
437
+
438
+ /** The fresh row for an absent key — always the wave form (a single trivial
439
+ * wave `"1"` is still the `{ wave: "1" }` row — one row form, T26). */
440
+ entryFor(key: LedgerKey): ProgressRow {
441
+ return { wave: String(key) };
442
+ }
443
+
444
+ /** One mode's recorded cycle numbers on a row — the raw identity list, normalizing a
445
+ * legacy numeric count (`fix: 1`) to its assumed contiguous identity (`[1]`, the old
446
+ * 1:1 assumption). Absent/empty → `[]`. */
447
+ #cyclesOf(row: ProgressRow | undefined, mode: string): readonly number[] {
448
+ const raw = row?.rounds?.[mode];
449
+ if (raw === undefined) return [];
450
+ return Array.isArray(raw) ? raw : Array.from({ length: raw }, (_unused, index) => index + 1);
451
+ }
452
+
453
+ /** The last completed round of a dispatch key + mode — 0 when none on record (the
454
+ * round COUNT: the length of the recorded cycle set — for a contiguous review line
455
+ * this equals the latest cycle, but the identity is the cycle list, never the count). */
456
+ roundCount(key: LedgerKey, mode: string): number {
457
+ const data = this.readProgress();
458
+ if (data === null) return 0;
459
+ return this.#cyclesOf(this.rowFor(data, key), mode).length;
460
+ }
461
+
462
+ /** Whether a dispatch key + mode has a round recorded for a given CYCLE — the
463
+ * identity test the round-read gate uses (a fix cycle that skipped a number is
464
+ * present at its own number, not at its ordinal — D28). */
465
+ roundRecorded(key: LedgerKey, mode: string, cycle: number): boolean {
466
+ const data = this.readProgress();
467
+ if (data === null) return false;
468
+ return this.#cyclesOf(this.rowFor(data, key), mode).includes(cycle);
469
+ }
470
+
471
+ /** Record a completed round — the on-disk done record (the ledger edge of the
472
+ * ExecutionState carrier: TaskGraph in memory, the ledger on disk). The round's
473
+ * CYCLE is its identity (fix-K ⟷ review-K · D28), so a skipped cycle records its
474
+ * own number, never a flattened ordinal. The production caller passes the frame's
475
+ * own `round`; the default (the next cycle after the latest) records a sequential
476
+ * round. Creates the row on demand; the write is idempotent per cycle (a re-record
477
+ * of the same cycle does not double it). */
478
+ recordRound(key: LedgerKey, mode: string, cycle?: number): number {
479
+ const data = this.readProgress() ?? this.emptyProgress();
480
+ let row = this.rowFor(data, key);
481
+ if (row === undefined) {
482
+ row = this.entryFor(key);
483
+ data.waves.push(row);
484
+ }
485
+ const cycles = [...this.#cyclesOf(row, mode)];
486
+ const recorded = cycle ?? (cycles.length > 0 ? Math.max(...cycles) + 1 : 1);
487
+ if (!cycles.includes(recorded)) cycles.push(recorded);
488
+ cycles.sort((a, b) => a - b);
489
+ row.rounds = { ...row.rounds, [mode]: cycles };
490
+ this.writeProgress(data);
491
+ return cycles.length;
492
+ }
493
+
494
+ /** Record a line's reviewed identity — the identity-aware gate's basis (written
495
+ * when the review round completes: the line reopens on drift from this recorded
496
+ * revision, and BLOCKs revision-aware when unchanged). The kind IS part of the
497
+ * identity: a doc line binds a doc-revision (T7), a wave line a brief-revision
498
+ * (D30) — one row, one reviewed identity. */
499
+ recordReviewedRevision(key: LedgerKey, revision: ReviewedRevisionRef): void {
500
+ const data = this.readProgress() ?? this.emptyProgress();
501
+ let row = this.rowFor(data, key);
502
+ if (row === undefined) {
503
+ row = this.entryFor(key);
504
+ data.waves.push(row);
505
+ }
506
+ row.reviewedRevision = revision;
507
+ this.writeProgress(data);
508
+ }
509
+
510
+ /** Record a wave line's reviewed BRIEF revision (D30) — the RENDERED brief's
511
+ * content hash for the wave's tasks: the wave's true judgment input is the brief
512
+ * (§5: the wave's task sections + the plan's `## Constraints`), never the whole
513
+ * plan. A backfill touching OTHER tasks leaves this brief byte-identical, so the
514
+ * reviewed wave is not spuriously reopened (the backfill's whole point). An
515
+ * underivable brief records nothing (present facts only — the legacy face holds). */
516
+ recordReviewedBrief(waveKey: string, planPath: string): void {
517
+ const revision = this.#briefRevision(waveKey, planPath);
518
+ if (revision !== null) this.recordReviewedRevision(waveKey, revision);
519
+ }
520
+
521
+ /** The wave line's reviewed-basis revision (D30) — the RENDERED brief's content
522
+ * hash for the wave's tasks (the `plan` layer is the plan the brief renders from,
523
+ * the `brief_hash` layer the brief's own digest). Null when the plan is unreadable
524
+ * or a requested task is absent (present facts only). */
525
+ #briefRevision(waveKey: string, planPath: string): BriefRevisionRef | null {
526
+ try {
527
+ const tasks = waveKey.split(",").map((part) => Number(part));
528
+ // The plan layer is stored repoRoot-relative (P9 T4 §2.7) — one basis with
529
+ // every persisted path field; the read erases to absolute at the syscall edge.
530
+ const brief = this.#brief.render(readFileSync(this.#abs(planPath), "utf8"), tasks);
531
+ return this.#refs.briefRevision(this.#rel(planPath), brief);
532
+ } catch {
533
+ return null;
534
+ }
535
+ }
536
+
537
+ /** A line's recorded reviewed identity — null when none on record (a line with no
538
+ * reviewed identity keeps the legacy closed face). Callers narrow by `kind`: a doc
539
+ * line binds a doc-revision, a wave line a brief-revision (the kinds never mix). */
540
+ reviewedRevisionOf(key: LedgerKey): ReviewedRevisionRef | null {
541
+ const data = this.readProgress();
542
+ if (data === null) return null;
543
+ return this.rowFor(data, key)?.reviewedRevision ?? null;
544
+ }
545
+
546
+ /** The doc line's recorded reviewed doc revision — the doc-revision narrowing of
547
+ * `reviewedRevisionOf` (null when none on record, or when a non-doc kind sits on
548
+ * the row — a doc line is never a wave line). */
549
+ reviewedDocRevisionOf(key: LedgerKey): DocRevisionRef | null {
550
+ const reviewed = this.reviewedRevisionOf(key);
551
+ return reviewed !== null && reviewed.kind === "doc-revision" ? reviewed : null;
552
+ }
553
+
554
+ /** The doc line's identity verdict (T7) — the current doc revision vs the line's
555
+ * recorded reviewed revision: the ONE shared comparison across the session
556
+ * plane's reopen decision and the face plane's drift gate (both planes
557
+ * out-source the read + the same-ref ruling here — a single error policy).
558
+ * `drift` → the target moved past the reviewed identity (the line reopens);
559
+ * `same` → unchanged (the revision-aware BLOCK). Null when no reviewed revision
560
+ * is on record or the doc is unreadable (the legacy closed face keeps its
561
+ * generic message — only present facts land). */
562
+ docLineVerdict(key: LedgerKey, doc: string): "drift" | "same" | null {
563
+ const reviewed = this.reviewedDocRevisionOf(key);
564
+ if (reviewed === null) return null;
565
+ try {
566
+ // Both sides on ONE basis (P9 T4 §2.7): the recorded ref is repoRoot-relative;
567
+ // the incoming target (an absolute argv-erasure) is relativized here so the
568
+ // false-drift comparison never reads one document as two.
569
+ const rel = this.#rel(doc);
570
+ const current = this.#refs.docRevision(rel, readFileSync(this.#abs(doc), "utf8"));
571
+ return this.#refs.sameRef(reviewed, current) ? "same" : "drift";
572
+ } catch {
573
+ return null;
574
+ }
575
+ }
576
+
577
+ /** The review-gate method (T8 · §3.5) — the doc line's review request judgment +
578
+ * the phase advance, doc-revision FIRST: the shared docLineVerdict comparison is
579
+ * the PRIMARY criterion — a drifted doc OPENS the review lead regardless of the
580
+ * round/route state (fix / backfill / user-decision are one case: the stuck
581
+ * "next round is fix after an aborted fix" gate never freezes a revised doc);
582
+ * an unchanged doc yields the `same` verdict (review Convergence anti-spin:
583
+ * the callers' reject/reopen decision — the derived pending fix opens the fix
584
+ * face only, while the no-pending face falls back to the legacy rounds/routes
585
+ * judgment: a completed-fix line's C5-1 route reopens the review lead). The OPEN
586
+ * side performs no disk advance: the round + the revision snapshot land with the
587
+ * round's completion (Ledger#recordRound + the T7 write-back), so a BLOCKED
588
+ * re-review resumes the same round (nothing pre-binds). `unbound` (no identity on
589
+ * record / an unreadable doc) keeps the legacy round/route judgment. The
590
+ * judgment order change is the whole gate: the old rounds/routes-first read made
591
+ * the round/route state shadow the doc movement (the pre-T8 stuck path). */
592
+ reviewGate(key: LedgerKey, doc: string, type: TargetType): ReviewGateVerdict {
593
+ const verdict = this.docLineVerdict(key, doc);
594
+ if (verdict === "drift") return { kind: "open" };
595
+ if (verdict === "same") {
596
+ const reviewed = this.reviewedDocRevisionOf(key);
597
+ if (reviewed === null) return { kind: "unbound" };
598
+ return { kind: "same", pending: this.#pendingFix(key, type), reviewed };
599
+ }
600
+ return { kind: "unbound" };
601
+ }
602
+
603
+ /** The wave line's active C5 Route — the next C5 hop the dispatch engine would run
604
+ * on this wave. A wave with no implement round yet is dispatched whole (`next-wave`
605
+ * carrying the wave key — the engine's `implement`-phase action, rendered as the
606
+ * implement literal); a recorded implement holding no review yet, or a re-review
607
+ * after a blocker-carrying fix, is the review hop; a review awaiting a fix (its own
608
+ * blockers outstanding) is the one-way fix hop carrying the source review's handoff
609
+ * path. Null when the wave line holds no open hop (drained / deferred by the soft
610
+ * cap). The D16/T11 revision precheck belongs HERE, not in a per-consumer copy: a
611
+ * completed wave review bound the RENDERED BRIEF it judged to the row (run.ts
612
+ * bookkeep `#recordReviewedWaveBrief` → `#briefRevision`), and a drifted BRIEF
613
+ * reopens the wave at review regardless of the fix-awaited round state (the
614
+ * stale-revision findings are voided — new revision, new review). Same revision + a
615
+ * pending fix stays at fix (Review Convergence anti-spin); a null record (legacy wave
616
+ * row) keeps the pure round-count derivation. The final leg reads the latest fix
617
+ * round's C5 route under EMPTY_RUN_STATE — the close-side is inert for the
618
+ * review/closure query (only the fix round's own blockers can yield review). The
619
+ * `waveLinePhase` judge below derives its phase word from this route (one walk), and
620
+ * the board's `next:` derivation reads the route itself (D40 — the active hop, never
621
+ * a bare face handoff). */
622
+ waveLineRoute(waveKey: string): Route | null {
623
+ const implemented = this.roundCount(waveKey, "implement");
624
+ if (implemented === 0) return { kind: "next-wave", tasks: waveKey };
625
+ const data = this.readProgress();
626
+ const row = data === null ? undefined : this.rowFor(data, waveKey);
627
+ const latestReview = row === undefined ? 0 : this.#latestCycleOfRow(row, "review");
628
+ if (latestReview === 0) return { kind: "review" };
629
+ // The latest recorded round is a fix iff a fix is recorded at the latest review's
630
+ // CYCLE (D28 identity — fix-K ⟷ review-K); otherwise it is the latest review itself
631
+ // (its route carries the awaited `fix`). The prior "no fix at the latest review cycle
632
+ // ⇒ pending fix" short-circuit read a re-review-closed line (`review=[1,2] · fix=[1]`)
633
+ // as forever at `fix`, missing the closing review-2 — the router read below is the
634
+ // single judge (the `waveLineRoute` twin of `#rowClosed`).
635
+ const fixRecorded = row !== undefined && this.#cyclesOf(row, "fix").includes(latestReview);
636
+ const carried = this.round(
637
+ fixRecorded ? "fix" : "review",
638
+ "wave",
639
+ { tasks: waveKey },
640
+ latestReview,
641
+ );
642
+ if (carried === null) return null;
643
+ const route = this.#router.next(EMPTY_RUN_STATE, carried);
644
+ if (route?.kind === "review") return { kind: "review" };
645
+ if (route?.kind === "fix") {
646
+ // The fix-awaited face — a drifted wave BRIEF reopens at review (D30/D16), else fix.
647
+ const reviewed = this.reviewedRevisionOf(waveKey);
648
+ if (reviewed !== null && this.#briefDrift(waveKey, reviewed)) return { kind: "review" };
649
+ return {
650
+ kind: "fix",
651
+ reviews: this.handoffPath("review", "wave", { tasks: waveKey, round: latestReview }),
652
+ };
653
+ }
654
+ return null;
655
+ }
656
+
657
+ /** The wave line's open phase — the SINGLE derivation the wave gate AND the
658
+ * lifecycle's frame frontier both read (D26: one fact, one place, read at judgment
659
+ * time), mapped from `waveLineRoute`'s active C5 hop: the not-yet-implemented wave
660
+ * reads `implement`, the review hop `review`, the one-way fix hop `fix`, a drained /
661
+ * soft-capped line null. */
662
+ waveLinePhase(waveKey: string): RoundPhase | null {
663
+ const route = this.waveLineRoute(waveKey);
664
+ if (route === null) return null;
665
+ if (route.kind === "next-wave") return "implement";
666
+ if (route.kind === "review") return "review";
667
+ if (route.kind === "fix") return "fix";
668
+ return null;
669
+ }
670
+
671
+ /** The wave line's brief-drift verdict (D30) — the wave's CURRENT rendered brief
672
+ * vs the recorded reviewed brief. `true` when the wave's judgment input moved past
673
+ * the reviewed basis (the wave reopens at review). A plan edit OUTSIDE the wave's
674
+ * task sections + `## Constraints` leaves the brief byte-identical → `false`
675
+ * (the append-only backfill case the whole-plan hash wrongly flagged). An
676
+ * underivable brief (unreadable plan / absent task) is not a drift (present
677
+ * facts only). A row bound to a non-brief kind (a doc kind, only via a corrupt
678
+ * hand-write) is not a wave brief — no drift. */
679
+ #briefDrift(waveKey: string, reviewed: ReviewedRevisionRef): boolean {
680
+ if (reviewed.kind !== "brief-revision") return false;
681
+ const current = this.#briefRevision(waveKey, reviewed.plan);
682
+ if (current === null) return false;
683
+ return !this.#refs.sameRef(reviewed, current);
684
+ }
685
+
686
+ /** The pending-fix derivation — the "doc same + not APPROVED" face (T8): the
687
+ * latest review round has an outstanding fix AND its conclusion was not an
688
+ * approval. The identity test is the operable leg (D28): the latest review cycle
689
+ * is ABSENT from the fix cycle set (`roundRecorded(key, "fix", reviews)`) — a
690
+ * membership test, never a `reviews > fixes` count comparison, which would read a
691
+ * phantom pending fix when a cycle was skipped (a drift-voided review-1 → the first
692
+ * fix is cycle 2, present at its own number, not ordinal 1). The status read keeps
693
+ * the derivation's second leg explicit, degrading to the conservative pending on a
694
+ * missing carrier (a recorded round is a present fact — the same-doc re-review
695
+ * stays refused until its fix lands). A completed fix (the latest review cycle IS
696
+ * in the fix set) is NOT the pending face — the completed-fix line's re-review
697
+ * reopens through the fix round's C5 route (the legacy judgment). */
698
+ #pendingFix(key: LedgerKey, type: TargetType): boolean {
699
+ const reviews = this.roundCount(key, "review");
700
+ if (reviews === 0 || this.roundRecorded(key, "fix", reviews)) return false;
701
+ const carried = this.round("review", type, { round: reviews }, reviews);
702
+ // `carried.status` is the review round's DERIVED conclusion — `round()` sets it
703
+ // through the `HandoffSchema.conclusionOf` single source (the findings carrier
704
+ // stores no status field · D27), never a second read of the carrier here.
705
+ return carried === null || carried.status === undefined || carried.status !== "APPROVED";
706
+ }
707
+
708
+ /** Read one counter — a failure-category count on record (0 when the file is missing). */
709
+ counterOf(key: ProgressCounterKey): number {
710
+ return this.readProgress()?.[key] ?? 0;
711
+ }
712
+
713
+ /** Increment the timeout counter — the terminated-round write point (one TIMEOUT
714
+ * round lands, the count goes up by one). The counter's only writer. */
715
+ incrementTimeoutCount(): number {
716
+ const data = this.readProgress() ?? this.emptyProgress();
717
+ data.timeoutCount += 1;
718
+ this.writeProgress(data);
719
+ return data.timeoutCount;
720
+ }
721
+
722
+ // -------------------------------------------------------------------------
723
+ // closedWaves — the closure single read face (v1.20)
724
+ // -------------------------------------------------------------------------
725
+
726
+ /**
727
+ * The session's closed task ids — the C5 closure single read face (v1.20): a task
728
+ * is closed exactly when the C5 route of its LATEST recorded round lies on the
729
+ * closure side ({done, next-wave} — the SAME terminal predicate the lifecycle's
730
+ * #markTerminal applies). The retired "any ledger row is done" row-read is gone:
731
+ * an implement-only row NEVER closes (a recorded implement round is not a closure
732
+ * verdict — the structural root of the phantom-closure fix), and a historical
733
+ * merged-wave row naturalizes through its own review/fix pair (the wave row's C5
734
+ * route, never a per-member read). The frontier consumers (the wave gate · the
735
+ * board face) read this face — one closed set, one source.
736
+ */
737
+ closedWaves(): Set<number> {
738
+ const closed = new Set<number>();
739
+ const data = this.readProgress();
740
+ if (data === null) return closed;
741
+ for (const row of data.waves) {
742
+ if (this.#rowClosed("wave", { tasks: row.wave }, row)) {
743
+ for (const id of row.wave.split(",").map((part) => Number(part))) closed.add(id);
744
+ }
745
+ }
746
+ return closed;
747
+ }
748
+
749
+ /** Whether one LINE is closed — the line-level closure judge the board's `next:`
750
+ * derivation and its branch row consume (and `closedWaves()` reads through the
751
+ * same core). The C5 route of the line's LATEST recorded round must lie on the
752
+ * closure side ({done, next-wave}). The key is the line-type constant the round
753
+ * records under ("spec" / "plan" / "branch"); a row with no review round yet
754
+ * (implement-only or absent) holds the line open. One judge, one source: the
755
+ * board never re-derives closure in the face (zero second judge). */
756
+ lineClosed(key: LedgerKey, type: TargetType): boolean {
757
+ const data = this.readProgress();
758
+ if (data === null) return false;
759
+ const row = this.rowFor(data, key);
760
+ if (row === undefined) return false;
761
+ return this.#rowClosed(type, type === "wave" ? { tasks: String(key) } : {}, row);
762
+ }
763
+
764
+ /** The single-target line's active C5 Route — the next C5 hop the dispatch engine
765
+ * would run on this line (the doc/branch faces: the review-lead round judges the
766
+ * live tree; a fix-awaited review, a re-review after a blocker-carrying fix). A line
767
+ * with no review-lead round yet is the review-lead hop (`{kind:"review"}` — the
768
+ * renderer keys the literal off the target type); a review round with findings is
769
+ * the one-way fix hop (carrying the review's handoff); a fix round that still carries
770
+ * blockers is the re-review hop. Null when the line holds no open hop (a clean review
771
+ * / a blocker-free fix closed it — the closure-side routes are not an "active hop").
772
+ * The pending-fix test is the latest review's IDENTITY membership in the fix cycle
773
+ * set (D28) — a count comparison would flatten a skipped cycle into a phantom pending
774
+ * fix. The doc-revision gate is NOT part of this walk — the callers run their own
775
+ * reviewGate first (doc-drift-first ordering). `linePhase` maps this route to its
776
+ * phase word (one walk), and the board's `next:` derivation reads the route itself
777
+ * (D40 — the active hop, never a bare face handoff). */
778
+ lineRoute(key: LedgerKey, type: TargetType): Route | null {
779
+ const reviewLead = targetFaces[type].product.reviewLead;
780
+ const reviews = this.roundCount(key, reviewLead);
781
+ if (reviews === 0) return { kind: "review" };
782
+ if (!this.roundRecorded(key, "fix", reviews)) {
783
+ const route = this.#lineRoundRoute("review", type, reviews);
784
+ return route?.kind === "fix" ? route : null;
785
+ }
786
+ const route = this.#lineRoundRoute("fix", type, reviews);
787
+ return route?.kind === "review" ? route : null;
788
+ }
789
+
790
+ /** The single-target line's open phase — the rounds/routes walk the lifecycle's
791
+ * frame frontier (run.ts #nextLinePhase) and the CLI gate (gate.ts #linePhase)
792
+ * BOTH consume (one judge, one source — the retired twin copies), mapped from
793
+ * `lineRoute`'s active C5 hop: the review-lead hop reads the face's own review-lead
794
+ * mode word (branch→branch-review, the others→review), the fix hop `"fix"`, a closed
795
+ * line null. */
796
+ linePhase(key: LedgerKey, type: TargetType): RoundPhase | null {
797
+ const route = this.lineRoute(key, type);
798
+ if (route === null) return null;
799
+ return route.kind === "review" ? targetFaces[type].product.reviewLead : "fix";
800
+ }
801
+
802
+ /** One single-target line round's C5 route — the review-lead / fix round read back
803
+ * through the ledger and judged by the router (null when unreadable). Single-target
804
+ * lines key their handoff params `{ round }` (the run.ts / gate.ts shaping) — the
805
+ * same #roundRoute the closure judge reads, one walk. */
806
+ #lineRoundRoute(op: "review" | "fix", type: TargetType, round: number): Route | null {
807
+ return this.#roundRoute(op, type, { round }, round);
808
+ }
809
+
810
+ /** Whether a C5 route lies on the closure side — the `{done, next-wave}` terminal
811
+ * predicate SINGLE SOURCE (D40): the lifecycle's #markTerminal, `#rowClosed` and
812
+ * every closure consumer read it here, never a re-typed literal. */
813
+ static routeClosed(route: Route | null): boolean {
814
+ return route !== null && (route.kind === "done" || route.kind === "next-wave");
815
+ }
816
+
817
+ /** Whether one progress row's line is closed — the LATEST recorded round's C5 route
818
+ * lies on the closure side ({done, next-wave}). The latest recorded round is a fix
819
+ * iff a fix is recorded at the latest review's CYCLE (D28 identity — fix-K ⟷
820
+ * review-K); otherwise it is the latest review itself. The prior `Math.min(latestFix,
821
+ * latestReview)` form was WRONG on a re-review-closed line: with `review=[1,2] ·
822
+ * fix=[1]` (review-1 → fix-1 → review-2) it read the STALE fix-1 (whose route is
823
+ * `review`) and missed the closing review-2 (whose route is `done`) — reading the
824
+ * line forever open at fix. The latest recorded round is `review@2` here. A row with
825
+ * no review round yet (implement-only or scheduled) holds the line open. The row's
826
+ * review-lead mode rides the faces table (branch→branch-review, the others→review),
827
+ * so the wave/spec/plan/branch lines share ONE judge. */
828
+ #rowClosed(type: TargetType, params: HandoffParams, row: ProgressRow): boolean {
829
+ const latestReview = this.#latestCycleOfRow(row, targetFaces[type].product.reviewLead);
830
+ if (latestReview === 0) return false;
831
+ const fixRecorded = this.#cyclesOf(row, "fix").includes(latestReview);
832
+ return Ledger.routeClosed(
833
+ this.#roundRoute(fixRecorded ? "fix" : "review", type, params, latestReview),
834
+ );
835
+ }
836
+
837
+ /** The latest recorded cycle of a row + mode — 0 when none (the identity read; a
838
+ * skipped cycle reports its own number, never the count). */
839
+ #latestCycleOfRow(row: ProgressRow, mode: string): number {
840
+ const cycles = this.#cyclesOf(row, mode);
841
+ return cycles.length > 0 ? Math.max(...cycles) : 0;
842
+ }
843
+
844
+ /** The C5 route of one recorded round — null when the round is unreadable (a
845
+ * line whose round was never read cannot be judged closed: only present facts). */
846
+ #roundRoute(
847
+ op: "review" | "fix",
848
+ type: TargetType,
849
+ params: HandoffParams,
850
+ round: number,
851
+ ): Route | null {
852
+ const carried = this.round(op, type, params, round);
853
+ if (carried === null) return null;
854
+ return this.#router.next(EMPTY_RUN_STATE, carried);
855
+ }
856
+
857
+ // -------------------------------------------------------------------------
858
+ // handoff — naming / carrier / single-author persist
859
+ // -------------------------------------------------------------------------
860
+
861
+ /** The family record of an op/type pair — the engine-config handoff namespace data
862
+ * (loud on an unknown family: the naming table is the single truth, never a second list). */
863
+ #family(op: string, type: string): HandoffFamily {
864
+ const family = this.#families[`${op}.${type}`];
865
+ if (family === undefined) throw new Error(`unknown handoff family: ${op}.${type}`);
866
+ return family;
867
+ }
868
+
869
+ /** The handoff FACE of an op/type pair — the family's `schema` selector (work when
870
+ * the family declares none). The face-aware read/write/bookkeep spine (T2): a
871
+ * findings-face round rides the findings writable subset, a work-face round rides
872
+ * the findings-free work subset — never the caller's guess. */
873
+ handoffFaceOf(op: OpType, type: TargetType): HandoffSchemaFace {
874
+ return this.#family(op, type).schema ?? "work";
875
+ }
876
+
877
+ /** The canonical handoff file name — the family's `{placeholder}` pattern, filled. */
878
+ handoffName(op: string, type: string, params: HandoffParams = {}): string {
879
+ return this.#family(op, type)
880
+ .name.replaceAll("{tasks}", params.tasks ?? "")
881
+ .replaceAll("{round}", String(params.round ?? ""));
882
+ }
883
+
884
+ /** The canonical on-disk handoff path. */
885
+ handoffPath(op: string, type: string, params: HandoffParams = {}): string {
886
+ return this.#workspace.resolve(this.handoffName(op, type, params));
887
+ }
888
+
889
+ /** The handoff carrier skeleton — the schema-declared writable fields the agent
890
+ * round fills, SHAPED PER FACE: the work overload builds a `findings`-free carrier
891
+ * (the work writable subset declares no findings field — the type gate: a
892
+ * `buildHandoff("work", { findings })` call is a compile-time refusal, Q1→c), the
893
+ * findings overload REQUIRES the findings payload (the schema's required field).
894
+ * The engine-seated identity (phase · tasks) rides the CANONICAL FILE NAME
895
+ * (`tasks-{wave}-*.json` / the range / doc family), never inline: phase/tasks are
896
+ * NOT declared and never written (v1.30 — the inline identity seeded a mimicking
897
+ * precedence: a fix draft copied the materialized `phase` the engine had written and
898
+ * tripped the reserved-field gate it could never pass; single declaration, single
899
+ * author — the carrier holds only the schema's declared plane, and status STILL
900
+ * rides the caller's set — the round conclusion is the engine's, not the skeleton's). */
901
+ buildHandoff(face: "work", init?: WorkInit): WorkCarrier;
902
+ buildHandoff(face: "findings", init: FindingsInit): FindingsCarrier;
903
+ buildHandoff(
904
+ face: HandoffSchemaFace,
905
+ init: WorkInit & { findings?: unknown[] } = {},
906
+ ): WorkCarrier | FindingsCarrier {
907
+ const carrier: Record<string, unknown> = { artifacts: init.artifacts ?? {} };
908
+ if (face === "findings" || init.findings !== undefined) carrier.findings = init.findings;
909
+ return carrier as WorkCarrier | FindingsCarrier;
910
+ }
911
+
912
+ /** Persist a handoff payload at the canonical name — the single-author full-replace
913
+ * write (never a merge: the engine owns the file). Returns the written path. */
914
+ persistHandoff(
915
+ op: string,
916
+ type: string,
917
+ params: HandoffParams,
918
+ data: Record<string, unknown>,
919
+ ): string {
920
+ this.#persist(this.handoffName(op, type, params), data);
921
+ return this.handoffPath(op, type, params);
922
+ }
923
+
924
+ /** Read a handoff carrier; null when missing/corrupt. */
925
+ readHandoff(op: string, type: string, params: HandoffParams): Record<string, unknown> | null {
926
+ return this.#read<Record<string, unknown>>(this.handoffName(op, type, params));
927
+ }
928
+
929
+ // -------------------------------------------------------------------------
930
+ // crash — the lane crash → recovery record
931
+ // -------------------------------------------------------------------------
932
+
933
+ /** The crash record file name — `crash-<lane>-<round>.json`. */
934
+ crashName(lane: string, round: number): string {
935
+ return `crash-${lane}-${round}.json`;
936
+ }
937
+
938
+ /** The crash record path. */
939
+ crashPath(lane: string, round: number): string {
940
+ return this.#workspace.resolve(this.crashName(lane, round));
941
+ }
942
+
943
+ /** Write a lane-crash recovery record — the resume decision source (the resume
944
+ * command + the dead child's tails), never the handoff carrier. Returns the record. */
945
+ writeCrash(lane: string, round: number, record: CrashRecord): CrashRecord {
946
+ this.#persist(this.crashName(lane, round), record);
947
+ return record;
948
+ }
949
+
950
+ /** Read a crash record; null when absent/unreadable (a recordless failure round keeps
951
+ * the no-next failure face). */
952
+ readCrash(lane: string, round: number): CrashRecord | null {
953
+ return this.#read<CrashRecord>(this.crashName(lane, round));
954
+ }
955
+
956
+ // -------------------------------------------------------------------------
957
+ // round — the round carrier
958
+ // -------------------------------------------------------------------------
959
+
960
+ /** The handoff findings presented as round findings — entries with an unknown severity
961
+ * are dropped (never invented into the judgment domain). */
962
+ #findingsOf(carrier: Readonly<Record<string, unknown>>): readonly RoundFinding[] {
963
+ if (!Array.isArray(carrier.findings)) return [];
964
+ const findings: RoundFinding[] = [];
965
+ for (const entry of carrier.findings) {
966
+ const severity = (entry as { severity?: unknown } | null)?.severity;
967
+ if (severity !== "blocker" && severity !== "warn" && severity !== "nit") continue;
968
+ const summary = (entry as { summary?: unknown } | null)?.summary;
969
+ findings.push({ severity, summary: typeof summary === "string" ? summary : undefined });
970
+ }
971
+ return findings;
972
+ }
973
+
974
+ /** The blocker count of a handoff carrier's findings — the C5-1 severity count. */
975
+ #blockerCountOf(carrier: Readonly<Record<string, unknown>>): number {
976
+ if (!Array.isArray(carrier.findings)) return 0;
977
+ return carrier.findings.filter(
978
+ (entry) => (entry as { severity?: unknown } | null)?.severity === "blocker",
979
+ ).length;
980
+ }
981
+
982
+ /** The consecutive-S1 run — how many review rounds ending at `round` (newest first) each
983
+ * carried >=1 blocker finding. The run stops at the first clean review or an unreadable
984
+ * round history (missing/corrupt handoff degrades the count to the conservative baseline,
985
+ * never a throw). */
986
+ #consecutiveS1Run(type: string, params: HandoffParams, round: number): number {
987
+ let run = 0;
988
+ for (let index = round; index >= 1; index--) {
989
+ const carrier = this.readHandoff("review", type, { ...params, round: index });
990
+ if (carrier === null) break;
991
+ if (this.#blockerCountOf(carrier) === 0) break;
992
+ run += 1;
993
+ }
994
+ return run;
995
+ }
996
+
997
+ /** The progress key a round's dispatch records under — the same line-identity key
998
+ * the lifecycle records with (run.ts #lineKey): the wave task key (the only
999
+ * params-bearing face — every other line keys by its line-type constant:
1000
+ * `"branch"` / `"spec"` / `"plan"`). */
1001
+ #roundKey(type: TargetType, params: HandoffParams): LedgerKey {
1002
+ return type === "wave" ? (params.tasks ?? "") : type;
1003
+ }
1004
+
1005
+ /** The recorded mode one op's round records its cycle under — the review leg reads
1006
+ * the face table's review-lead mode (the single source: branch→branch-review, the
1007
+ * others→review), matching `recordRound(frame.key, frame.phase, frame.round)`; the
1008
+ * implement/fix legs their own name. */
1009
+ #recordedMode(op: OpType, type: TargetType): string {
1010
+ return op === "review" ? targetFaces[type].product.reviewLead : op;
1011
+ }
1012
+
1013
+ /** Read a round's concluding record as the Round the dispatch next-router judges.
1014
+ * A round is present ONLY when `recordRound` recorded it (the round verdict's
1015
+ * single source): an unrecorded round returns null whatever draft sits on disk —
1016
+ * a rejected child's leftover draft is never read back as a completed round
1017
+ * (the §2.8 gate; without it a BLOCKED round with a stale draft rendered a
1018
+ * contradictory `status: BLOCKED · next: done`). A fix round carries the SOURCE
1019
+ * review's findings (C5-1: the `--reviews` input content, never its own
1020
+ * carrier); the consecutive-S1 run is walked from the review history.
1021
+ * Missing/corrupt evaluated handoff → null too — a fix round whose source review
1022
+ * is unreadable is never a zero-findings fabrication: a round whose blocker set
1023
+ * was never read must not be judged clean. */
1024
+ round(op: OpType, type: TargetType, params: HandoffParams, round: number): Round | null {
1025
+ // §2.8 — the round-read gate: only a recorded round is a round. The test is the
1026
+ // round's IDENTITY (its cycle number), not a count: a fix that skipped a cycle
1027
+ // (a drift-voided review → the first fix is cycle 2, not ordinal 1) is present at
1028
+ // cycle 2 (D28). A count comparison would flatten that to 1 and refuse the read.
1029
+ if (!this.roundRecorded(this.#roundKey(type, params), this.#recordedMode(op, type), round)) {
1030
+ return null;
1031
+ }
1032
+ if (op === "implement") {
1033
+ const carrier = this.readHandoff("implement", type, params);
1034
+ if (carrier === null) return null;
1035
+ return {
1036
+ phase: "implement",
1037
+ findings: [],
1038
+ consecutiveS1: 0,
1039
+ };
1040
+ }
1041
+ if (op === "review") {
1042
+ const reviewParams = { ...params, round };
1043
+ const carrier = this.readHandoff("review", type, reviewParams);
1044
+ if (carrier === null) return null;
1045
+ return {
1046
+ phase: "review",
1047
+ // The conclusion is DERIVED from the review carrier's own findings at judgment
1048
+ // time (D27 · the findings carrier holds no status field) — the single source
1049
+ // shared with the fix leg below (`HandoffSchema.conclusionOf`).
1050
+ status: this.#handoffSchema.conclusionOf("findings", carrier),
1051
+ findings: this.#findingsOf(carrier),
1052
+ reviewsPath: this.handoffPath("review", type, reviewParams),
1053
+ consecutiveS1: this.#consecutiveS1Run(type, params, round),
1054
+ };
1055
+ }
1056
+ // op === "fix" — the C5-1 fingerprint: the fix round judges the source review's input
1057
+ // findings. Missing/corrupt source review OR fix carrier → null (no round on record),
1058
+ // matching the review branch's contract: a fix whose blocker set was never read must
1059
+ // not be judged a clean zero-findings round — the next-hop derivation cannot close a
1060
+ // line it could not read.
1061
+ const reviewParams = { ...params, round };
1062
+ const reviewCarrier = this.readHandoff("review", type, reviewParams);
1063
+ const fixCarrier = this.readHandoff("fix", type, reviewParams);
1064
+ if (reviewCarrier === null || fixCarrier === null) return null;
1065
+ return {
1066
+ phase: "fix",
1067
+ // The fix round's conclusion derives from ITS OWN carrier's declared plane (the
1068
+ // work face reads its status; a docs-fix findings face rolls its findings up) —
1069
+ // the same `conclusionOf` single source (D27).
1070
+ status: this.#handoffSchema.conclusionOf(this.handoffFaceOf("fix", type), fixCarrier),
1071
+ findings: this.#findingsOf(reviewCarrier),
1072
+ reviewsPath: this.handoffPath("review", type, reviewParams),
1073
+ consecutiveS1: this.#consecutiveS1Run(type, params, round),
1074
+ };
1075
+ }
1076
+ }