@oscaner-skills/cdd-engine 4.2.0 → 4.4.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 (58) hide show
  1. package/README.md +38 -9
  2. package/README.zh-CN.md +44 -10
  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 +382 -172
  25. package/dist/face/capsule.js +73 -88
  26. package/dist/face/cli.js +152 -38
  27. package/dist/face/declare.js +42 -19
  28. package/dist/face/gate.js +119 -40
  29. package/dist/face/init.js +84 -25
  30. package/dist/face/lifecycle.js +540 -123
  31. package/dist/face/plugins.js +70 -2
  32. package/dist/face/preview.js +69 -18
  33. package/dist/face/route-render.js +60 -21
  34. package/dist/face/termination.js +135 -261
  35. package/dist/face/words.js +139 -13
  36. package/dist/infra/atomic.js +15 -0
  37. package/dist/infra/git.js +25 -0
  38. package/dist/infra/proc.js +150 -0
  39. package/dist/infra/round-log.js +104 -0
  40. package/dist/infra/runtime.js +16 -4
  41. package/dist/infra/workspace.js +7 -2
  42. package/dist/render/brief.js +15 -17
  43. package/dist/render/skeleton.js +41 -28
  44. package/dist/render/templates.js +128 -84
  45. package/dist/session/faces.js +47 -20
  46. package/dist/session/graph.js +13 -37
  47. package/dist/session/handoff-schema.js +16 -8
  48. package/dist/session/inflight.js +282 -0
  49. package/dist/session/ledger.js +603 -145
  50. package/dist/session/line-identity.js +33 -0
  51. package/dist/session/next.js +140 -80
  52. package/dist/session/pipeline.js +247 -0
  53. package/dist/session/preflight.js +276 -68
  54. package/dist/session/reviewed-identity.js +54 -0
  55. package/dist/session/round-naming.js +56 -8
  56. package/dist/session/run.js +364 -80
  57. package/dist/session/wave.js +94 -14
  58. package/package.json +13 -3
@@ -3,11 +3,12 @@
3
3
  // converge into ONE single-entry gate a work command consults before ANY child
4
4
  // dispatch — the clean-tree hard gate (tree-clean → BLOCKED with the commit/discard
5
5
  // guidance, the skill-side claim `engine entry gate: dirty → BLOCKED` finally made
6
- // real), then the wave-side gates (graph validate + the three-verb WaveGate)
7
- // and the doc-side gate (Contract.validate over the target doc).
6
+ // real), then the plan/ledger structure gate (`plan-ledger`, P21 §3.1/§6.4), the
7
+ // wave-side gates (graph validate + the three-verb WaveGate) and the doc-side gate
8
+ // (Contract.validate over the target doc).
8
9
  //
9
10
  // Gate order (the design's pinned sequence, judgeable on every verdict):
10
- // tree-clean → (wave/plan faces) graph validate → (wave face) WaveGate.vet →
11
+ // tree-clean → in-flight → graph → plan-ledger → (wave face) WaveGate.vet →
11
12
  // (spec/plan faces) Contract.validate → dispatch
12
13
  // The evidence/read-back gates stay at the dispatch child face (the seam never
13
14
  // touches the round's produced artifacts — non-pre-flight by design).
@@ -15,18 +16,22 @@
15
16
  // The verdict is the single BLOCK carrier: `gate` names the refusing gate, `reason`
16
17
  // the named refusal row, `message` the CDD_BLOCKED wording (pinned rows), `details`
17
18
  // the named issue/finding lines the renderer prints, `order` the gates that ran
18
- // (the CLI never re-implements a gate — the seam owns the whole sequence). BLOCK
19
- // wording rides the word table (the capsule station + the preflight rows), never a
20
- // CLI restate.
19
+ // (the CLI never re-implements a gate — the seam owns the whole sequence) and
20
+ // `checked` the per-rule checked list (P21 §3.4) — derived from the SAME rule
21
+ // declaration surface the policy composition walks, so "which rule ran" and "what it
22
+ // judged" can never drift apart.
21
23
  //
22
24
  // Module-level exports are types / the class — zero behavior-carrying bare
23
25
  // functions (the plan's zero-bare-function discipline).
24
26
  import { PlanDocType } from "../contract/doc.js";
25
27
  import { FrontMatterExtractor } from "../contract/frontmatter.js";
