@oscaner-skills/cdd-engine 4.2.0 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +38 -9
  2. package/README.zh-CN.md +43 -9
  3. package/dist/contract/completion-criterion.js +351 -0
  4. package/dist/contract/declare.js +181 -43
  5. package/dist/contract/doc.js +84 -271
  6. package/dist/contract/frontmatter.js +2 -1
  7. package/dist/contract/home-extractors.js +49 -316
  8. package/dist/contract/invariants.js +400 -296
  9. package/dist/contract/judge.js +74 -49
  10. package/dist/contract/lint.js +3 -2
  11. package/dist/contract/liveness-signal.js +103 -0
  12. package/dist/contract/markdown-document.js +410 -0
  13. package/dist/contract/markdown-tree-types.js +6 -0
  14. package/dist/contract/markdown-tree.js +137 -0
  15. package/dist/contract/project.js +1 -1
  16. package/dist/contract/rules.js +106 -0
  17. package/dist/contract/selector-engine.js +332 -0
  18. package/dist/contract/selector-spec.js +74 -0
  19. package/dist/contract/skill-anatomy.js +29 -1
  20. package/dist/contract/task-block-grammar.js +285 -0
  21. package/dist/contract/task-blocks.js +65 -0
  22. package/dist/contract/translate.js +21 -0
  23. package/dist/contract/wave-width.js +15 -0
  24. package/dist/face/board-view.js +401 -131
  25. package/dist/face/capsule.js +66 -89
  26. package/dist/face/cli.js +116 -35
  27. package/dist/face/declare.js +36 -18
  28. package/dist/face/gate.js +117 -40
  29. package/dist/face/init.js +1 -1
  30. package/dist/face/lifecycle.js +540 -123
  31. package/dist/face/preview.js +43 -10
  32. package/dist/face/route-render.js +51 -21
  33. package/dist/face/termination.js +135 -261
  34. package/dist/face/words.js +134 -12
  35. package/dist/infra/atomic.js +15 -0
  36. package/dist/infra/git.js +25 -0
  37. package/dist/infra/proc.js +150 -0
  38. package/dist/infra/round-log.js +104 -0
  39. package/dist/infra/runtime.js +16 -4
  40. package/dist/infra/workspace.js +7 -2
  41. package/dist/render/brief.js +15 -17
  42. package/dist/render/skeleton.js +41 -28
  43. package/dist/render/templates.js +128 -84
  44. package/dist/session/faces.js +47 -20
  45. package/dist/session/graph.js +13 -37
  46. package/dist/session/handoff-schema.js +16 -8
  47. package/dist/session/inflight.js +282 -0
  48. package/dist/session/ledger.js +581 -136
  49. package/dist/session/line-identity.js +33 -0
  50. package/dist/session/next.js +138 -80
  51. package/dist/session/preflight.js +276 -68
  52. package/dist/session/round-naming.js +56 -8
  53. package/dist/session/run.js +317 -78
  54. package/dist/session/wave.js +94 -14
  55. package/package.json +13 -3
@@ -18,6 +18,8 @@
18
18
  // Module-level exports are types / the class / one empty-state data const — zero
19
19
  // behavior-carrying bare functions (the plan's zero-bare-function discipline).
20
20
  import { readFileSync } from "node:fs";
21
+ import { PlanDocType } from "../contract/doc.js";
22
+ import { PlanTaskBlocksReader } from "../contract/task-blocks.js";
21
23
  import { Ledger, } from "./ledger.js";
22
24
  import { NextStepRouter } from "./next.js";
