@oscaner-skills/cdd-engine 1.0.0 → 3.0.0

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