26
- import { NodeFs } from "../contract/invariants.js";
28
+ import { LedgerTaskSetRule, NodeFs } from "../contract/invariants.js";
29
+ import { Contract } from "../contract/judge.js";
27
30
  import { RepoRoot } from "../infra/root.js";
28
31
  import { SlugIndex } from "../infra/slug-index.js";
32
+ import { TargetFaceTable } from "./faces.js";
29
33
  import { TaskGraph } from "./graph.js";
34
+ import { RoundRecords } from "./ledger.js";
30
35
  import { WaveGate } from "./wave.js";
31
36
  /**
32
37
  * PreFlight — the single pre-flight seam of the work dispatch. One `vet` call runs
@@ -52,82 +57,114 @@ export class PreFlight {
52
57
  this.#waveGate = opts.waveGate ?? new WaveGate();
53
58
  this.#fs = opts.fs ?? new NodeFs();
54
59
  }
55
- /** vet(ctx) — the single seam call: tree-clean → graph → wave → doc-contract.
56
- * The first refused gate owns the verdict; the gates that ran precede it (the
57
- * judgeable order). */
60
+ /** vet(ctx) — the single seam call: tree-clean → in-flight → graph → plan-ledger
61
+ * → wave → doc-contract. The first refused gate owns the verdict; the gates that
62
+ * ran precede it (the judgeable order). */
58
63
  async vet(ctx) {
59
64
  const gates = [];
60
- // 1. tree-clean — the hard gate all three verbs share: a dirty working tree
61
- // BLOCKs BEFORE any other judgment (review's baseline = the committed state). isClean is
62
- // fail-open-false (a non-repo counts dirty — the CDD flow needs git).
65
+ const checked = [];
66
+ // 1. tree-clean — the hard gate all three verbs share.
63
67
  gates.push("tree-clean");
68
+ checked.push("tree-clean");
64
69
  if (!(await this.#git.isClean(ctx.repoRoot))) {
65
- return {
70
+ return this.#refusal({
66
71
  ok: false,
67
72
  gate: "tree-clean",
68
73
  reason: "dirty-tree",
69
74
  message: this.#words.preflightWords().dirtyTree,
70
- order: gates,
71
- };
75
+ }, gates, checked, this.#docOutcomeOf(ctx), { kind: "no-ledger-facts" });
76
+ }
77
+ // 2. in-flight — the tree's dispatch fact (P21 §6.4). The gate judges ONLY: it
78
+ // inspects the record + the holder's liveness and never touches the lock or
79
+ // the record bytes. The acquire is the real dispatch path's write point (it
80
+ // runs after this gate), so the preview's zero-write discipline holds.
81
+ gates.push("in-flight");
82
+ const inFlight = await ctx.inflight.inspect();
83
+ checked.push(this.#inFlightRow(inFlight));
84
+ const held = this.#inFlightRefusal(inFlight, ctx.stealStale === true);
85
+ if (held !== null) {
86
+ return this.#refusal({
87
+ ok: false,
88
+ gate: "in-flight",
89
+ reason: held.reason,
90
+ message: held.message,
91
+ holding: inFlight,
92
+ }, gates, checked, this.#docOutcomeOf(ctx), { kind: "no-ledger-facts" });
72
93
  }
73
- // 2. graph — the wave/plan faces' structural gate: the plan's DependsOn
74
- // graph must validate (missing-edge / missing-id / self-loop / cycle) before
75
- // the dispatch reads it. The task-loss class dies here, never silently.
94
+ // 3. graph — the wave/plan faces' structural gate.
76
95
  let graph = null;
77
96
  if ((ctx.type === "wave" || ctx.type === "plan") && ctx.planText !== null) {
78
97
  gates.push("graph");
98
+ checked.push("graph");
79
99
  graph = new TaskGraph(new PlanDocType("plan").parse(ctx.planText.split("\n")));
80
100
  const issues = graph.validate();
81
101
  if (issues.length > 0) {
82
- return {
102
+ return this.#refusal({
83
103
  ok: false,
84
104
  gate: "graph",
85
105
  reason: "graph",
86
106
  message: this.#words.preflightWords().graph.replace("{count}", String(issues.length)),
87
107
  details: issues.map((issue) => `${issue.kind}@T${issue.task}: ${issue.message}`),
88
- order: gates,
89
- };
108
+ }, gates, checked, this.#docOutcomeOf(ctx), { kind: "no-ledger-facts" });
90
109
  }
91
110
  }
