@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,700 @@
1
+ // packages/cdd-engine/src-next/face/lifecycle.ts
2
+ // T8 — the lifecycle face (the split contract §6.2: face/cli.ts slims to composition).
3
+ // The dispatch seam's production default lives here — CliLifecycle (the former
4
+ // HarnessDispatch composition member, renamed by the split; face/cli.ts re-exports it
5
+ // as HarnessDispatch so the public surface is unchanged) — the dispatch + readback +
6
+ // round-context plane (§6.2: implement/review/fix dispatch, the read-back reconstruct
7
+ // (#reconstruct/#reject/#materialize + carrier helpers), the round-context data
8
+ // (#valuesOf/#childPrompt/round-context fact assembly)). The shared seams the
9
+ // lifecycle rides (cli io / sync process / env / scene) are declared here too — the
10
+ // root composition imports them back (zero public-export drift, zero import cycle).
11
+ // The root Cli holds the lifecycle instances and composes through them via its .action
12
+ // thin shells — zero bare functions; every collaborator stays injectable (the tests
13
+ // substitute the hermetic ones).
14
+
15
+ // The module exports the shared seams + the lifecycle class — zero behavior-carrying
16
+ // bare functions.
17
+
18
+ import process from "node:process";
19
+ import { execaSync } from "execa";
20
+ import { printParseErrorCode } from "jsonc-parser";
21
+ import { ConfigLoader } from "../infra/config.ts";
22
+ import type { HandoffFamily } from "../infra/runtime.ts";
23
+ import type { Workspace } from "../infra/workspace.ts";
24
+ import type { TemplateValues, WorkMode } from "../render/templates.ts";
25
+ import { TemplateAssembler } from "../render/templates.ts";
26
+ import type { HandoffSchemaFace } from "../session/handoff-schema.ts";
27
+ import { HandoffSchema } from "../session/handoff-schema.ts";
28
+ import type { Ledger, OpType, RoundStatus } from "../session/ledger.ts";
29
+ import type { DispatchOutcome, DispatchStep, OpenFrame } from "../session/run.ts";
30
+ import { DISPATCH, HOSTS, HostDetect, type HostId, type HostReferenceTable, REFS } from "./host.ts";
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // the stable seams — the shared faces the composition root + the lifecycle ride
34
+ // (declared here, re-exported by face/cli.ts so the public surface never drifts)
35
+ // ---------------------------------------------------------------------------
36
+
37
+ /** The CLI io seam — production wraps process stdio; tests capture. */
38
+ export interface CliIo {
39
+ stdout(text: string): void;
40
+ stderr(text: string): void;
41
+ }
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // the sync process seam + the harness dispatch (the production dispatch default)
45
+ // ---------------------------------------------------------------------------
46
+
47
+ /** The sync child-process face — the fail-open subprocess seam the harness dispatch
48
+ * runs through (a non-zero/broken child rides the code, never a throw). */
49
+ export interface SyncProcess {
50
+ run(
51
+ command: string,
52
+ args: readonly string[],
53
+ cwd: string,
54
+ ): { code: number; stdout: string; stderr: string };
55
+ }
56
+
57
+ /** SyncRunner — the unbounded sync child channel (spec §14 · D36): execa's
58
+ * synchronous face, which imposes no output-buffer ceiling — the whole-buffer
59
+ * cap class the retired built-in call hit (a fixed 1 MiB default, the W1
60
+ * `child claude returned no status line` truncation) does not exist here. The
61
+ * face stays synchronous (the T8 lifecycle's DispatchStep seam is one dispatch,
62
+ * one advance) and keeps the injected `SyncProcess` shape byte-for-byte: a
63
+ * non-zero/broken child rides the code, never a throw — `reject: false` surfaces
64
+ * the failure as a result, and `stripFinalNewline: false` keeps the child's
65
+ * stdout verbatim (the `RETURN_STDOUT_BLOCK` tail stays intact). The adapter is
66
+ * a pure `#collect` read: no buffering to bound, no worker, no concurrency. */
67
+ export class SyncRunner implements SyncProcess {
68
+ run(
69
+ command: string,
70
+ args: readonly string[],
71
+ cwd: string,
72
+ ): { code: number; stdout: string; stderr: string } {
73
+ return this.#collect(command, args, cwd);
74
+ }
75
+
76
+ /** The synchronous collection — execa's sync face with the three options the
77
+ * fail-open `SyncProcess` contract needs: `reject: false` (a failed child is a
78
+ * result, never a throw), `stripFinalNewline: false` (byte-verbatim stdout), and
79
+ * the default unbounded output buffer (the cap class is retired). The result
80
+ * reads back into the same `{code, stdout, stderr}` face — `exitCode ?? 1` is the
81
+ * exit code; stderr is the child's own stream when it wrote one, else the execa
82
+ * diagnostic (a spawn failure like ENOENT writes nothing, so its reason rides the
83
+ * `shortMessage` — the fail-open face keeps a reason text, never an empty block). */
84
+ #collect(
85
+ command: string,
86
+ args: readonly string[],
87
+ cwd: string,
88
+ ): { code: number; stdout: string; stderr: string } {
89
+ const result = execaSync(command, [...args], {
90
+ cwd,
91
+ reject: false,
92
+ stripFinalNewline: false,
93
+ });
94
+ return {
95
+ code: result.exitCode ?? 1,
96
+ stdout: result.stdout ?? "",
97
+ stderr: result.stderr || (result.failed ? (result.shortMessage ?? "") : ""),
98
+ };
99
+ }
100
+ }
101
+
102
+ /** The environment face the harness dispatch detects the host against. */
103
+ export type ProcessEnvLike = Record<string, string | undefined>;
104
+
105
+ /** One dispatch scene — the per-invocation composition the work commands assemble
106
+ * (the workspace + ledger the frame's round rides, the plan/brief paths the prompt
107
+ * references, the base artifact's branch name the branch review's scope anchor
108
+ * (BASE_BRANCH) derives). */
109
+ export interface DispatchScene {
110
+ workspace: Workspace;
111
+ ledger: Ledger;
112
+ planPath: string | null;
113
+ briefPath: string | null;
114
+ baseBranch?: string | null;
115
+ }
116
+
117
+ /**
118
+ * CliLifecycle — the lifecycle's dispatch-seam production default (the split contract's
119
+ * lifecycle face; face/cli.ts re-exports it as HarnessDispatch so the composition
120
+ * surface keeps its name). `step()` returns the DispatchStep the lifecycle runs, which
121
+ * assembles the dispatch prompt (the render template-contract data plane) from the
122
+ * frame, runs the host harness CLI (the harness-contract rows: cli + invoke flags +
123
+ * the phase's skill-ref slash form) and parses the child's return block back into the
124
+ * lifecycle's outcome. Detection reads the harness-contract detect markers from the
125
+ * injected env — empty host → a BLOCKED outcome over the CDD_BLOCKED channel (never a
126
+ * thrown dispatch).
127
+ */
128
+ export class CliLifecycle {
129
+ readonly #env: ProcessEnvLike;
130
+ readonly #cwd: string;
131
+ readonly #sync: SyncProcess;
132
+ readonly #config: ConfigLoader;
133
+ readonly #template: TemplateAssembler;
134
+ readonly #io: CliIo;
135
+ readonly #scene: DispatchScene;
136
+ readonly #findings: string | null;
137
+ /** The handoff-schema face — stateless, one shared instance (the read-back
138
+ * validator + the injected prompt text). */
139
+ readonly #handoffSchema = new HandoffSchema();
140
+
141
+ constructor(opts: {
142
+ env?: ProcessEnvLike;
143
+ cwd?: string;
144
+ sync?: SyncProcess;
145
+ config?: ConfigLoader;
146
+ template?: TemplateAssembler;
147
+ io?: CliIo;
148
+ scene: DispatchScene;
149
+ findings?: string | null;
150
+ }) {
151
+ this.#env = opts.env ?? process.env;
152
+ this.#cwd = opts.cwd ?? process.cwd();
153
+ this.#sync = opts.sync ?? new SyncRunner();
154
+ this.#config = opts.config ?? new ConfigLoader();
155
+ this.#template = opts.template ?? new TemplateAssembler();
156
+ this.#io = opts.io ?? {
157
+ stdout: (t) => process.stdout.write(t),
158
+ stderr: (t) => process.stderr.write(t),
159
+ };
160
+ this.#scene = opts.scene;
161
+ this.#findings = opts.findings ?? null;
162
+ }
163
+
164
+ /** The host-harness id detected from the env — "claude" | "cursor" | "pi" | "" —
165
+ * a delegation to the module-level judgment (HostDetect.detect, face/host.ts —
166
+ * the detection's single home; this instance method is the injectable-env
167
+ * adapter the lifecycle face rides, behavior unchanged). */
168
+ detectHost(env: ProcessEnvLike = this.#env): string {
169
+ return HostDetect.detect(env);
170
+ }
171
+
172
+ /** The DispatchStep the lifecycle runs — one frame → the outcome. */
173
+ step(): DispatchStep {
174
+ return (frame) => this.#dispatch(frame);
175
+ }
176
+
177
+ /** One dispatch — prompt from the template plane + the frame, host child via
178
+ * the harness-contract rows, the child's write-back read in (v1.9: the draft at
179
+ * OUTPUT_HANDOFF is the round's content — the block is the pointer). */
180
+ #dispatch(frame: OpenFrame): DispatchOutcome {
181
+ const host = this.detectHost();
182
+ if (host === "") {
183
+ this.#io.stderr(
184
+ "CDD_BLOCKED: no host harness detected (run cdd from within a supported harness)\n",
185
+ );
186
+ return { status: "BLOCKED" };
187
+ }
188
+ const prompt = this.#template.render(this.#valuesOf(frame));
189
+ const row = HOSTS[host as HostId];
190
+ const cliName = row.cli;
191
+ const args = [...row.invoke.split(" ").filter((part) => part.length > 0)];
192
+ const ref = this.#skillRef(host, frame);
193
+ // The child receives ONE prompt argument — per the host's promptForm data column
194
+ // (§3.5): the ref-prefixed form embeds the slash ref at the start of the single
195
+ // prompt positional (claude -p consumes the whole first positional as the prompt;
196
+ // a standalone ref arg after the flags would be swallowed, losing everything after
197
+ // the ref) — the prompt assembly is data, never a code assumption.
198
+ const result = this.#sync.run(
199
+ cliName,
200
+ [...args, this.#childPrompt(row.promptForm, ref, prompt)],
201
+ this.#cwd,
202
+ );
203
+ if (result.code !== 0) {
204
+ this.#io.stderr(`CDD_BLOCKED: child ${cliName} exited ${result.code}\n`);
205
+ return { status: "BLOCKED" };
206
+ }
207
+ // The three-line block is the child's termination handshake — a child that exits 0
208
+ // without a status line misbehaved (the abnormal face owns it; no draft read).
209
+ if (!/^status:\s*\S+/m.test(result.stdout)) {
210
+ this.#io.stderr(`CDD_BLOCKED: child ${cliName} returned no status line\n`);
211
+ return { status: "BLOCKED" };
212
+ }
213
+ return this.#reconstruct(frame, this.#parseBlockReturn(result.stdout));
214
+ }
215
+
216
+ /** The work-mode of a frame phase — branch-review rides the review family. */
217
+ #opOf(frame: OpenFrame): OpType {
218
+ return frame.phase === "branch-review" ? "review" : frame.phase;
219
+ }
220
+
221
+ /** The dispatch-table work-mode (ROLE) of a frame — the spec/plan fix faces ride
222
+ * the docs-fix mode; everything else maps by its phase (§3.5's four-mode table). */
223
+ #roleOf(frame: OpenFrame): WorkMode {
224
+ if (frame.phase === "fix") {
225
+ return frame.type === "spec" || frame.type === "plan" ? "docs-fix" : "fix";
226
+ }
227
+ return frame.phase === "implement" ? "implement" : "review";
228
+ }
229
+
230
+ /** The phase's skill-ref slash form for the detected host ("/mattpocock-skills:implement"
231
+ * · "/mattpocock-skills:code-review" etc.); null when the phase carries no skill
232
+ * ref (the fix face and the spec/plan reviews — their criteria ride the
233
+ * prompt's fixed body, never a slash arg). */
234
+ #skillRef(host: string, frame: OpenFrame): string | null {
235
+ const dispatch = DISPATCH;
236
+ let ref: unknown = null;
237
+ if (frame.phase === "review" || frame.phase === "branch-review") {
238
+ // The task/branch rows are object-shaped {ref}; the spec/plan review types
239
+ // carry NO dispatch row (their criteria are the review prompt's fixed body).
240
+ const entry = dispatch.review[frame.type as "wave" | "branch"];
241
+ const declaredRef = (entry as { ref?: unknown } | undefined)?.ref;
242
+ ref =
243
+ typeof declaredRef === "string" && declaredRef.startsWith("mattpocock-skills:")
244
+ ? declaredRef
245
+ : null;
246
+ } else {
247
+ // The implement row is the dispatch table's single string slot; the other
248
+ // phases (fix) carry no dispatch row — the lookup resolves null (the fix
249
+ // face's ref-less face, same-shape as the spec/plan reviews).
250
+ const value = dispatch[frame.phase as "implement"];
251
+ ref = typeof value === "string" ? value : null;
252
+ }
253
+ if (typeof ref !== "string") return null;
254
+ const hostForm = (REFS as HostReferenceTable)[ref]?.[host as HostId];
255
+ return hostForm ?? null;
256
+ }
257
+
258
+ /** The child's single prompt argument — per the host's promptForm data contract
259
+ * (§3.5): the ref-prefixed form embeds the skill-ref slash form at the start of
260
+ * the assembled dispatch prompt as one positional (`/kairos:cdd-* <prompt>`); the
261
+ * plain form passes the prompt verbatim. */
262
+ #childPrompt(form: "ref-prefixed" | "plain", ref: string | null, prompt: string): string {
263
+ return form === "ref-prefixed" && ref !== null ? `${ref} ${prompt}` : prompt;
264
+ }
265
+
266
+ /** The round-context zone values of the dispatch prompt (the naming contract:
267
+ * ROLE nominative · WAVE (unit) · INPUT_* read-side · OUTPUT_* write-side · WORKSPACE_*
268
+ * environment · BASE_BRANCH scope anchor). Every declared token supplied — a mode's
269
+ * non-consumed slots stay empty and are NOT emitted by the assembler
270
+ * (empty-valued keys are dropped), so each mode's round context carries only the
271
+ * facts the mode reads. The review criteria/lens are NOT values — they fold into
272
+ * the review type's fixed prefix (§3.7). */
273
+ #valuesOf(frame: OpenFrame): TemplateValues {
274
+ const scene = this.#scene;
275
+ const op = this.#opOf(frame);
276
+ const role = this.#roleOf(frame);
277
+ const params = frame.params;
278
+ const isReview = frame.phase === "review" || frame.phase === "branch-review";
279
+ const docPath = frame.target.kind === "doc" ? frame.target.doc : null;
280
+ const isWave = frame.type === "wave";
281
+ return {
282
+ ROLE: role,
283
+ // v1.22 (wave-unitary): the wave face's scope IS the wave (the whole task list)
284
+ // — the round context speaks the UNIT, `WAVE`; the line faces carry their own
285
+ // read-side identity (INPUT_DOC — the doc/branch line's own token under the
286
+ // wave-unitary model).
287
+ WAVE: isWave ? (params.tasks ?? "") : "",
288
+ // The wave-brief read input — the ONE engine-rendered brief of the current
289
+ // dispatch (the unconditional re-extract at every dispatch makes it the pure
290
+ // read face of the wave line — §4.2); the non-wave faces carry no brief path
291
+ // (the slot stays empty, never emitted).
292
+ INPUT_WAVE_BRIEF: isWave ? (scene.briefPath ?? "") : "",
293
+ // v1.9: INPUT_FINDINGS is fix/docs-fix only — the open findings of the source
294
+ // review; a review writes its own draft (INPUT_FINDINGS === OUTPUT_HANDOFF
295
+ // would be a short-circuit).
296
+ INPUT_FINDINGS:
297
+ op === "fix"
298
+ ? (this.#findings ?? scene.ledger.handoffPath("review", frame.type, params))
299
+ : "",
300
+ // The doc anchor — the target doc for a doc line, the plan path for a branch
301
+ // line (the branch review/fix judge the plan document). Empty off those faces.
302
+ INPUT_DOC: docPath ?? (frame.target.kind === "branch" ? (scene.planPath ?? "") : ""),
303
+ // The branch/wave tree-review scope anchor (BASE_BRANCH) — engine-injected
304
+ // from the base artifact at dispatch; empty off those faces (spec/plan reviews
305
+ // carry none, and the empty slot is dropped by the assembler).
306
+ BASE_BRANCH:
307
+ isReview && (frame.type === "branch" || frame.type === "wave")
308
+ ? (scene.baseBranch ?? "")
309
+ : "",
310
+ // find #5 (P4.1 T7) — the prescribed artifact write paths (the {family}-{key}-
311
+ // {artifact} single naming): the round context carries the canonical OUTPUT_*
312
+ // names the child MUST use (zero free naming · cross-round zero overwrite); a
313
+ // slot the frame's family does not consume stays empty and is dropped (only
314
+ // present facts land). The brief is a pure read input (INPUT_WAVE_BRIEF) with
315
+ // no write slot.
316
+ OUTPUT_REPORT: this.#outputOf(frame, "report"),
317
+ OUTPUT_EVIDENCE: this.#outputOf(frame, "evidence"),
318
+ OUTPUT_HANDOFF: scene.ledger.handoffPath(op, frame.type, params),
319
+ REVIEW_TYPE: isReview ? frame.type : "",
320
+ WORKSPACE_DIR: scene.workspace.path,
321
+ WORKSPACE_ID: scene.workspace.slug,
322
+ // v1.9 — the injected writable-subset schema (projection ①): the `## Handoff
323
+ // schema` section of the mode's fixed prefix (byte-stable per mode; the work
324
+ // faces — implement/fix — carry the evidence-file fence too).
325
+ HANDOFF_SCHEMA: this.#schemaText(frame),
326
+ };
327
+ }
328
+
329
+ /** The canonical prescribed OUTPUT_* write path of one artifact kind (find #5 —
330
+ * the {family}-{key}-{artifact} single naming scheme; find #9 — branch line
331
+ * drops the range token: `branch-{op}{-round}-report.md` · `branch-test-evidence.json`,
332
+ * the branch line carries no commit identity · doc = the {type}-{op}-{round} stem,
333
+ * spec-review-1). "" when the frame's family does not consume the slot — only
334
+ * present facts ride the prompt (the assembler drops the empty-valued keys). */
335
+ #outputOf(frame: OpenFrame, kind: "report" | "evidence"): string {
336
+ const workspace = this.#scene.workspace;
337
+ const op = this.#opOf(frame);
338
+ if (frame.type === "spec" || frame.type === "plan") {
339
+ // The doc family — the round-keyed {type}-{op}-{round} stem (spec-review-1):
340
+ // every review/docs-fix round books its own report (a re-review never
341
+ // overwrites its predecessor); evidence is a work-family face only.
342
+ if (kind !== "report") return "";
343
+ return workspace.resolve(`${frame.type}-${op}-${frame.round}-report.md`);
344
+ }
345
+ const family = frame.type === "wave" ? `tasks-${frame.params.tasks ?? ""}` : "branch";
346
+ if (kind === "report") {
347
+ const suffix = frame.phase === "implement" ? "" : `-${frame.round}`;
348
+ return workspace.resolve(`${family}-${op}${suffix}-report.md`);
349
+ }
350
+ // evidence — the work faces only (implement/fix write the canonical evidence file)
351
+ if (frame.phase !== "implement" && frame.phase !== "fix") return "";
352
+ return workspace.resolve(this.#evidenceName(frame));
353
+ }
354
+
355
+ /** The canonical evidence file name of a work frame (find #5/#9 — the
356
+ * {line}-test-evidence.json form: `tasks-{tasks}-test-evidence.json` /
357
+ * `branch-test-evidence.json` — the branch line's row-level current state,
358
+ * overwritten each round (the range token left the name);
359
+ * the same name the read-back gate reads). The line token joins when the frame
360
+ * keys it (the task face) — a key-less line (branch) names the family alone. */
361
+ #evidenceName(frame: OpenFrame): string {
362
+ const key = frame.type === "wave" ? (frame.params.tasks ?? "") : "";
363
+ const line = key === "" ? this.#evidencePrefix(frame) : `${this.#evidencePrefix(frame)}-${key}`;
364
+ return `${line}-test-evidence.json`;
365
+ }
366
+
367
+ /** The RETURN_STDOUT_BLOCK child stdout → the outcome: the two canonical lines
368
+ * (status / artifacts), each key=value tokens; a missing status line is a BLOCKED
369
+ * outcome (only present facts land). */
370
+ #parseBlockReturn(stdout: string): DispatchOutcome {
371
+ const status = stdout.match(/^status:\s*(\S+)/m)?.[1];
372
+ if (status === undefined) return { status: "BLOCKED" };
373
+ const outcome: DispatchOutcome = { status: status as RoundStatus };
374
+ const artifacts = stdout.match(/^artifacts:(.*)$/m);
375
+ if (artifacts !== null) {
376
+ outcome.artifacts = {};
377
+ for (const pair of artifacts[1].trim().split(/\s+/)) {
378
+ const eq = pair.indexOf("=");
379
+ if (eq !== -1) outcome.artifacts[pair.slice(0, eq)] = pair.slice(eq + 1);
380
+ }
381
+ }
382
+ return outcome;
383
+ }
384
+
385
+ // -------------------------------------------------------------------------
386
+ // the read-back reconstruct (§3.6) — the draft is the round's content
387
+ // -------------------------------------------------------------------------
388
+
389
+ /** The read-back reconstruct — the child's draft at OUTPUT_HANDOFF is the round's
390
+ * content source of truth: read it, validate it against the mode's writable
391
+ * subset (projection ② of session/handoff-schema.ts — the SAME declared objects
392
+ * the prompt injected), then build the final carrier the lifecycle persists in
393
+ * place (agent draft → finalized, full-replace at the same path — the engine
394
+ * remains the carrier's single author). A missing or schema-violating draft →
395
+ * BLOCK over the CDD_BLOCKED channel + a crash record + the draft untouched
396
+ * (on failure, no overwrite — the child's work is never clobbered; resume re-runs the same
397
+ * command, which re-offers the round). The test-evidence file (task-family work
398
+ * rounds only) is read back with the same stakes: a missing/violating file
399
+ * rewrites the carrier to BLOCKED (persisted — the child's work is kept, marked
400
+ * bad), the second fix for a prose-only claim. */
401
+ #reconstruct(frame: OpenFrame, block: DispatchOutcome): DispatchOutcome {
402
+ const scene = this.#scene;
403
+ const op = this.#opOf(frame);
404
+ const face = this.#familyOf(op, frame.type).schema ?? "work";
405
+ const schema = this.#handoffSchema;
406
+ const path = scene.ledger.handoffPath(op, frame.type, frame.params);
407
+ // The tri-state draft read — a MISSING draft ("never written") and a MALFORMED one
408
+ // (present but unparseable JSON) are different facts: the rejection reports each
409
+ // truly, so a corrupt draft is never misreported as "not written" (D27). The read
410
+ // is LENIENT (D39): the draft is a child-LLM-authored carrier, and a trailing comma
411
+ // (a routine model slip) must not void the whole round — jsonc-parser tolerates the
412
+ // lenient dialect while a real break (a missing brace, …) still reports malformed.
413
+ const draftRead = scene.workspace.readJsonLenient<Record<string, unknown>>(
414
+ scene.ledger.handoffName(op, frame.type, frame.params),
415
+ );
416
+ if (draftRead.kind === "missing") {
417
+ return this.#reject(frame, path, `the handoff draft was not written at ${path}`);
418
+ }
419
+ if (draftRead.kind === "malformed") {
420
+ // The lenient face carries the parser's precise error codes (D39) — surface
421
+ // them in the rejection so a genuinely corrupt draft is diagnosable, not just
422
+ // "malformed".
423
+ const codes = (draftRead.errors ?? [])
424
+ .map((error) => printParseErrorCode(error.error))
425
+ .join(", ");
426
+ const detail = codes === "" ? "" : ` (${codes})`;
427
+ return this.#reject(frame, path, `the handoff draft at ${path} is malformed JSON${detail}`);
428
+ }
429
+ const draft = draftRead.value;
430
+ const problems = schema.violations(face, draft);
431
+ if (problems.length > 0) {
432
+ return this.#reject(
433
+ frame,
434
+ path,
435
+ `the handoff draft at ${path} violates the ${face} schema: ${problems.join("; ")}`,
436
+ );
437
+ }
438
+ // T2 — the face-aware read: the findings face ALONE reads `draft.findings` (its
439
+ // own declared required field — rolled up to the conclusion); the work face
440
+ // derives its status from the draft's declared status, never the findings plane
441
+ // (the work writable subset declares no findings field — zero findings read).
442
+ // The conclusion rides the ONE source (`HandoffSchema.conclusionOf`) the ledger
443
+ // legs read too — the reconstruct never rules a work status by a second path.
444
+ const findings =
445
+ face === "findings" ? (Array.isArray(draft.findings) ? draft.findings : []) : [];
446
+ // A validated draft's conclusion is total: the findings face rolls up its own
447
+ // required findings, and the work face's `status` passed the `required` gate above
448
+ // — so the `?? "BLOCKED"` never fires here (a work draft without a status never
449
+ // reaches this line; the absent→undefined case exists only for on-disk legacy
450
+ // carriers the ledger reads back, never a schema-validated draft).
451
+ let status: RoundStatus = schema.conclusionOf(face, draft) ?? "BLOCKED";
452
+ let reason: string | null = null;
453
+ // The evidence gate (v1.9) — the work faces (implement/fix task+branch) write
454
+ // the canonical `{family-prefix}-{key}-test-evidence.json` under the workspace
455
+ // (§3.7 naming: tasks- for the task families, branch- for the branch fix); the
456
+ // docs faces (review/docs-fix) carry no evidence file. The read-back is REAL — a
457
+ // missing/malformed/schema-violating file rewrites the draft to BLOCKED (each
458
+ // cause reported truly — the tri-state read, D27).
459
+ if (face === "work") {
460
+ const evidenceName = this.#evidenceName(frame);
461
+ const evidencePath = scene.workspace.resolve(evidenceName);
462
+ const evidenceRead = scene.workspace.readJson<unknown>(evidenceName);
463
+ // The SAME tri-state discrimination as the draft leg (D27): a PRESENT-but-corrupt
464
+ // evidence file reports its true cause, never the misleading "missing" — only a
465
+ // genuinely absent file (or a schema-violating present one) rides the schema
466
+ // verdict below.
467
+ if (evidenceRead.kind === "malformed") {
468
+ status = "BLOCKED";
469
+ reason = `the test evidence at ${evidencePath} is malformed JSON`;
470
+ } else {
471
+ const evidence = evidenceRead.kind === "ok" ? evidenceRead.value : null;
472
+ const evidenceProblems = schema.evidenceViolations(evidence);
473
+ if (evidenceProblems.length > 0) {
474
+ status = "BLOCKED";
475
+ reason = `the test evidence at ${evidencePath} violates the contract: ${evidenceProblems.join("; ")}`;
476
+ }
477
+ }
478
+ }
479
+ return {
480
+ status,
481
+ findings: face === "findings" ? schema.findingsOf(findings) : undefined,
482
+ artifacts: block.artifacts,
483
+ carrier: this.#materialize(frame, face, draft, status, reason),
484
+ };
485
+ }
486
+
487
+ /** The read-back rejection face — CDD_BLOCKED reason + the crash record (the
488
+ * same-command resume's decision source: the attempted handoff + the resume
489
+ * command) + NO carrier (the bookkeep leaves the draft untouched). */
490
+ #reject(frame: OpenFrame, path: string, reason: string): DispatchOutcome {
491
+ this.#io.stderr(`CDD_BLOCKED: ${reason}\n`);
492
+ const op = this.#opOf(frame);
493
+ this.#scene.ledger.writeCrash(`${op}.${frame.type}`, frame.round, {
494
+ exitCode: 0,
495
+ stderrTail: [reason],
496
+ stdoutTail: [],
497
+ attemptedHandoff: path,
498
+ next: this.#resumeOf(frame),
499
+ cause: "contract-violation",
500
+ });
501
+ return { status: "BLOCKED" };
502
+ }
503
+
504
+ /** Build the final carrier — the validated writable fields from the draft (the
505
+ * engine-seated identity rides the canonical file name, never inline: phase/tasks
506
+ * are not declared and never written — v1.30), persisted by the bookkeep
507
+ * full-replace at the SAME path (agent draft → finalized). The evidence override
508
+ * rewrites the status to BLOCKED + a failure_category + the reason note (the
509
+ * child's work preserved, marked bad). */
510
+ #materialize(
511
+ frame: OpenFrame,
512
+ face: HandoffSchemaFace,
513
+ draft: Record<string, unknown>,
514
+ status: RoundStatus,
515
+ reason: string | null,
516
+ ): Record<string, unknown> {
517
+ const ledger = this.#scene.ledger;
518
+ const notes: string[] = [];
519
+ // The §8.7 classification ruling — the SAME judgment the read-back validator makes
520
+ // (non-declared keys are dropped, never a BLOCK): materialize drops them and books
521
+ // AT MOST ONE WARN on the carrier's notes (auditable, non-interrupting — replacing
522
+ // the retired "BLOCK + crash-resume + reopen" chain). The engine stays the carrier's
523
+ // single author; a child's stray key is surfaced, not obeyed.
524
+ const dropped = this.#handoffSchema.droppedKeys(face, draft);
525
+ if (dropped.length > 0) {
526
+ notes.push(
527
+ `dropped non-declared draft field(s): ${dropped.join(", ")} — engine-reserved, never written`,
528
+ );
529
+ }
530
+ // The per-face carrier — buildHandoff's typed overloads: the findings face REQUIRES
531
+ // its findings payload (the schema-required field — cli.test pins the review
532
+ // carrier's findings + status), the work face builds a findings-FREE typed carrier
533
+ // (the work writable subset declares no findings field — the materialized work
534
+ // carrier carries zero findings keys). `Record<string, unknown>` local: the round
535
+ // conclusion (status — a RoundStatus, wider than the carrier's declared union) and
536
+ // the engine's extended fields ride the caller's set below.
537
+ const carrier: Record<string, unknown> =
538
+ face === "findings"
539
+ ? ledger.buildHandoff("findings", {
540
+ artifacts: this.#canonicalArtifacts(frame, draft.artifacts, notes),
541
+ findings: this.#findingsList(draft.findings),
542
+ })
543
+ : ledger.buildHandoff("work", {
544
+ artifacts: this.#canonicalArtifacts(frame, draft.artifacts, notes),
545
+ });
546
+ // The work face ALONE persists the round conclusion — it is the child's own
547
+ // declared status (the schema enum pinned it to APPROVED | BLOCKED). The findings
548
+ // face holds NO status field: its conclusion is DERIVED at judgment time
549
+ // (`HandoffSchema.conclusionOf("findings", carrier)` → rollup(findings)), so the
550
+ // persisted findings carrier stays the pure declaration plane
551
+ // (findings/artifacts/notes) and a fix child's INPUT_FINDINGS carrier is
552
+ // status-free (the judgment face is perpendicular to the input face · D27).
553
+ const draftNotes = Array.isArray(draft.notes) ? [...(draft.notes as unknown[])] : [];
554
+ if (face === "work") {
555
+ carrier.status = status;
556
+ if (typeof draft.failure_category === "string")
557
+ carrier.failure_category = draft.failure_category;
558
+ // The evidence-contract override (work faces only — the evidence gate reads a
559
+ // work round's evidence file) rewrites the persisted conclusion to BLOCKED.
560
+ if (reason !== null) {
561
+ carrier.status = "BLOCKED";
562
+ carrier.failure_category = "evidence-contract";
563
+ draftNotes.push(reason);
564
+ }
565
+ }
566
+ if (notes.length > 0 || draftNotes.length > 0) carrier.notes = [...notes, ...draftNotes];
567
+ return carrier;
568
+ }
569
+
570
+ /** The carrier's artifacts map (find #5 — the engine self-derives, never trusts a
571
+ * child-reported path for the canonical slots): a declared PRESCRIBED slot
572
+ * (report/test_evidence) books the frame's canonical OUTPUT_* path — a
573
+ * free-named deviation is replaced and surfaced on the notes (the review scope
574
+ * axis reads them); the non-prescribed slots (a docs-fix's `doc`, child extras)
575
+ * pass verbatim. undefined when the draft declared no artifacts. */
576
+ #canonicalArtifacts(
577
+ frame: OpenFrame,
578
+ artifacts: unknown,
579
+ notes: string[],
580
+ ): Record<string, string> | undefined {
581
+ const declared = this.#stringMap(artifacts);
582
+ if (declared === undefined) return undefined;
583
+ const out: Record<string, string> = {};
584
+ for (const [key, value] of Object.entries(declared)) {
585
+ const canonical = this.#prescribedArtifact(frame, key);
586
+ if (canonical !== "" && value !== canonical) {
587
+ notes.push(
588
+ `artifact ${key}: declared path ${value} deviates from the prescribed ${canonical} — the canonical path is booked`,
589
+ );
590
+ out[key] = canonical;
591
+ } else {
592
+ out[key] = value;
593
+ }
594
+ }
595
+ return Object.keys(out).length > 0 ? out : undefined;
596
+ }
597
+
598
+ /** The prescribed path of one block-artifact slot — a slot the frame's family
599
+ * prescribes (report/test_evidence → the canonical OUTPUT_* name), "" for every
600
+ * other slot (the pure read input `brief` is never a write slot, and a docs-fix's
601
+ * `doc` is never prescribed — both pass verbatim). */
602
+ #prescribedArtifact(frame: OpenFrame, slot: string): string {
603
+ switch (slot) {
604
+ case "report":
605
+ return this.#outputOf(frame, "report");
606
+ case "test_evidence":
607
+ return this.#outputOf(frame, "evidence");
608
+ default:
609
+ return "";
610
+ }
611
+ }
612
+
613
+ /** The `## Handoff schema` section value — the mode's writable-subset fence
614
+ * (projection ①; byte-fixed per mode so the prompt's fixed prefix stays
615
+ * cache-friendly). The family's `schema` field selects the face (§3.6: work →
616
+ * carrier + evidence fence for the implement/fix modes; findings → the review /
617
+ * docs-fix fence only). */
618
+ #schemaText(frame: OpenFrame): string {
619
+ const op = this.#opOf(frame);
620
+ const face = this.#familyOf(op, frame.type).schema ?? "work";
621
+ const evidence = face === "work";
622
+ const prefix = evidence ? this.#evidencePrefix(frame) : "tasks";
623
+ return this.#handoffSchema.schemaText(face, evidence, prefix);
624
+ }
625
+
626
+ /** The evidence file's family prefix (§3.7 naming) — the task-family work rounds
627
+ * use the canonical `tasks-` prefix; the branch fix uses the `branch-` family
628
+ * prefix (never the misleading tasks- spine). */
629
+ #evidencePrefix(frame: OpenFrame): string {
630
+ return frame.type === "wave" ? "tasks" : "branch";
631
+ }
632
+
633
+ /** The op.type family record — the engine-config handoff namespace single truth
634
+ * (loud on an unknown family: never a second naming table). */
635
+ #familyOf(op: string, type: string): HandoffFamily {
636
+ const family = this.#config.engineConfig().handoffNamespace.families[`${op}.${type}`] as
637
+ | HandoffFamily
638
+ | undefined;
639
+ if (family === undefined) throw new Error(`unknown handoff family: ${op}.${type}`);
640
+ return family;
641
+ }
642
+
643
+ /** The artifacts field as a string-map (only string values land — non-string rows
644
+ * are dropped, never coerced). */
645
+ #stringMap(artifacts: unknown): Record<string, string> | undefined {
646
+ if (typeof artifacts !== "object" || artifacts === null || Array.isArray(artifacts))
647
+ return undefined;
648
+ const out: Record<string, string> = {};
649
+ for (const [key, value] of Object.entries(artifacts)) {
650
+ if (typeof value === "string") out[key] = value;
651
+ }
652
+ return Object.keys(out).length > 0 ? out : undefined;
653
+ }
654
+
655
+ /** The draft findings as a plain list (the materialized carrier keeps them
656
+ * verbatim; the schema validated their shape before this ran). */
657
+ #findingsList(findings: unknown): unknown[] {
658
+ return Array.isArray(findings) ? findings : [];
659
+ }
660
+
661
+ /** The same-command resume string — the crash record's `next`, mirroring the
662
+ * CLI's dispatchable form of this frame (re-run the same command per the BLOCKED
663
+ * `next:` to continue — the idempotent full mode re-run). */
664
+ #resumeOf(frame: OpenFrame): string {
665
+ const scene = this.#scene;
666
+ const plan = scene.planPath ?? "<plan>";
667
+ switch (frame.phase) {
668
+ case "implement":
669
+ return `cdd implement --tasks ${frame.params.tasks ?? ""} --plan ${plan}`;
670
+ case "branch-review":
671
+ // The branch re-review literal carries only the workspace-identity `--plan`
672
+ // — the review judges the live tree (the scope anchor BASE_BRANCH is
673
+ // engine-injected at dispatch), so no range rides the command.
674
+ return `cdd review --type branch --plan ${plan}`;
675
+ case "review":
676
+ if (frame.type === "spec") return `cdd review --type spec --spec ${this.#docOf(frame)}`;
677
+ if (frame.type === "plan") return `cdd review --type plan --plan ${this.#docOf(frame)}`;
678
+ return `cdd review --type wave --tasks ${frame.params.tasks ?? ""} --plan ${plan}`;
679
+ case "fix": {
680
+ const findings = scene.ledger.handoffPath("review", frame.type, frame.params);
681
+ const target =
682
+ frame.target.kind === "doc"
683
+ ? `--${frame.type === "spec" ? "spec" : "plan"} ${frame.target.doc}`
684
+ : // The branch fix carries no refs — the source findings ride the
685
+ // --findings handoff; the workspace-identity `--plan` still rides
686
+ // (the plan is the branch line's identity, zero orchestrator fallback).
687
+ frame.target.kind === "branch"
688
+ ? `--plan ${plan}`
689
+ : `--tasks ${frame.params.tasks ?? ""} --plan ${plan}`;
690
+ return `cdd fix --type ${frame.type} ${target} --findings ${findings}`;
691
+ }
692
+ }
693
+ }
694
+
695
+ /** The doc path of a doc-target frame (the `""` never lands — the reject paths
696
+ * only frame docs). */
697
+ #docOf(frame: OpenFrame): string {
698
+ return frame.target.kind === "doc" ? frame.target.doc : "";
699
+ }
700
+ }