23
25
  /** The empty run state — a target line with no task frontier (branch/spec/plan):
@@ -29,6 +31,83 @@ export const EMPTY_RUN_STATE = {
29
31
  frontier: () => [],
30
32
  markDone: () => undefined,
31
33
  };
34
+ /**
35
+ * PlanStructure — one plan document's STRUCTURE face: the task-id set and each task's
36
+ * declared `DependsOn` set (design spec §7.3).
37
+ *
38
+ * It is a per-round DISPATCH baseline, not a stored fact: the lifecycle snapshots it
39
+ * right before the spawn and re-reads it at the round's close, so only the round's OWN
40
+ * structure edit is judged — a content-only amendment (facts, file lists, steps,
41
+ * acceptance detail, cited line numbers) stays legal. The judgment has ONE presentation
42
+ * face (the round's graded `violations`): no doc-contract rule row is registered for it,
43
+ * because the engine's single doc-contract evaluation point is the pre-dispatch gate.
44
+ */
45
+ export class PlanStructure {
46
+ /** The registered task ids, ascending. */
47
+ #taskIds;
48
+ /** Each task's declared dependency set, keyed by task id. */
49
+ #dependsOn;
50
+ constructor(taskIds, dependsOn) {
51
+ this.#taskIds = taskIds;
52
+ this.#dependsOn = dependsOn;
53
+ }
54
+ /** Read a plan document's two structure faces. `absent` when there is no plan fact
55
+ * (no path, or a path whose document does not exist); `unreadable` when the path
56
+ * exists but the document cannot be read (the reason rides the read result); `ok`
57
+ * with the snapshot otherwise. The three cases stay apart so a caller can tell "there
58
+ * is no plan" from "the plan is damaged" — the two carry different judgments. */
59
+ static of(planPath) {
60
+ if (planPath === null)
61
+ return { kind: "absent" };
62
+ try {
63
+ return { kind: "ok", structure: PlanStructure.parse(readFileSync(planPath, "utf8")) };
64
+ }
65
+ catch (error) {
66
+ // A path with no document is the absent case, never a read failure; every other
67
+ // error is the damaged-document case, its reason carried into the caller's message.
68
+ if (error.code === "ENOENT")
69
+ return { kind: "absent" };
70
+ return { kind: "unreadable", reason: error instanceof Error ? error.message : String(error) };
71
+ }
72
+ }
73
+ /** Parse one plan document into its structure face — the ONE task-block read face. */
74
+ static parse(content) {
75
+ const reader = new PlanTaskBlocksReader();
76
+ const blocks = reader.parse(content);
77
+ const dependsOn = new Map();
78
+ for (const block of blocks)
79
+ dependsOn.set(block.id, reader.dependsOn(block));
80
+ const taskIds = blocks.map((block) => block.id).sort((left, right) => left - right);
81
+ return new PlanStructure(taskIds, dependsOn);
82
+ }
83
+ /** The task-id set, ascending. */
84
+ get taskIds() {
85
+ return this.#taskIds;
86
+ }
87
+ /** One task's declared dependency set ([] when it declares none). */
88
+ dependsOnOf(taskId) {
89
+ return this.#dependsOn.get(taskId) ?? [];
90
+ }
91
+ /** Whether the two snapshots differ on either structure face — SET equality over the
92
+ * task-id set and over every task's dependency set (a task added, removed or rewired
93
+ * differs; a prose edit does not; declaration order is prose, the edge set is the
94
+ * structure). */
95
+ differsFrom(other) {
96
+ if (this.#taskIds.length !== other.#taskIds.length)
97
+ return true;
98
+ if (!this.#taskIds.every((id, index) => id === other.#taskIds[index]))
99
+ return true;
100
+ return this.#taskIds.some((id) => !PlanStructure.#sameIds(this.dependsOnOf(id), other.dependsOnOf(id)));
101
+ }
102
+ /** Set equality of two id lists (order-insensitive). */
103
+ static #sameIds(left, right) {
104
+ if (left.length !== right.length)
105
+ return false;
106
+ const sortedLeft = [...left].sort((a, b) => a - b);
107
+ const sortedRight = [...right].sort((a, b) => a - b);
108
+ return sortedLeft.every((id, index) => id === sortedRight[index]);
109
+ }
110
+ }
32
111
  /**
33
112
  * Lifecycle — the parameterized single lifecycle over one target-type face. One
34
113
  * instance drives one target line. advance() runs one dispatch step:
@@ -66,6 +145,11 @@ export class Lifecycle {
66
145
  /** The workspace plan path — the `next:` implement literal's required `--plan`
67
146
  * arg (P4.1 T4 — the task face's implement-consuming fact). */
68
147
  #planPath;
148
+ /** The pipeline-station discrimination the hop derivation injects (P22 §5.2) —
149
+ * the SAME face read the capsule/board use (`BoardView.docClassOf`). The
150
+ * composition root passes it; the session-plane default keys by target type
151
+ * (the CLI is the seam that reads a spec's DECLARED class). */
152
+ #docClassOf;
69
153
  constructor(opts) {
70
154
  this.#face = opts.face;
71
155
  this.#state = opts.state;
@@ -76,6 +160,16 @@ export class Lifecycle {
76
160
  this.#capsule = opts.capsule ?? null;
77
161
  this.#preflight = opts.preflight ?? null;
78
162
  this.#planPath = opts.planPath ?? null;
163
+ this.#docClassOf = opts.docClassOf ?? Lifecycle.#docClassByType;
164
+ }
165
+ /** The session-plane default discrimination — the target type's own pipeline key.
166
+ * Every target type but the standalone `single-spec` IS a pipeline key (the
167
+ * `PipelineKey` derivation), so the map is the identity plus the one terminal row
168
+ * (a single-spec carries no pipeline seam). The declaration-reading judgment (a
169
+ * doc's `doc-type:`) belongs to the face plane; the composition root injects it as
170
+ * `BoardView.docClassOf`. */
171
+ static #docClassByType(target) {
172
+ return target.type === "single-spec" ? "terminal" : target.type;
79
173
  }
80
174
  /** The face row this instance drives. */
81
175
  face() {
@@ -91,9 +185,18 @@ export class Lifecycle {
91
185
  * cursor pre-checks the next step against the requested verb before it advances
92
186
  * (a mismatch must not consume the round: advance() dispatches on entry — the
93
187
  * {16,22,24} bug's loop reordered lookahead-after-dispatch and spent the next
94
- * phase's round in the same invocation). Null = the run is exhausted / capped. */
188
+ * phase's round in the same invocation). The returned `hop` is the SAME `NextHop`
189
+ * object the board and the CLI rejection message read (P22 §5.2's fourth read
190
+ * face): one derivation over this line's facts, never a lookahead-only copy.
191
+ * Null = the run is exhausted / capped (no open frame → no line to name). */
95
192
  peekNext() {
96
- return this.#openFrame();
193
+ const frame = this.#openFrame();
194
+ if (frame === null)
195
+ return null;
196
+ const route = frame.type === "wave"
197
+ ? this.#ledger.waveLineRoute(String(frame.key))
198
+ : this.#ledger.lineRoute(frame.key, frame.type);
199
+ return { frame, hop: this.#hopOf(frame, route) };
97
200
  }
98
201
  /** advance() — one dispatch step: frontier → pre-flight gate → dispatch → result →
99
202
  * bookkeeping → next routing. Null when the line holds no open frame (the run is
@@ -109,7 +212,7 @@ export class Lifecycle {
109
212
  if (verdict !== null && !verdict.ok) {
110
213
  return {
111
214
  frame,
112
- round: this.#ledger.roundCount(frame.key, frame.phase),
215
+ round: this.#ledger.roundCount(frame.key, frame.phase, frame.type),
113
216
  route: null,
114
217
  capsuleLines: [],
115
218
  preflight: verdict,
@@ -126,11 +229,15 @@ export class Lifecycle {
126
229
  // review empties the ready batch, so the step routes `done` (an exhausted run),
127
230
  // not a phantom next-wave of the just-closed task.
128
231
  const route = this.#routeNext(frame);
232
+ // The failure face holds NO next object at all (the `next:` line's absence gate
233
+ // is the NextHop's absence, never `hop: null` — that still renders `done` / the
234
+ // soft-cap / the doc-class rows).
235
+ const failed = outcome.status === "BLOCKED" || outcome.status === "TIMEOUT";
129
236
  return {
130
237
  frame,
131
238
  round,
132
239
  route,
133
- capsuleLines: this.#capsuleLines(frame, outcome, route),
240
+ capsuleLines: this.#capsuleLines(frame, outcome, failed ? null : this.#hopOf(frame, route)),
134
241
  termination: outcome.termination,
135
242
  };
136
243
  }
@@ -161,6 +268,7 @@ export class Lifecycle {
161
268
  return null;
162
269
  const target = { kind: "wave", tasks: ready };
163
270
  const round = this.#roundFor(phase, key);
271
+ const attempt = this.#attemptFor(phase, key, round);
164
272
  return {
165
273
  type: "wave",
166
274
  phase,
@@ -168,8 +276,17 @@ export class Lifecycle {
168
276
  target,
169
277
  params: this.#paramsOf({ type: "wave", phase, target, round }),
170
278
  key,
279
+ attempt,
171
280
  };
172
281
  }
282
+ /** The attempt number one dispatch takes — allocated ONCE here from the row's
283
+ * records (`RoundNaming#attemptOf`, the naming single source) and shared by the
284
+ * round record and the round log's name. */
285
+ #attemptFor(phase, key, round) {
286
+ return this.#ledger
287
+ .naming()
288
+ .attemptOf(this.#ledger.recordsOf(key, this.#face.type), this.#opOf(phase), round);
289
+ }
173
290
  /** The next phase of one wave line — the SAME single derivation the wave gate reads
174
291
  * (`Ledger#waveLinePhase` · D26: one fact, one place). The lifecycle's frame
175
292
  * frontier and the three-verb WaveGate must agree on the open wave's phase, or a
@@ -188,6 +305,7 @@ export class Lifecycle {
188
305
  if (phase === null)
189
306
  return null;
190
307
  const round = this.#roundFor(phase, key);
308
+ const attempt = this.#attemptFor(phase, key, round);
191
309
  return {
192
310
  type: this.#face.type,
193
311
  phase,
@@ -195,20 +313,34 @@ export class Lifecycle {
195
313
  target,
196
314
  params: this.#paramsOf({ type: this.#face.type, phase, target, round }),
197
315
  key,
316
+ attempt,
198
317
  };
199
318
  }
200
319
  /** The next phase of a single-target line — the doc-revision gate (lifecycle-side:
201
320
  * its reviewGate needs the target doc path) then the ledger's SINGLE rounds/routes
202
321
  * judge (`Ledger#linePhase`, D40 — the retired lifecycle twin). A CLOSED doc line
203
- * reopens through the identity verdict (T7): a drifted doc opens the review lead
204
- * whatever the round/route state says (the fix-awaited route never freezes a
205
- * revised doc); an unchanged doc with the pending fix derived opens the fix; the
206
- * unbound / same-without-pending faces fall through to the shared rounds/routes
322
+ * reopens through the identity verdict (T7) — the ONE `Ledger#docReopens` judgment,
323
+ * the same one the dispatch gate reads, so an exit-side drift opens the review lead
324
+ * whatever the round/route state says while a still-pending fix keeps its round
325
+ * (drift never outranks it, §5.5 ② — the gate never names a round this frontier
326
+ * would not frame); an unchanged doc with the pending fix derived opens the fix;
327
+ * the unbound / same-without-pending faces fall through to the shared rounds/routes
207
328
  * walk (a completed-fix line reopens review through the fix round's route). */
208
329
  #nextLinePhase(key, target, reviewLead) {
209
330
  if (target.kind === "plan" || target.kind === "spec") {
210
331
  const verdict = this.#ledger.reviewGate(key, target.doc, this.#face.type);
211
- if (verdict.kind === "open")
332
+ if (this.#ledger.docReopens(key, this.#face.type, verdict))
333
+ return reviewLead;
334
+ if (verdict.kind === "same" && verdict.pending)
335
+ return "fix";
336
+ }
337
+ // The branch line's identity is its PLAN document (P21 §4.1): a plan revision
338
+ // after the terminal branch review reopens the branch-review lead, an unchanged
339
+ // plan keeps the line closed. Same gate, same judgment — only the doc path is
340
+ // the line's plan (the audit target itself carries no doc).
341
+ if (target.kind === "branch" && this.#planPath !== null) {
342
+ const verdict = this.#ledger.reviewGate(key, this.#planPath, "branch");
343
+ if (this.#ledger.docReopens(key, "branch", verdict))
212
344
  return reviewLead;
213
345
  if (verdict.kind === "same" && verdict.pending)
214
346
  return "fix";
@@ -216,25 +348,28 @@ export class Lifecycle {
216
348
  return this.#ledger.linePhase(key, this.#face.type);
217
349
  }
218
350
  /** The round number one phase dispatches under: implement = the fixed family (1);
219
- * the review-lead = the next increment; fix = the source review-lead round. */
351
+ * the review-lead = the next increment (every in-register cycle consumes a number);
352
+ * fix = the source review-lead's latest COMPLETED cycle (a failed fix never pushes
353
+ * it forward — a retry is fix-K's attempt + 1, never a phantom fix-(K+1)). */
220
354
  #roundFor(phase, key) {
221
355
  if (phase === "implement")
222
356
  return 1;
223
357
  if (phase === "fix") {
224
- const reviews = this.#reviewCount(key);
225
- return reviews > 0 ? reviews : 1;
358
+ const completed = this.#ledger.completedCycles(key, "review", this.#face.type);
359
+ return completed.length > 0 ? Math.max(...completed) : 1;
226
360
  }
227
361
  return this.#reviewCount(key) + 1;
228
362
  }
229
363
  /** The review-lead round count of a key (branch counts its branch-review mode,
230
364
  * the others the review mode — the face row's single source). */
231
365
  #reviewCount(key) {
232
- return this.#ledger.roundCount(key, this.#face.product.reviewLead);
366
+ return this.#ledger.roundCount(key, this.#face.product.reviewLead, this.#face.type);
233
367
  }
234
368
  /** The progress key of a single-target line — the line's STABLE key (find #9 ·
235
369
  * spec §6.5/§3.7 — `"branch"` per workspace for the branch line, accumulating
236
- * across re-reviews; the doc line keys by its line-type constant `"spec"`/`"plan"`
237
- * — the argv path copy never resets the round: a moved argv string (absolute vs
370
+ * across re-reviews; a doc line keys by its target-type word (`"phase-spec"` /
371
+ * `"overall"` / `"plan"` / `"single-spec"`) — the argv path copy never resets the
372
+ * round: a moved argv string (absolute vs
238
373
  * relative) must not fork the same line into two ledger rows). The task face
239
374
  * never routes here — frames key by the wave key. */
240
375
  #lineKey(target) {
@@ -259,30 +394,33 @@ export class Lifecycle {
259
394
  }
260
395
  case "branch":
261
396
  return { round: frame.round };
262
- case "spec":
397
+ case "phase-spec":
398
+ case "overall":
263
399
  case "plan":
400
+ case "single-spec":
264
401
  return { round: frame.round };
265
402
  }
266
403
  }
267
404
  // -------------------------------------------------------------------------
268
405
  // dispatch → result → bookkeeping
269
406
  // -------------------------------------------------------------------------
270
- /** Bookkeeping — persist the round's handoff carrier and record the progress round.
271
- * The persisted carrier is either the dispatch's materialized form (the production
407
+ /** Bookkeeping — persist the round's handoff carrier and record the round. The
408
+ * persisted carrier is either the dispatch's materialized form (the production
272
409
  * read-back reconstruct — outcome.carrier, full-replace at the SAME path, so the
273
410
  * child's draft becomes the finalized carrier — the two-state single file, the engine is the single
274
- * author) or the engine-built fallback from the outcome fields (the hermetic /
275
- * injected dispatchers). A BLOCKED/TIMEOUT round WITHOUT a carrier is neither persisted nor
276
- * recorded — the child's draft (if any) stays untouched (no-overwrite on failure) and the
277
- * frontier re-offers the same round (resume = re-run the same command); a BLOCKED
278
- * round WITH a carrier (e.g. the evidence-contract override — the child's work is
279
- * preserved as the BLOCKED carrier) is persisted but not counted as a completed
280
- * round, so the frontier still re-dispatches it. Returns the round count on record
281
- * (the task done-marking rides the step's C5 route — #markTerminal, after
282
- * #routeNext). */
411
+ * author) or — on the INJECTED face alone (an outcome carrying no verdict) — the
412
+ * engine-built fallback from the outcome fields. A production round that wrote no
413
+ * carrier is booked with `carrierPath: null` and no file at the handoff path: the
414
+ * completion criterion owns the absence (§3.3), and a re-dispatch's draft read must
415
+ * see the child's own draft, never an engine synthesis of it. A failure round
416
+ * WITHOUT a carrier leaves the child's draft untouched (no-overwrite on failure) but
417
+ * is STILL recorded — every dispatched round lands; "completed" is the record's
418
+ * verdict, never a membership test. Returns the in-register round count (the task
419
+ * done-marking rides the step's C5 route — #markTerminal, after #routeNext). */
283
420
  #bookkeep(frame, outcome) {
284
421
  const blocked = outcome.status === "BLOCKED" || outcome.status === "TIMEOUT";
285
- if (outcome.carrier !== undefined || !blocked) {
422
+ let carrierPath = null;
423
+ if (outcome.carrier !== undefined || (outcome.verdict === undefined && !blocked)) {
286
424
  const op = this.#opOf(frame.phase);
287
425
  // T2 — the engine-built fallback rides the FRAME's op-derived plane (never the
288
426
  // outcome's field presence): a judge-plane round (review) builds the findings
@@ -304,35 +442,53 @@ export class Lifecycle {
304
442
  // (`HandoffSchema.conclusionOf` → rollup(findings)), never a stored field (D27).
305
443
  if (plane === "work" && carrier.status === undefined && outcome.status !== undefined)
306
444
  carrier.status = outcome.status;
307
- this.#ledger.persistHandoff(op, frame.type, frame.params, carrier);
445
+ carrierPath = this.#ledger.persistHandoff(op, frame.type, frame.params, carrier);
308
446
  }
309
- if (!blocked) {
310
- // The recorded CYCLE is the frame's own round — its identity (fix-K ⟷ review-K ·
311
- // D28): a skipped cycle records its own number, never a flattened ordinal.
312
- const count = this.#ledger.recordRound(frame.key, frame.phase, frame.round);
313
- // The completed-review revision write-back — the doc line and the wave line
314
- // each bind their OWN reviewed revision (T7 doc · T11 wave / D16 / D30): a
315
- // completed review binds the CURRENT revision of the reviewed input — read at
316
- // bookkeep, the clean-tree dispatch gate keeps the read-only review's input
317
- // stable across the round. For a doc line that input is the target doc (the
318
- // whole-content doc-revision). For a wave line it is the RENDERED BRIEF —
319
- // `#recordReviewedWaveBrief` → `recordReviewedBrief(String(frame.key),
320
- // #planPath)` hashes the brief the plan renders to, holding #planPath only as
321
- // the plan the brief renders FROM (the render-from POINTER, not the hashed
322
- // identity; the wave gate derives the plan path FROM this record, so
323
- // cli.ts/preflight.ts stay untouched). The two legs do NOT share one gate —
324
- // each ref kind carries its own reviewed identity. An unreadable input records
325
- // nothing (present facts only); a null plan path (no plan fact) leaves a legacy
326
- // wave row — null stays backward compatible.
327
- if (frame.phase === "review") {
328
- if (frame.target.kind === "plan" || frame.target.kind === "spec")
329
- this.#recordReviewedDocRevision(frame);
330
- else if (frame.target.kind === "wave")
331
- this.#recordReviewedWaveBrief(frame);
332
- }
333
- return count;
447
+ // The recorded CYCLE is the frame's own round — its identity (fix-K ⟷ review-K ·
448
+ // D28): a skipped cycle records its own number, never a flattened ordinal. The
449
+ // attempt was allocated once by the frame builder and rides both the record and
450
+ // the round log's name.
451
+ const record = this.#ledger.recordRound(frame.key, {
452
+ op: this.#opOf(frame.phase),
453
+ cycle: frame.round,
454
+ attempt: frame.attempt ?? 1,
455
+ dispatchBase: outcome.dispatchBase ?? null,
456
+ // The verdict is the dispatch's own judgment when it carries one (the
457
+ // production lifecycle's `#verdictOf`); the injected dispatchers keep the
458
+ // status-derived fallback.
459
+ verdict: outcome.verdict ?? {
460
+ treeClean: outcome.treeClean ?? true,
461
+ targetAction: !blocked,
462
+ },
463
+ violations: outcome.violations ?? [],
464
+ carrierPath,
465
+ }, frame.type);
466
+ // The completed-review revision write-back is gated on the round's VERDICT (a
467
+ // hard-failed review must not bind the current revision — that would silently
468
+ // close the drift identity the review never judged). The doc line and the wave
469
+ // line each bind their OWN reviewed revision (T7 doc · T11 wave / D16 / D30): a
470
+ // completed review binds the CURRENT revision of the reviewed input — read at
471
+ // bookkeep, the clean-tree dispatch gate keeps the read-only review's input
472
+ // stable across the round. For a doc line that input is the target doc (the
473
+ // whole-content doc-revision). For a wave line it is the RENDERED BRIEF —
474
+ // `#recordReviewedWaveBrief` → `recordReviewedBrief(String(frame.key),
475
+ // #planPath)` hashes the brief the plan renders to, holding #planPath only as
476
+ // the plan the brief renders FROM (the render-from POINTER, not the hashed
477
+ // identity; the wave gate derives the plan path FROM this record, so
478
+ // cli.ts/preflight.ts stay untouched). The two legs do NOT share one gate —
479
+ // each ref kind carries its own reviewed identity. An unreadable input records
480
+ // nothing (present facts only); a null plan path (no plan fact) leaves a legacy
481
+ // wave row — null stays backward compatible.
482
+ if (record.verdict.targetAction &&
483
+ (frame.phase === "review" || frame.phase === "branch-review")) {
484
+ if (frame.target.kind === "plan" || frame.target.kind === "spec")
485
+ this.#recordReviewedDocRevision(frame);
486
+ else if (frame.target.kind === "wave")
487
+ this.#recordReviewedWaveBrief(frame);
488
+ else if (frame.target.kind === "branch")
489
+ this.#recordReviewedBranchRevision(frame);
334
490
  }
335
- return this.#ledger.roundCount(frame.key, frame.phase);
491
+ return this.#ledger.roundCount(frame.key, frame.phase, frame.type);
336
492
  }
337
493
  /** The reviewed-revision write-back — bind the reviewed input's revision to the
338
494
  * line record (the T7 doc + D30 wave identity gates' reopen-compare basis). The
@@ -344,13 +500,7 @@ export class Lifecycle {
344
500
  #recordReviewedDocRevision(frame) {
345
501
  if (frame.target.kind !== "plan" && frame.target.kind !== "spec")
346
502
  return;
347
- try {
348
- const content = readFileSync(frame.target.doc, "utf8");
349
- this.#ledger.recordReviewedRevision(frame.key, this.#ledger.refs().docRevision(frame.target.doc, content));
350
- }
351
- catch {
352
- // unreadable input — no reviewed identity recorded (present facts only)
353
- }
503
+ this.#recordDocRevisionOf(frame.key, frame.target.doc, frame.type);
354
504
  }
355
505
  /** The wave line's reviewed-brief write-back (D30) — bind the RENDERED brief's
356
506
  * revision for the wave's tasks to the row (the D30 wave-gate reopen basis). Null
@@ -360,6 +510,28 @@ export class Lifecycle {
360
510
  return;
361
511
  this.#ledger.recordReviewedBrief(String(frame.key), this.#planPath);
362
512
  }
513
+ /** The branch line's reviewed identity (P21 §4.1) — its PLAN document's
514
+ * `doc-revision`, the same ref kind the doc lines bind (no new ref kind, no commit
515
+ * sha). A later plan revision reopens the line; an unchanged plan keeps it closed.
516
+ * An unreadable plan / a null plan path records nothing (present facts only). */
517
+ #recordReviewedBranchRevision(frame) {
518
+ if (this.#planPath === null)
519
+ return;
520
+ this.#recordDocRevisionOf(frame.key, this.#planPath, frame.type);
521
+ }
522
+ /** The doc-revision write-back body — read the reviewed document and bind its
523
+ * current revision to the line row (the ONE read + hash + record path the doc and
524
+ * branch legs share; each passes its own path source). An unreadable input records
525
+ * nothing — the line keeps the legacy closed face (present facts only). */
526
+ #recordDocRevisionOf(key, path, identity) {
527
+ try {
528
+ const content = readFileSync(path, "utf8");
529
+ this.#ledger.recordReviewedRevision(key, this.#ledger.refs().docRevision(path, content), identity);
530
+ }
531
+ catch {
532
+ // unreadable input — no reviewed identity recorded (present facts only)
533
+ }
534
+ }
363
535
  /** Mark the wave done when the concluding route says its line closed — the C5
364
536
  * verdict is the single closure gate (terminal ⇔ route.kind ∈ {done, next-wave},
365
537
  * the v1.20 closure side): a clean review or a blocker-free fix closes the wave
@@ -375,6 +547,28 @@ export class Lifecycle {
375
547
  const waveTarget = frame.target;
376
548
  for (const id of waveTarget.tasks)
377
549
  this.#state.markDone(id);
550
+ // The closure's OTHER historical fact (P21 §5.1): the plan's task set at the
551
+ // instant this wave closed. It is the append-vs-stall basis the wave gate reads
552
+ // later — recorded here, at the one point that knows the wave just closed, and
553
+ // never re-derived (a later plan revision must not rewrite the history).
554
+ this.#recordPlanSnapshot(frame);
555
+ }
556
+ /** Record the closing wave's plan-task snapshot — the plan's CURRENT task-id set
557
+ * read from the plan document (`#planPath`, the same source the brief renders
558
+ * from) through the contract parse face. An unreadable plan or a null plan path
559
+ * records nothing: the snapshot is a present fact only, never a fabricated `[]`
560
+ * (an absent snapshot reads conservatively as "stall" in the wave gate). */
561
+ #recordPlanSnapshot(frame) {
562
+ if (this.#planPath === null)
563
+ return;
564
+ try {
565
+ const lines = readFileSync(this.#planPath, "utf8").split("\n");
566
+ const parsed = new PlanDocType("plan").parse(lines);
567
+ this.#ledger.recordPlanTasks(String(frame.key), parsed.taskBlocks.map((block) => block.id));
568
+ }
569
+ catch {
570
+ // unreadable plan — skip the snapshot (present facts only)
571
+ }
378
572
  }
379
573
  /** The handoff-family op of a phase — branch-review rides the review family. */
380
574
  #opOf(phase) {
@@ -400,29 +594,72 @@ export class Lifecycle {
400
594
  #routeState() {
401
595
  return this.#face.nextSemantics.batch ? this.#state : EMPTY_RUN_STATE;
402
596
  }
597
+ /** The line's ONE next-hop object (§5.2) — this lifecycle's facts handed to the
598
+ * ONE derivation (`Ledger#nextHopOf`): the recorded round's route, the line's
599
+ * completed records, the drift-aware gate and the injected station
600
+ * discrimination. The nullable route is handed over UNJUDGED — the assembly owns
601
+ * the exit-side decision (a closed line's `null` route is where the drift reopen
602
+ * lands), so the frontier face reads the same object the board and the gate read.
603
+ * The failure face's absent hop is the CALLER's fact (`advance` passes null for a
604
+ * BLOCKED/TIMEOUT round), never a second short-circuit here. */
605
+ #hopOf(frame, route) {
606
+ const target = this.#routeTarget(frame);
607
+ return this.#ledger.nextHopOf({
608
+ type: frame.type,
609
+ key: frame.key,
610
+ route,
611
+ target,
612
+ doc: this.#docOf(frame),
613
+ // The wave closure's NEXT-line fact (P21 §4.2) rides the derivation's input
614
+ // face — the retired render-side patch parameter is gone, the fact is not.
615
+ nextLineOpen: frame.type === "wave" ? this.#branchLineOpen() : undefined,
616
+ docClassOf: (candidate) => this.#docClassOf(candidate),
617
+ });
618
+ }
619
+ /** The line's judged document — the doc lines' own path, the branch line's plan
620
+ * (its identity document, P21 §4.1); null off the doc faces. */
621
+ #docOf(frame) {
622
+ if (frame.target.kind === "plan" || frame.target.kind === "spec")
623
+ return frame.target.doc;
624
+ if (frame.target.kind === "branch")
625
+ return this.#planPath;
626
+ return null;
627
+ }
628
+ /** Whether the branch line has a dispatchable open round — the wave closure's
629
+ * NEXT-line fact (P21 §4.2), read HERE (the ledger-holding side) from the two
630
+ * already-registered ledger faces: the branch row's drift-aware gate (the plan
631
+ * moved past its reviewed doc-revision) or a still-active C5 hop. `undefined` when
632
+ * no plan fact exists (the wave row keeps its plain station). */
633
+ #branchLineOpen() {
634
+ if (this.#planPath === null)
635
+ return undefined;
636
+ const gate = this.#ledger.reviewGate("branch", this.#planPath, "branch");
637
+ if (gate.kind === "open")
638
+ return true;
639
+ return this.#ledger.lineRoute("branch", "branch") !== null;
640
+ }
403
641
  /** The capsule lines of one step — empty unless a capsule is attached (the non-hard
404
- * interaction point). A success round carries the real blocker count and the
405
- * handoff carrier path. A failure round (TIMEOUT / BLOCKED) carries no blocker
406
- * cell (its count would be a filler); its handoff cell is the crash record and is
407
- * emitted only when that record exists (a no-host BLOCKED writes none). The
408
- * dispatch-ready `next:` literal rides the frame's own RouteTarget identity
409
- * (type + id — the v1.25 combination point: frame.type + params.tasks + route
410
- * are all present here). */
411
- #capsuleLines(frame, outcome, route) {
642
+ * interaction point). A success round carries the handoff carrier path; a failure
643
+ * round (TIMEOUT / BLOCKED) carries the crash record as its handoff cell, emitted
644
+ * only when that record exists (a no-host BLOCKED writes none). The fix round's
645
+ * disposition summary is handed to the capsule as its `summary` — the render places
646
+ * it between the status line and the trailing `next:` literal (P22 §10). */
647
+ #capsuleLines(frame, outcome, hop) {
648
+ const summary = outcome.dispositionsSummary;
412
649
  if (this.#capsule === null)
413
- return [];
650
+ return summary === undefined ? [] : [summary];
414
651
  const op = this.#opOf(frame.phase);
415
652
  const failure = outcome.status === "BLOCKED" || outcome.status === "TIMEOUT";
416
- const lane = `${op}.${frame.type}`;
653
+ const naming = this.#ledger.naming();
417
654
  // The failure face's handoff is the crash record — the engine's own postmortem
418
655
  // artifact, its existence the emission condition; the success face keeps the
419
- // round's handoff carrier path.
420
- const crash = failure ? this.#ledger.readCrash(lane, frame.round) : null;
421
- const blockers = (outcome.findings ?? []).filter((finding) => finding.severity === "blocker").length;
656
+ // round's handoff carrier path. The name derives from the frame through the ONE
657
+ // naming source (`RoundNaming`), the same name the lifecycle wrote it under.
658
+ const crash = failure ? this.#ledger.readCrash(naming.crashName(frame)) : null;
422
659
  const handoff = crash !== null
423
- ? this.#ledger.crashPath(lane, frame.round)
660
+ ? naming.crashPath(frame)
424
661
  : this.#ledger.handoffPath(op, frame.type, frame.params);
425
- return this.#capsule.emit(outcome.status, String(blockers), handoff, route, this.#routeTarget(frame), crash !== null);
662
+ return this.#capsule.emit(outcome.status, handoff, hop, crash !== null, summary);
426
663
  }
427
664
  /** The frame's RouteTarget — the dispatch-ready literal's target identity (the
428
665
  * frame's own facts: the wave task key · the branch line key · the doc path).
@@ -442,8 +679,10 @@ export class Lifecycle {
442
679
  id: "branch",
443
680
  plan: this.#planPath ?? undefined,
444
681
  };
445
- case "spec":
682
+ case "phase-spec":
683
+ case "overall":
446
684
  case "plan":
685
+ case "single-spec":
447
686
  return {
448
687
  type: frame.type,
449
688
  id: frame.target.doc,