92
- // 3. wave — the three-verb unified wave gate (the task face's phase authority):
93
- // the requested `--tasks` must be EXACTLY the derived open wave at the verb's
94
- // phase. The refusal wording rides the wave-gate word-table rows.
111
+ // 4. plan-ledger — the ledger-scope rules (P21 §3.1/§6.4). Plan / wave / branch
112
+ // dispatches run it; the doc-scope rules never do (two scopes, two entries).
113
+ // A missing fact bundle is NOT a refusal: the rows render `skipped`.
114
+ let ledgerOutcome = { kind: "no-ledger-facts" };
115
+ let ledgerInput = null;
116
+ if (ctx.type === "plan" || ctx.type === "wave" || ctx.type === "branch") {
117
+ gates.push("plan-ledger");
118
+ checked.push("plan-ledger");
119
+ const facts = this.#ledgerFactsOf(ctx, graph);
120
+ if (facts !== null) {
121
+ ledgerInput = this.#ledgerInputOf(ctx);
122
+ const findings = this.#contract.validateLedger(ledgerInput, facts);
123
+ ledgerOutcome = { kind: "judged", findings };
124
+ const ahead = LedgerTaskSetRule.planAhead(facts);
125
+ if (ahead > 0) {
126
+ checked.push(this.#words.checkedWords().planAhead.replace("{count}", String(ahead)));
127
+ }
128
+ if (findings.length > 0) {
129
+ return this.#refusal({
130
+ ok: false,
131
+ gate: "plan-ledger",
132
+ message: this.#words.preflightWords().planLedger,
133
+ details: findings.map((finding) => `${finding.kind}@${finding.field}: ${finding.message}`),
134
+ }, gates, checked, this.#docOutcomeOf(ctx), ledgerOutcome);
135
+ }
136
+ }
137
+ }
138
+ // 5. wave — the three-verb unified wave gate.
95
139
  if (ctx.type === "wave" && graph !== null && ctx.ledger !== null && ctx.tasks !== null) {
96
140
  gates.push("wave");
141
+ checked.push("wave");
97
142
  const verdict = this.#waveGate.vet(ctx.tasks, ctx.verb, graph, ctx.ledger, this.#words);
98
143
  if (!verdict.ok) {
99
- return {
144
+ return this.#refusal({
100
145
  ok: false,
101
146
  gate: "wave",
102
147
  reason: verdict.reason,
103
148
  message: verdict.message ?? "",
104
- order: gates,
105
- };
149
+ }, gates, checked, this.#docOutcomeOf(ctx), ledgerOutcome);
106
150
  }
107
151
  }
