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