@oscaner-skills/cdd-engine 2.0.0 → 3.0.1

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