108
- // 4. doc-contract — the doc faces' structural gate: the target doc must pass
109
- // Contract.validate (the interpreter's single judgment entry) before its
110
- // review/fix round dispatches. An unreadable doc carries no judgment (no
111
- // fabricated findings from an absent surface). A PRESENT doc carrying no
112
- // `doc-type:` key BLOCKs (spec §12 · D34: the declared type is
113
- // the one reading face, zero filename-suffix fallback).
114
- if (ctx.type === "spec" || ctx.type === "plan") {
152
+ // 6. doc-contract — the doc shapes' structural gate (the doc-scope rules).
153
+ // The four document shapes (`phase-spec` · `overall` · `plan` · `single-spec`)
154
+ // are judged by the SAME gate: the document's declared `doc-type:` picks the
155
+ // contract, never the command's `--type` spelling.
156
+ let docOutcome = this.#docOutcomeOf(ctx);
157
+ if (TargetFaceTable.isDocShape(ctx.type)) {
115
158
  gates.push("doc-contract");
159
+ checked.push("doc-contract");
116
160
  const doc = ctx.doc;
117
- // The relative `RepoPath` erases to the absolute syscall form through the ONE
118
- // value object (the seam's OWN `RepoRoot(ctx.repoRoot)`) just before the read.
119
161
  const docAbsolute = doc === null ? null : new RepoRoot(ctx.repoRoot).resolve(doc.path);
120
162
  const content = docAbsolute === null ? null : this.#fs.read(docAbsolute);
121
163
  if (content !== null && doc !== null && docAbsolute !== null) {
122
- // D1 (position-carrying error): a front-matter block the `yaml` engine cannot parse is
123
- // BLOCKed with the REAL failure (line · column · reason) BEFORE the
124
- // doc-type judgment — an unparseable head also reads no doc-type, so the
125
- // parse check must precede the missing-key check (the misread fix: a
126
- // `[`-led author line reports "invalid YAML", never "no doc-type").
127
164
  const { head } = FrontMatterExtractor.split(content);
128
165
  const parseError = head.parseError;
129
166
  if (parseError !== null) {
130
- return {
167
+ return this.#refusal({
131
168
  ok: false,
132
169
  gate: "doc-contract",
133
170
  reason: "doc-contract",
@@ -137,61 +174,232 @@ export class PreFlight {
137
174
  .replace("{line}", String(parseError.line))
138
175
  .replace("{column}", String(parseError.column))
139
176
  .replace("{source}", parseError.source),
140
- order: gates,
141
- };
177
+ }, gates, checked, { kind: "not-judged" }, ledgerOutcome);
142
178
  }
143
179
  if (doc.docKey === null) {
144
- // Two shapes, one gate: a head carrying no `doc-type:` key reads the
145
- // missing-key word; a head carrying an out-of-domain value reads the
146
- // word that names the value and lists the declared domain.
147
180
  const message = head.docType === null
148
181
  ? this.#words.routeWord("docType")
149
182
  : this.#words.docTypeValueWord(head.docType);
150
- return {
151
- ok: false,
152
- gate: "doc-contract",
153
- reason: "doc-contract",
154
- message,
155
- order: gates,
156
- };
183
+ return this.#refusal({ ok: false, gate: "doc-contract", reason: "doc-contract", message }, gates, checked, { kind: "not-judged" }, ledgerOutcome);
157
184
  }
158
- // The identity gate (spec §2.1/§2.2) — same face, same carrier: the
159
- // workspace key is the declared `slug:`, and the four-way judgment is the
160
- // SAME `SlugIndex` one the board and the dispatch carrier read (one fact,
161
- // one rule; this carrier supplies the pre-flight verdict shape only).
162
185
  const index = SlugIndex.build(ctx.repoRoot, this.#fs);
163
186
  const verdict = index.slugVerdict(doc.path, head.slug);
164
187
  if (verdict.kind !== "accepted") {
165
- return {
188
+ return this.#refusal({
166
189
  ok: false,
167
190
  gate: "doc-contract",
168
191
  reason: "doc-contract",
169
192
  message: this.#words.slugRefusal(verdict),
170
- order: gates,
171
- };
193
+ }, gates, checked, { kind: "not-judged" }, ledgerOutcome);
172
194
  }
195
+ // The plan's topological layers ride the graph gate's own derivation
196
+ // (`TaskGraph#batches()` — the ONE width authority), so the plan-scope rules
197
+ // judge exactly the layer set the wave gates will dispatch against.
198
+ const taskLayers = graph?.batches();
173
199
  const findings = this.#contract.validate({
174
200
  docKey: doc.docKey,
175
201
  path: docAbsolute,
176
202
  content,
177
203
  root: ctx.repoRoot,
178
- // The SAME index the identity gates above read — one scan per dispatch,
179
- // and the contract's chain / slug-ref lookups judge the identical facts.
180
204
  slugIndex: index,
181
205
  fs: this.#fs,
206
+ taskLayers,
182
207
  });
208
+ docOutcome = {
209
+ kind: "judged",
210
+ findings,
211
+ // The layer fact is absent only where the graph gate never ran, and on the
212
+ // dispatch faces that cannot happen: `--type plan` REQUIRES `--plan` (a usage
213
+ // rejection exits first), so a plan doc always has its graph and therefore its
214
+ // layers; a phase-spec's docKey is `phase-spec`, never `plan`; and the wave /
215
+ // branch faces judge no doc target (`no-doc-target`). The row therefore
216
+ // describes a non-dispatch judgment face (a programmatic caller, a future
217
+ // face) — a visible degradation, never a dispatch-time refusal.
218
+ layersUnavailable: doc.docKey === "plan" && taskLayers === undefined,
219
+ };
183
220
  if (findings.length > 0) {
184
- return {
221
+ return this.#refusal({
185
222
  ok: false,
186
223
  gate: "doc-contract",
187
224
  reason: "doc-contract",
188
225
  message: this.#words.preflightWords().docContract,
189
226
  details: findings.map((finding) => `${finding.kind}@${finding.field}: ${finding.message}`),
190
- order: gates,
191
- };
227
+ }, gates, checked, docOutcome, ledgerOutcome);
192
228
  }
193
229
  }
230
+ else {
231
+ docOutcome = { kind: "unreadable" };
232
+ }
233
+ }
234
+ return {
235
+ ok: true,
236
+ order: gates,
237
+ checked: [...checked, ...this.#ruleRows(docOutcome, ledgerOutcome)],
238
+ };
239
+ }
240
+ /** The in-flight gate's refusal — the three-state judgment + the explicit takeover
241
+ * flag. A live holder is always refused (the flag never crosses "alive"); a dead
242
+ * holder or a corrupt-record-with-lock passes only under `stealStale`; a corrupt
243
+ * record with no lock behind it is no holder at all (pass, named on the row). */
244
+ #inFlightRefusal(state, stealStale) {
245
+ if (state.kind === "held") {
246
+ if (state.alive) {
247
+ return {
248
+ reason: "held",
249
+ message: this.#words.inFlightBlocked(state.record, true),
250
+ };
251
+ }
252
+ if (stealStale)
253
+ return null;
254
+ return {
255
+ reason: "held",
256
+ message: this.#words.inFlightBlocked(state.record, false),
257
+ };
258
+ }
259
+ if (state.kind === "corrupt" && state.locked && !stealStale) {
260
+ return {
261
+ reason: "corrupt-record",
262
+ message: this.#words.inFlightWords().corruptLocked,
263
+ };
194
264
  }
195
- return { ok: true, order: gates };
265
+ return null;
266
+ }
267
+ /** The in-flight gate's checked row — `in-flight: <judged state>` (the ONE gate
268
+ * row that names its state; the takeover flag never rewrites the fact, it only
269
+ * lets the gate pass). */
270
+ #inFlightRow(state) {
271
+ const rows = this.#words.checkedWords().inFlight;
272
+ if (state.kind === "absent")
273
+ return `in-flight: ${rows.free}`;
274
+ if (state.kind === "corrupt")
275
+ return `in-flight: ${state.locked ? rows.corruptLocked : rows.corruptUnlocked}`;
276
+ return `in-flight: ${(state.alive ? rows.held : rows.stale).replace("{pid}", String(state.record.pid))}`;
277
+ }
278
+ /** Assemble the refusal verdict — the gates/checked rows accumulated so far, plus
279
+ * the per-rule rows of the judgment outcomes reached (one carrier shape). */
280
+ #refusal(verdict, gates, checked, doc, ledger) {
281
+ return {
282
+ ...verdict,
283
+ order: gates,
284
+ checked: [...checked, ...this.#ruleRows(doc, ledger)],
285
+ };
286
+ }
287
+ /** The doc-scope outcome of a dispatch — "no doc target" on the doc-less faces
288
+ * (wave / branch), "not judged" when the doc-contract gate never ran. The `judged`
289
+ * outcome is assigned by the doc-contract gate itself (the one gate that judges). */
290
+ #docOutcomeOf(ctx) {
291
+ if (ctx.type === "wave" || ctx.type === "branch")
292
+ return { kind: "no-doc-target" };
293
+ return { kind: "not-judged" };
294
+ }
295
+ /** The checked rows of the rule declaration surface — one line per declaration,
296
+ * rendered ONCE (a rule crossing two gates never appears twice). */
297
+ #ruleRows(doc, ledger) {
298
+ const words = this.#words.checkedWords();
299
+ const rows = [];
300
+ for (const declaration of Contract.ruleRows()) {
301
+ if (declaration.scope === "doc") {
302
+ if (doc.kind === "no-doc-target")
303
+ rows.push(`${declaration.id}: ${words.skippedNoDocTarget}`);
304
+ else if (doc.kind === "not-judged")
305
+ rows.push(`${declaration.id}: ${words.skippedNotJudged}`);
306
+ else if (doc.kind === "unreadable")
307
+ rows.push(`${declaration.id}: ${words.skippedUnreadableDoc}`);
308
+ else if (doc.layersUnavailable === true && declaration.id === "wave-width-at-most-three")
309
+ rows.push(`${declaration.id}: ${words.planLayersUnavailable}`);
310
+ else
311
+ rows.push(`${declaration.id}: ${doc.findings.some((finding) => finding.kind === declaration.id)
312
+ ? words.failed
313
+ : words.passed}`);
314
+ continue;
315
+ }
316
+ if (ledger.kind === "no-ledger-facts") {
317
+ rows.push(`${declaration.id}: ${words.skippedNoLedgerFacts}`);
318
+ }
319
+ else {
320
+ rows.push(`${declaration.id}: ${ledger.findings.some((finding) => finding.kind === declaration.id)
321
+ ? words.failed
322
+ : words.passed}`);
323
+ }
324
+ }
325
+ return rows;
326
+ }
327
+ /** The ledger fact bundle of one dispatch — built from the ledger, the plan text
328
+ * and the plan's topological layers. Null when either fact source is absent
329
+ * (the gate then renders `skipped (no ledger facts)`). */
330
+ #ledgerFactsOf(ctx, graph) {
331
+ const ledger = ctx.ledger;
332
+ if (ledger === null || ctx.planText === null)
333
+ return null;
334
+ const parsed = new PlanDocType("plan").parse(ctx.planText.split("\n"));
335
+ const planTasks = parsed.taskBlocks.map((block) => block.id);
336
+ const layers = (graph ?? new TaskGraph(parsed)).batches();
337
+ const data = ledger.readProgress();
338
+ const recorded = this.#recordedTasksOf(data);
339
+ const closed = ledger.closedWaves();
340
+ const closedWaves = (data?.waves ?? [])
341
+ .map((row) => this.#taskIdsOf(row.wave))
342
+ .filter((ids) => ids.length > 0 && ids.every((id) => closed.has(id)));
343
+ return {
344
+ planTasks,
345
+ recordedTasks: recorded,
346
+ closedWaves,
347
+ // The wave rows' closure-time plan-task snapshots (P21 §5.1) — read from the
348
+ // SAME ledger face the wave gate's append judgment reads (zero second source).
349
+ snapshots: this.#snapshotsOf(data),
350
+ layers,
351
+ };
352
+ }
353
+ /** The wave rows' plan-task snapshots — one entry per TASK wave row carrying a
354
+ * snapshot (an absent snapshot is a historical row, not an empty set). The
355
+ * snapshot is read off the row already in hand: the same field `Ledger#planTasksOf`
356
+ * returns, one file read for the whole set instead of one per row. */
357
+ #snapshotsOf(data) {
358
+ const snapshots = [];
359
+ for (const row of data?.waves ?? []) {
360
+ if (this.#taskIdsOf(row.wave).length === 0)
361
+ continue;
362
+ const planTasks = row.planTasks;
363
+ if (planTasks !== undefined)
364
+ snapshots.push({ wave: row.wave, planTasks });
365
+ }
366
+ return snapshots;
367
+ }
368
+ /** The task ids the ledger recorded a COMPLETED round for (the recorded set of the
369
+ * plan/ledger agreement rule — the completion read, so a dispatched-but-failed
370
+ * round does not close the agreement). Only TASK waves count: a doc/branch line row
371
+ * (keyed `"plan"` / `"phase-spec"` / `"overall"` / `"single-spec"` / `"branch"`) is
372
+ * not a task id. */
373
+ #recordedTasksOf(data) {
374
+ const recorded = [];
375
+ for (const row of data?.waves ?? []) {
376
+ const completed = RoundRecords.of(row).some((record) => record.verdict.targetAction);
377
+ if (!completed)
378
+ continue;
379
+ recorded.push(...this.#taskIdsOf(row.wave));
380
+ }
381
+ return recorded;
382
+ }
383
+ /** A wave key's task ids — the numeric-only reading (a non-numeric line key yields
384
+ * no task ids; the ledger rules judge TASK waves, never doc/branch line rows). */
385
+ #taskIdsOf(waveKey) {
386
+ const ids = [];
387
+ for (const part of waveKey.split(",")) {
388
+ const id = Number(part);
389
+ if (Number.isInteger(id) && id > 0)
390
+ ids.push(id);
391
+ }
392
+ return ids;
393
+ }
394
+ /** The ledger judgment's input document — the plan under judgment (the ledger rules
395
+ * are declared plan-only; the other facts ride `LedgerFacts`). */
396
+ #ledgerInputOf(ctx) {
397
+ return {
398
+ docKey: "plan",
399
+ path: ctx.doc?.path ?? "",
400
+ content: ctx.planText ?? "",
401
+ root: ctx.repoRoot,
402
+ fs: this.#fs,
403
+ };
196
404
  }
197
405
  }
@@ -0,0 +1,54 @@
1
+ // packages/cdd-engine/src-next/session/reviewed-identity.ts
2
+ // P25 — the reviewed-revision write-back judgment's ONE home. Two faces state the
3
+ // same write-back: the lifecycle's `#bookkeep` (the record a real run appends) and
4
+ // the preview renderer's `#recordsOf` (the `would record:` forecast). Both ask this
5
+ // file which reviewed input a completed round binds: the phase whitelist is declared
6
+ // here once and the kind → leg mapping is decided here once, so one face can no
7
+ // longer drift from the other.
8
+ //
9
+ // The leg vocabulary is 1:1 with the lifecycle's three write-back methods: `doc` →
10
+ // `#recordReviewedDocRevision` (the plan and spec targets share it — the doc path
11
+ // rides the frame's target), `brief` → `#recordReviewedWaveBrief` (the RENDERED
12
+ // brief, D30), `branch` → `#recordReviewedBranchRevision` (the branch line's plan
13
+ // document).
14
+ //
15
+ // Three same-site facts that are INPUTS, never part of this judgment:
16
+ // 1. `targetAction` — the round verdict's completion flag, held by a real run alone;
17
+ // a dry run never has it, so each face applies it on its own side.
18
+ // 2. the plan path — the branch leg's identity SOURCE (the record method reads it;
19
+ // the preview states it from the scene). Because that path is an input, the
20
+ // branch target carries a leg name of its own instead of folding into `doc`.
21
+ // 3. the wave leg's asymmetry — when the line carries no plan path the real run
22
+ // records nothing while the preview still states the brief leg. Kept as it was:
23
+ // a face-side input difference, not a second judgment.
24
+ //
25
+ // Zero module-level bare functions — this module is one type, one const and the class.
26
+ /** The phases whose completed round binds a reviewed revision — the whitelist's ONE
27
+ * declaration: a completed review binds the revision it judged, a completed fix the
28
+ * revision it produced (so a warn-only fix cannot leave the line adrift in its own
29
+ * delta), and a branch-review rides the review family. `implement` binds nothing. */
30
+ export const REVIEWED_WRITE_PHASES = ["review", "branch-review", "fix"];
31
+ /** The reviewed-revision write-back judgment — which leg (if any) one round writes.
32
+ *
33
+ * A class rather than an arrow-constant object: the repo's zero-bare-function
34
+ * discipline admits no standalone judgment function, and a static-only class is the
35
+ * established shape for one pure read face (precedent: `TargetFaceTable`). */
36
+ // biome-ignore lint/complexity/noStaticOnlyClass: the judgment's one pure read face — the zero-bare-function discipline admits no standalone judgment function.
37
+ export class ReviewedIdentity {
38
+ /** The leg one round binds — null when the phase is outside the whitelist or the
39
+ * target kind has no write-back. An unlisted kind answers null on BOTH faces: a
40
+ * target union that ever grows writes nothing, never a silent doc write-back.
41
+ * Pure: it reads (phase, kind) and nothing else — no ledger, no file, no verdict,
42
+ * no plan path. */
43
+ static legOf(phase, kind) {
44
+ if (!REVIEWED_WRITE_PHASES.includes(phase))
45
+ return null;
46
+ if (kind === "wave")
47
+ return "brief";
48
+ if (kind === "plan" || kind === "spec")
49
+ return "doc";
50
+ if (kind === "branch")
51
+ return "branch";
52
+ return null;
53
+ }
54
+ }
@@ -6,6 +6,7 @@
6
6
  // naming table is the single truth, never a second list).
7
7
  //
8
8
  // Module-level exports are the class — zero behavior-carrying bare functions.
9
+ import { TargetFaceTable } from "./faces.js";
9
10
  /**
10
11
  * RoundNaming — the one home of a round's prescribed artifact names. A frame's
11
12
  * report / evidence / brief names derive here, so every consumer (the lifecycle's
@@ -40,12 +41,8 @@ export class RoundNaming {
40
41
  * `{family}-{op}{-round}-report.md` (the implement round carries no round token:
41
42
  * the line keys the implement round alone). */
42
43
  report(frame) {
43
- if (frame.type === "spec" || frame.type === "plan") {
44
- return this.#workspace.resolve(`${frame.type}-${this.op(frame)}-${frame.round}-report.md`);
45
- }
46
- const family = frame.type === "wave" ? `tasks-${frame.params.tasks ?? ""}` : "branch";
47
- const suffix = frame.phase === "implement" ? "" : `-${frame.round}`;
48
- return this.#workspace.resolve(`${family}-${this.op(frame)}${suffix}-report.md`);
44
+ const params = { tasks: frame.params.tasks, round: frame.round };
45
+ return this.#workspace.resolve(`${this.#stem(this.op(frame), frame.type, params)}-report.md`);
49
46
  }
50
47
  /** The prescribed test-evidence path of a round — "" off the evidence rounds (the doc
51
48
  * lines and the review rounds prescribe no evidence file). */
@@ -55,9 +52,10 @@ export class RoundNaming {
55
52
  }
56
53
  /** The test-evidence file NAME of a work frame — the workspace-relative face the
57
54
  * read-back gate reads it by (`{line}-test-evidence.json`: the task families key
58
- * the line, the branch line names the family alone). "" off the evidence rounds. */
55
+ * the line, the branch line names the family alone). "" off the evidence rounds
56
+ * — the doc shapes (phase-spec · overall · plan · single-spec) prescribe none. */
59
57
  evidenceName(frame) {
60
- if (frame.type === "spec" || frame.type === "plan")
58
+ if (TargetFaceTable.isDocShape(frame.type))
61
59
  return "";
62
60
  if (frame.phase !== "implement" && frame.phase !== "fix")
63
61
  return "";
@@ -70,4 +68,54 @@ export class RoundNaming {
70
68
  prefix(frame) {
71
69
  return frame.type === "wave" ? "tasks" : "branch";
72
70
  }
71
+ /** The attempt number a dispatch of one op/cycle would take — the max attempt
72
+ * already on record for that identity plus one (1 when the cycle was never
73
+ * dispatched). The ledger's records are the input slice, so the naming table
74
+ * allocates the attempt ONCE for both the record and the log name. */
75
+ attemptOf(records, op, cycle) {
76
+ let latest = 0;
77
+ for (const record of records) {
78
+ if (record.op === op && record.cycle === cycle && record.attempt > latest) {
79
+ latest = record.attempt;
80
+ }
81
+ }
82
+ return latest + 1;
83
+ }
84
+ /** The per-round log file NAME of a round — the report stem with `.log` instead
85
+ * of `-report.md`, carrying `-a{attempt}` when the dispatch is a re-attempt (so
86
+ * attempt 1's log is never overwritten). The attempt is allocated by `attemptOf`
87
+ * and passed in, never extrapolated here. */
88
+ logName(op, type, params, attempt) {
89
+ const attemptSuffix = attempt > 1 ? `-a${attempt}` : "";
90
+ return `${this.#stem(op, type, params)}${attemptSuffix}.log`;
91
+ }
92
+ /** The round's artifact STEM — the ONE derivation the report and the log name read
93
+ * (`{type}-{op}-{round}` on the doc lines, `{family}-{op}{-round}` on the
94
+ * wave/branch lines). The round-token decision keys on the FAMILY OP (implement is
95
+ * the round-less family), so the report and its log can never diverge. */
96
+ #stem(op, type, params) {
97
+ if (TargetFaceTable.isDocShape(type))
98
+ return `${type}-${op}-${params.round}`;
99
+ const family = type === "wave" ? `tasks-${params.tasks ?? ""}` : "branch";
100
+ const suffix = op === "implement" ? "" : `-${params.round}`;
101
+ return `${family}-${op}${suffix}`;
102
+ }
103
+ /** The crash record's workspace-relative name — `crash-{line}-{op}-{round}.json`.
104
+ * The `line` derives from the frame's ONE identity (wave → `tasks-{tasks}`;
105
+ * branch / the doc shapes → the line-type constant), the `op` keeps the verb
106
+ * (`RoundNaming.op`: branch-review rides the review family) — so a wave's
107
+ * implement-2 and review-2 crash records never overwrite each other. */
108
+ crashName(frame) {
109
+ return `crash-${this.#line(frame)}-${this.op(frame)}-${frame.round}.json`;
110
+ }
111
+ /** The crash record's on-disk path — the same derivation as `crashName` (one
112
+ * name, one rule; the read and write faces agree by construction). */
113
+ crashPath(frame) {
114
+ return this.#workspace.resolve(this.crashName(frame));
115
+ }
116
+ /** A frame's line identity — the dispatch unit the crash record keys on: the
117
+ * wave's task group (`tasks-{tasks}`), the branch line, or the doc-type line. */
118
+ #line(frame) {
119
+ return frame.type === "wave" ? `tasks-${frame.params.tasks ?? ""}` : frame.type;
120
+ }
73
121
  }