@oscaner-skills/cdd-engine 3.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 (143) hide show
  1. package/{src-next/bin.ts → dist/bin.js} +18 -21
  2. package/dist/contract/declare.js +998 -0
  3. package/dist/contract/doc.js +565 -0
  4. package/dist/contract/frontmatter.js +209 -0
  5. package/dist/contract/home-extractors.js +379 -0
  6. package/dist/contract/invariants.js +1030 -0
  7. package/dist/contract/judge.js +109 -0
  8. package/dist/contract/lint.js +206 -0
  9. package/dist/contract/project.js +371 -0
  10. package/dist/contract/skill-anatomy.js +156 -0
  11. package/dist/contract/translate.js +85 -0
  12. package/dist/face/artifacts.js +189 -0
  13. package/dist/face/board-view.js +522 -0
  14. package/dist/face/capsule.js +141 -0
  15. package/dist/face/cli.js +891 -0
  16. package/dist/face/declare.js +241 -0
  17. package/dist/face/gate.js +158 -0
  18. package/dist/face/graph-view.js +66 -0
  19. package/dist/face/host.js +211 -0
  20. package/dist/face/lifecycle.js +603 -0
  21. package/dist/face/preview.js +136 -0
  22. package/dist/face/projection.js +259 -0
  23. package/dist/face/route-render.js +162 -0
  24. package/dist/face/termination.js +482 -0
  25. package/dist/face/words.js +220 -0
  26. package/{src-next/infra/config.ts → dist/infra/config.js} +19 -24
  27. package/{src-next/infra/doc-roots.ts → dist/infra/doc-roots.js} +3 -13
  28. package/dist/infra/git.js +37 -0
  29. package/dist/infra/process.js +22 -0
  30. package/{src-next/infra/root.ts → dist/infra/root.js} +25 -36
  31. package/dist/infra/runtime.js +85 -0
  32. package/dist/infra/workspace.js +276 -0
  33. package/dist/render/brief.js +82 -0
  34. package/dist/render/issue-body.js +129 -0
  35. package/dist/render/skeleton.js +434 -0
  36. package/dist/render/templates.js +520 -0
  37. package/dist/session/faces.js +38 -0
  38. package/dist/session/graph.js +309 -0
  39. package/dist/session/handoff-schema.js +295 -0
  40. package/dist/session/ledger.js +762 -0
  41. package/dist/session/next.js +211 -0
  42. package/dist/session/preflight.js +194 -0
  43. package/dist/session/round-naming.js +73 -0
  44. package/dist/session/run.js +441 -0
  45. package/dist/session/state.js +8 -0
  46. package/dist/session/wave.js +92 -0
  47. package/package.json +5 -5
  48. package/src-next/__tests__/bin.test.ts +0 -128
  49. package/src-next/__tests__/dead-decl.guard.test.ts +0 -39
  50. package/src-next/__tests__/floor.guard.test.ts +0 -69
  51. package/src-next/__tests__/issue-body.guard.test.ts +0 -66
  52. package/src-next/__tests__/phase-suffix.guard.test.ts +0 -72
  53. package/src-next/__tests__/smoke.integration.test.ts +0 -185
  54. package/src-next/__tests__/support/strip-comments.ts +0 -99
  55. package/src-next/__tests__/zero-dep.test.ts +0 -94
  56. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +0 -256
  57. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +0 -165
  58. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +0 -190
  59. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +0 -106
  60. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +0 -240
  61. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +0 -165
  62. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +0 -190
  63. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +0 -100
  64. package/src-next/contract/__tests__/declare.test.ts +0 -481
  65. package/src-next/contract/__tests__/doc.test.ts +0 -527
  66. package/src-next/contract/__tests__/dockey.guard.test.ts +0 -58
  67. package/src-next/contract/__tests__/edge-conditions.guard.test.ts +0 -81
  68. package/src-next/contract/__tests__/frontmatter.test.ts +0 -164
  69. package/src-next/contract/__tests__/judge.test.ts +0 -1111
  70. package/src-next/contract/__tests__/lint.test.ts +0 -324
  71. package/src-next/contract/__tests__/project.test.ts +0 -460
  72. package/src-next/contract/__tests__/structure-pin.test.ts +0 -186
  73. package/src-next/contract/__tests__/translate.test.ts +0 -96
  74. package/src-next/contract/declare.ts +0 -1071
  75. package/src-next/contract/doc.ts +0 -816
  76. package/src-next/contract/frontmatter.ts +0 -233
  77. package/src-next/contract/home-extractors.ts +0 -397
  78. package/src-next/contract/invariants.ts +0 -1413
  79. package/src-next/contract/judge.ts +0 -151
  80. package/src-next/contract/lint.ts +0 -239
  81. package/src-next/contract/project.ts +0 -656
  82. package/src-next/contract/skill-anatomy.ts +0 -301
  83. package/src-next/contract/translate.ts +0 -113
  84. package/src-next/face/__tests__/board-view.test.ts +0 -1151
  85. package/src-next/face/__tests__/capsule.test.ts +0 -300
  86. package/src-next/face/__tests__/channel-closure.guard.test.ts +0 -129
  87. package/src-next/face/__tests__/cli.test.ts +0 -4897
  88. package/src-next/face/__tests__/face.test.ts +0 -289
  89. package/src-next/face/__tests__/graph-view.test.ts +0 -61
  90. package/src-next/face/__tests__/host.test.ts +0 -24
  91. package/src-next/face/__tests__/install-rows.guard.test.ts +0 -58
  92. package/src-next/face/__tests__/negation.ts +0 -6
  93. package/src-next/face/__tests__/preview.test.ts +0 -374
  94. package/src-next/face/__tests__/projection.test.ts +0 -303
  95. package/src-next/face/__tests__/repo-root.guard.test.ts +0 -120
  96. package/src-next/face/__tests__/termination.test.ts +0 -650
  97. package/src-next/face/__tests__/words.guard.test.ts +0 -93
  98. package/src-next/face/artifacts.ts +0 -248
  99. package/src-next/face/board-view.ts +0 -652
  100. package/src-next/face/capsule.ts +0 -163
  101. package/src-next/face/cli.ts +0 -1028
  102. package/src-next/face/declare.ts +0 -323
  103. package/src-next/face/gate.ts +0 -171
  104. package/src-next/face/graph-view.ts +0 -74
  105. package/src-next/face/host.ts +0 -302
  106. package/src-next/face/lifecycle.ts +0 -725
  107. package/src-next/face/preview.ts +0 -151
  108. package/src-next/face/projection.ts +0 -285
  109. package/src-next/face/route-render.ts +0 -185
  110. package/src-next/face/termination.ts +0 -573
  111. package/src-next/face/words.ts +0 -314
  112. package/src-next/infra/__tests__/infra.test.ts +0 -333
  113. package/src-next/infra/__tests__/root.test.ts +0 -56
  114. package/src-next/infra/git.ts +0 -39
  115. package/src-next/infra/process.ts +0 -34
  116. package/src-next/infra/runtime.ts +0 -132
  117. package/src-next/infra/workspace.ts +0 -322
  118. package/src-next/render/__tests__/render.test.ts +0 -550
  119. package/src-next/render/__tests__/skeleton.test.ts +0 -684
  120. package/src-next/render/brief.ts +0 -121
  121. package/src-next/render/issue-body.ts +0 -162
  122. package/src-next/render/skeleton.ts +0 -502
  123. package/src-next/render/templates.ts +0 -645
  124. package/src-next/session/__tests__/graph.test.ts +0 -277
  125. package/src-next/session/__tests__/handoff-plane.guard.test.ts +0 -48
  126. package/src-next/session/__tests__/handoff-schema.test.ts +0 -310
  127. package/src-next/session/__tests__/ledger.test.ts +0 -745
  128. package/src-next/session/__tests__/next.test.ts +0 -460
  129. package/src-next/session/__tests__/preflight.test.ts +0 -545
  130. package/src-next/session/__tests__/round-naming.test.ts +0 -142
  131. package/src-next/session/__tests__/run.test.ts +0 -1026
  132. package/src-next/session/__tests__/wave-line-phase.guard.test.ts +0 -49
  133. package/src-next/session/__tests__/wave.test.ts +0 -476
  134. package/src-next/session/faces.ts +0 -110
  135. package/src-next/session/graph.ts +0 -411
  136. package/src-next/session/handoff-schema.ts +0 -373
  137. package/src-next/session/ledger.ts +0 -1076
  138. package/src-next/session/next.ts +0 -293
  139. package/src-next/session/preflight.ts +0 -271
  140. package/src-next/session/round-naming.ts +0 -84
  141. package/src-next/session/run.ts +0 -610
  142. package/src-next/session/state.ts +0 -30
  143. package/src-next/session/wave.ts +0 -139
@@ -0,0 +1,891 @@
1
+ // packages/cdd-engine/src-next/face/cli.ts
2
+ // T11 + T8 — the command face + composition root (design spec §3.3: the cdd CLI
3
+ // command surface — implement / review / fix / schema / issue / base / board — is
4
+ // kept as a steady word face; T20 converges the base command face to `base` and T5
5
+ // adds the board observability command — the seven-command surface). This module is
6
+ // the new tree's composition root: the
7
+ // `Cli.create` static factory — the class face is the entry, the module carries zero
8
+ // bare functions (the composition root's deliberate class form) — wires the contract /
9
+ // session / face objects into the ONE CLI the bin thin entry boots. Task 3 (P1)
10
+ // reorganized the face into one boundary per responsibility — the CLI declaration
11
+ // single surface (face/declare.ts, §2.4 — the seven subcommand rows + the argv
12
+ // channel), the declaration projection (face/projection.ts — the CommandTreeBuilder
13
+ // whose commander program OWNS the parse + help + validation pipeline), and the run
14
+ // face; the typed argv parse channel (face/argv.ts) was deleted at T6 — the parse
15
+ // handover to commander is total, and the domain-run error face's usage is
16
+ // commander's own byte.
17
+ //
18
+ // Task 8 (the split contract §6.2) slimmed this module to the COMPOSITION RESPONSIBILITY:
19
+ // wire + exit + parse, plus the work/pure command run bodies that ASSEMBLE the scene.
20
+ // The domain faces live in their own files and are composed through here —
21
+ // face/lifecycle.ts (CliLifecycle — the dispatch + readback + round-context plane:
22
+ // implement/review/fix dispatch, the read-back reconstruct, the round-context fact
23
+ // assembly; the pre-split HarnessDispatch member renamed, re-exported unchanged
24
+ // below), face/gate.ts (CliGate — the target/line gate family: the readiness
25
+ // judgments + the doc line's revision-aware BLOCK/pending-fix faces), face/artifacts.ts
26
+ // (CliArtifacts — the pure-command domain: schema get / issue / base runs). The root
27
+ // Cli holds the three instances and composes through them via its .action thin shells
28
+ // (zero bare functions; the seams it still assembles — the lifecycle dispatch seam's
29
+ // production default construction — stay here).
30
+ //
31
+ // · runArgv — parse through the commander program (face/projection.ts), dispatch
32
+ // each parsed command through an .action thin shell (the parseArg-normalized
33
+ // values ride into the domain run as its consumed values, zero rewriting) and
34
+ // normalize the exit-code surface from the thrown CommanderError (0 = help/OK ·
35
+ // 2 = usage (incl. the preAction conditional-required) · 1 = run failure).
36
+ // · the .action thin shells — the work commands (implement / review / fix)
37
+ // assemble the lifecycle (session/run), the capsule + words (face), the ledger
38
+ // (session/ledger) and the task graph (contract parse) and advance the
39
+ // requested phase; schema / issue / base run their pure artifact surfaces
40
+ // through the same assembled objects (the pure runs + the readiness gates
41
+ // delegate to the split faces above — the root orchestrates, never re-types).
42
+ // Module-level exports are types / constant data / classes — zero behavior-carrying
43
+ // bare functions (the composition root is the Cli class's static create factory).
44
+ import { existsSync, readFileSync } from "node:fs";
45
+ import path from "node:path";
46
+ import process from "node:process";
47
+ import { CommanderError } from "commander";
48
+ import { declaredRegistries } from "../contract/declare.js";
49
+ import { PlanDocType } from "../contract/doc.js";
50
+ import { FrontMatterExtractor } from "../contract/frontmatter.js";
51
+ import { FileExistenceInvariant } from "../contract/invariants.js";
52
+ import { Contract } from "../contract/judge.js";
53
+ import { Projector } from "../contract/project.js";
54
+ import { Translator } from "../contract/translate.js";
55
+ import { ConfigLoader } from "../infra/config.js";
56
+ import { GitClient } from "../infra/git.js";
57
+ import { RepoRoot } from "../infra/root.js";
58
+ import { Workspace, WorkspaceRoot } from "../infra/workspace.js";
59
+ import { BriefRenderer } from "../render/brief.js";
60
+ import { IssueBodyRenderer } from "../render/issue-body.js";
61
+ import { TemplateAssembler } from "../render/templates.js";
62
+ import { targetFaces } from "../session/faces.js";
63
+ import { TaskGraph } from "../session/graph.js";
64
+ import { Ledger } from "../session/ledger.js";
65
+ import { NextStepRouter } from "../session/next.js";
66
+ import { PreFlight } from "../session/preflight.js";
67
+ import { EMPTY_RUN_STATE, Lifecycle } from "../session/run.js";
68
+ import { CliArtifacts } from "./artifacts.js";
69
+ import { BoardView } from "./board-view.js";
70
+ import { Capsule } from "./capsule.js";
71
+ import { ARGV_CHANNEL } from "./declare.js";
72
+ import { CliGate } from "./gate.js";
73
+ import { GraphView } from "./graph-view.js";
74
+ import { HostDetect } from "./host.js";
75
+ import { CliLifecycle } from "./lifecycle.js";
76
+ import { Preview } from "./preview.js";
77
+ import { CommandTreeBuilder } from "./projection.js";
78
+ import { Terminator } from "./termination.js";
79
+ import { Words } from "./words.js";
80
+ export { CliLifecycle as HarnessDispatch } from "./lifecycle.js";
81
+ /**
82
+ * The Cli — the command face's parse/run surface over the assembled object graph.
83
+ * runArgv() parses through the commander program and rejects unknown flags (the
84
+ * unknown-flag semantics); run() dispatches to the command's run body — the work verbs
85
+ * compose the lifecycle/capsule/ledger/graph and advance the requested phase, the
86
+ * pure verbs run their artifact surfaces through the same assembled objects.
87
+ */
88
+ export class Cli {
89
+ #io;
90
+ #config;
91
+ #projector;
92
+ #words;
93
+ #git;
94
+ #sync;
95
+ #dryRun;
96
+ #dispatch;
97
+ #template;
98
+ #brief;
99
+ #stdinRead;
100
+ #issue;
101
+ #translator;
102
+ /** The pre-flight board face (the blocked-dispatch wave hint). */
103
+ #graphView;
104
+ /** The lifecycle pre-flight seam (P4.1 T1) — the single dispatch gate the work
105
+ * commands consult before ANY child dispatch (tree-clean → graph → wave →
106
+ * doc-contract; the CLI orchestrates the call + the render, never a re-type). */
107
+ #preflight;
108
+ /** The contract coordinator — the doc-contract judgment face the pre-flight's
109
+ * doc gate reads (the single interpreter entry; spec §12 · D34 retired the
110
+ * filename→type derivation — the doc type is now the declared header fact read
111
+ * through BoardView.readDocType). */
112
+ #contract;
113
+ /** The commander command tree — the declaration projection (CommandTreeBuilder,
114
+ * face/projection.ts): the domain-run error face's usage byte is the command
115
+ * node's commander-native helpInformation() first line (the self-built usage
116
+ * corpus is retired; the T3 rebuild closes the parse face onto the same
117
+ * program). */
118
+ #program;
119
+ /** The target/line gate family (T8 — the split contract's gate face,
120
+ * face/gate.ts): the work commands' readiness judgments (line phase / review
121
+ * convergence BLOCKs) + the group/line helpers. */
122
+ #gate;
123
+ /** The pure-command domain (T8 — the split contract's artifacts face,
124
+ * face/artifacts.ts): the schema/issue/base run bodies. */
125
+ #artifacts;
126
+ constructor(opts = {}) {
127
+ this.#io = opts.io ?? {
128
+ stdout: (t) => process.stdout.write(t),
129
+ stderr: (t) => process.stderr.write(t),
130
+ };
131
+ this.#config = opts.config ?? new ConfigLoader();
132
+ this.#words = opts.words ?? new Words();
133
+ this.#projector = opts.projector ?? new Projector(declaredRegistries);
134
+ this.#program = new CommandTreeBuilder().program;
135
+ this.#wireTreeOutput(this.#program);
136
+ this.#wireActions();
137
+ this.#git = opts.git ?? new GitClient();
138
+ this.#sync = opts.sync ?? new Terminator();
139
+ this.#dryRun = opts.dryRun ?? false;
140
+ this.#dispatch = opts.dispatch ?? null;
141
+ this.#template = opts.template ?? new TemplateAssembler();
142
+ this.#brief = opts.brief ?? new BriefRenderer();
143
+ this.#stdinRead = opts.stdinRead ?? (() => readFileSync(0, "utf8"));
144
+ this.#translator = opts.translator ?? new Translator(this.#words);
145
+ this.#issue = new IssueBodyRenderer(this.#words, this.#translator);
146
+ this.#graphView = new GraphView();
147
+ this.#contract = new Contract();
148
+ this.#preflight =
149
+ opts.preflight ??
150
+ new PreFlight({
151
+ git: this.#git,
152
+ contract: this.#contract,
153
+ words: this.#words,
154
+ });
155
+ this.#gate = new CliGate({ brief: this.#brief });
156
+ this.#artifacts = new CliArtifacts({
157
+ io: this.#io,
158
+ projector: this.#projector,
159
+ issue: this.#issue,
160
+ stdinRead: this.#stdinRead,
161
+ usage: (node, message) => this.#usage(node, message),
162
+ });
163
+ }
164
+ // ---------------------------------------------------------------------------
165
+ // the commander parse pipeline — the composition root parses through the
166
+ // projection's program (T3): the .action thin shells (below) dispatch the parsed
167
+ // command to its domain run; the exit-code discriminator maps the CommanderError
168
+ // surface (§3.1 — probe-verified v0.9): help exit 0 / helpDisplayed → 0 · help
169
+ // non-zero (bare run · missing subcommand · help <bogus>) + usage-class codes →
170
+ // 2 · an unexpected throw → 1.
171
+ // ---------------------------------------------------------------------------
172
+ /** runArgv(argv) — the CLI face: parse through the commander program, return the
173
+ * thin shell's domain-run exit code (0 = success/help · 2 = usage · 1 = run
174
+ * failure — the steady exit-code table). Every commander/normal usage error
175
+ * discriminates on the thrown CommanderError: the help display faces write
176
+ * themselves through the node's configured output (the CLI never re-types a
177
+ * help byte), the parse/usage rejections carry commander's own "error: " line
178
+ * (never double-written), and the preAction conditional-required rejection (the
179
+ * one commander throws unwritten) is surfaced by the run face. */
180
+ async runArgv(raw) {
181
+ try {
182
+ this.#exitCode = 0;
183
+ await this.#program.parseAsync([...raw], { from: "user" });
184
+ return this.#exitCode;
185
+ }
186
+ catch (err) {
187
+ return this.#normalizeExit(err);
188
+ }
189
+ }
190
+ /** The exit-code discriminator — the CommanderError surface (§3.1): the explicit
191
+ * help faces exit 0, the missing-command/missing-subcommand faces ride the help
192
+ * code's non-zero exit → 2, the usage-class codes (unknown option/command ·
193
+ * invalid argument (incl. the preAction conditional-required) · excess args ·
194
+ * missing required) → 2, an unexpected error → 1. */
195
+ #normalizeExit(err) {
196
+ if (err instanceof CommanderError) {
197
+ if (err.code === "commander.help")
198
+ return err.exitCode === 0 ? 0 : 2;
199
+ if (err.code === "commander.helpDisplayed")
200
+ return 0;
201
+ // usage-class — commander's own error() already wrote its "error: ..." line
202
+ // (the parseArg/unknown surfaces); the preAction hook's InvalidArgumentError
203
+ // and the run bodies' #usage throw are both thrown unwritten — the run face
204
+ // surfaces them once.
205
+ if (!err.message.startsWith("error: "))
206
+ this.#io.stderr(`error: ${err.message}\n`);
207
+ return 2;
208
+ }
209
+ this.#io.stderr(`cdd: ${err instanceof Error ? err.message : String(err)}\n`);
210
+ return 1;
211
+ }
212
+ /** The domain-run usage error — a usage rejection raised inside a run body:
213
+ * commander's OWN CommanderError (never a second error type — the retired
214
+ * parse-channel error class is deleted at T6), which the normalizeExit
215
+ * discriminator above surfaces with the native "error:" byte and exit 2 (§3.1).
216
+ * The usage byte is the owning command node's commander-native
217
+ * helpInformation() first line (the declaration's help face — the self-built
218
+ * usage corpus never returned here); the throw carries only the message. */
219
+ #usage(node, message) {
220
+ const usageLine = node.helpInformation().split("\n")[0];
221
+ if (usageLine !== "")
222
+ this.#io.stderr(`${usageLine}\n`);
223
+ throw new CommanderError(2, "cdd.usage-error", message);
224
+ }
225
+ /** The per-invocation exit code the thin shells capture (commander discards the
226
+ * action's return — parseAsync resolves with the program node, so the shell
227
+ * writes the domain-run's code here and runArgv reads it back). */
228
+ #exitCode = 0;
229
+ /** The .action thin shells — the parsed command → its domain run: build the
230
+ * run input from commander's parsed opts (parseArg-normalized values pass
231
+ * through as the domain's consumed values — no rewrite, §3.3) and dispatch to
232
+ * the domain run, capturing the exit code. */
233
+ #wireActions() {
234
+ const commandNode = (name) => this.#program.commands.find((c) => c.name() === name);
235
+ const leafNode = (parent, name) => commandNode(parent).commands.find((c) => c.name() === name);
236
+ // the work verbs — implement / review / fix compose the domain run
237
+ for (const verb of ["implement", "review", "fix"]) {
238
+ commandNode(verb).action(async (_opts, command) => {
239
+ this.#exitCode = await this.#runWork(verb, command, this.#runInput(null, command));
240
+ });
241
+ }
242
+ // the pure commands' leaves — schema get · base set/get · issue render
243
+ leafNode("schema", "get").action(async (_type, _target, _opts, command) => {
244
+ this.#exitCode = await this.#runSchema(command, this.#runInput("get", command));
245
+ });
246
+ leafNode("base", "set").action(async (_opts, command) => {
247
+ this.#exitCode = await this.#runBase(command, this.#runInput("set", command));
248
+ });
249
+ leafNode("base", "get").action(async (_opts, command) => {
250
+ this.#exitCode = await this.#runBase(command, this.#runInput("get", command));
251
+ });
252
+ leafNode("issue", "render").action(async (_opts, command) => {
253
+ this.#assertDryRunScope(command, this.#dryRunOf(command));
254
+ this.#exitCode = this.#artifacts.runIssue();
255
+ });
256
+ // the board observability command — a pure read (no preflight gate)
257
+ commandNode("board").action(async (_slug, _opts, command) => {
258
+ this.#exitCode = await this.#runBoard(command, this.#runInput(null, command));
259
+ });
260
+ }
261
+ /** `cdd board <slug>` — the slug progress board (spec §5 · §2.2): a PURE READ —
262
+ * zero preflight gate, zero tree writes, zero ledger writes, zero child dispatch.
263
+ * The slug (the one positional) resolves the repo root, assembles the node tree
264
+ * and renders the phase/program board + the `next:` derivation to stdout. A
265
+ * missing slug is a usage error (exit 2, commander's own byte); a slug matching
266
+ * nothing on disk renders the not-found face and exits 2; a present doc line
267
+ * carrying no `doc-type:` key renders its BLOCKED marker and exits 2
268
+ * (spec §12 · D34). The host is detected once for the pipeline-entry ref render
269
+ * (REFS[ref][host], the same judgment the capsule injects — never hard-coded). */
270
+ async #runBoard(node, parsed) {
271
+ this.#assertDryRunScope(node, parsed.dryRun);
272
+ const slug = parsed.positionals[0];
273
+ if (slug === undefined)
274
+ this.#usage(node, "cdd board: missing <slug>");
275
+ const repoRoot = await this.#rootOf();
276
+ if (repoRoot === null)
277
+ return 1;
278
+ if (!BoardView.hasNode(slug, repoRoot)) {
279
+ this.#io.stderr(`cdd board: no docs match slug ${slug}\n`);
280
+ return 2;
281
+ }
282
+ const host = HostDetect.detect(process.env);
283
+ const board = BoardView.render(slug, repoRoot, this.#words, host, ARGV_CHANNEL);
284
+ for (const line of board.lines)
285
+ this.#io.stdout(`${line}\n`);
286
+ return board.exitCode;
287
+ }
288
+ /** The thin shell's run input — commander's parsed opts mapped to the domain
289
+ * run's consumption face (the parseArg-normalized values ride through verbatim:
290
+ * int-list → the comma string · enum → the value · sha → the short form · the
291
+ * schema <type> → the parseTypeKey normalization), plus the positionals
292
+ * (processedArgs) and the program-scope dry-run (optsWithGlobals — the flag
293
+ * lives on the program node, merged here). The args read GLOBALS too: a flag
294
+ * declared on the parent command (schema's --plan) is consumed by that node —
295
+ * the leaf's own opts would miss it. */
296
+ #runInput(leaf, command) {
297
+ const globals = command.optsWithGlobals();
298
+ const args = {};
299
+ for (const [key, value] of Object.entries(globals)) {
300
+ if (value === undefined)
301
+ continue;
302
+ args[key] = typeof value === "boolean" ? (value ? "true" : "false") : String(value);
303
+ }
304
+ return {
305
+ leaf,
306
+ args,
307
+ // The path-typed values land empty — the funnel (`#funnel`) is the ONE
308
+ // normalization site that fills them with the branded repoRoot-relative form.
309
+ paths: { plan: null, spec: null, reviews: null },
310
+ positionals: command.processedArgs,
311
+ dryRun: this.#dryRunOf(command),
312
+ };
313
+ }
314
+ /** The invocation's `--dry-run` scope — the constructor flag OR the program-scope
315
+ * flag (the flag is declared on the program node, so a leaf's own opts would miss
316
+ * it; `optsWithGlobals` merges the parent chain). The ONE derivation the run input
317
+ * and the scope guard read — never a second copy of the merge rule. */
318
+ #dryRunOf(command) {
319
+ const globals = command.optsWithGlobals();
320
+ return this.#dryRun || globals.dryRun === true;
321
+ }
322
+ /** The `--dry-run` scope guard (P11 T5 · §3.5) — the preview semantics belong to
323
+ * the three work verbs alone. A pure command carrying the program flag is a usage
324
+ * rejection (exit 2), never a silently ignored flag: a no-op flag the consumer has
325
+ * to remember to skip is a mind-share defect, not a convenience. The usage byte is
326
+ * the owning node's commander-native usage line (the same `#usage` face every run
327
+ * body's rejection rides). */
328
+ #assertDryRunScope(node, dryRun) {
329
+ if (!dryRun)
330
+ return;
331
+ this.#usage(node, "--dry-run previews the next dispatch step and its expected artifacts — it applies to implement / review / fix only");
332
+ }
333
+ /** Configure every node's output into the injected io (commander writes its
334
+ * help/error bytes through the node that produced them — a subcommand's help
335
+ * uses the subcommand's own output configuration, so the whole tree must be
336
+ * wired, never just the program). */
337
+ #wireTreeOutput(node) {
338
+ node.configureOutput({
339
+ writeOut: (text) => this.#io.stdout(text),
340
+ writeErr: (text) => this.#io.stderr(text),
341
+ });
342
+ for (const child of node.commands)
343
+ this.#wireTreeOutput(child);
344
+ }
345
+ // ---------------------------------------------------------------------------
346
+ // the work commands — lifecycle/capsule/ledger composition + the phase advance
347
+ // ---------------------------------------------------------------------------
348
+ /** One work command's run — assemble the scene, advance the requested phase (the
349
+ * lifecycle's single dispatch step per frame), render the capsule lines. */
350
+ async #runWork(verb, node, raw) {
351
+ const type = (raw.args.type ?? "wave");
352
+ if (type === "wave" && raw.args.tasks === undefined) {
353
+ this.#usage(node, `cdd ${verb} --type wave: missing required --tasks <n|n,n,…>`);
354
+ }
355
+ // The repo root (the ONE conversion point, T2) + the input funnel (T3 §2.3) run
356
+ // FIRST — before the scene or any downstream face reads a path arg, so the whole
357
+ // run (scene + ledger + dispatch `--reviews`) speaks ONE normalized argv shape.
358
+ const repoRoot = await this.#rootOf();
359
+ if (repoRoot === null)
360
+ return 1;
361
+ const root = new RepoRoot(repoRoot);
362
+ const parsed = this.#funnel(root, raw);
363
+ const scene = await this.#sceneOf(verb, type, node, root, parsed);
364
+ if (scene === null)
365
+ return 1;
366
+ // THE pre-flight seam (P4.1 T1 · design §1): the single dispatch gate —
367
+ // tree-clean → graph → wave → doc-contract — ONE call, the whole sequence
368
+ // lives in the seam (session/preflight.ts), the CLI only orchestrates the call
369
+ // + the verdict render (zero re-implemented gate here). A refused verdict
370
+ // returns before any brief/lifecycle: no child dispatch ever runs. The
371
+ // dirty-tree / doc-contract refusals ride the CDD_BLOCKED channel; the
372
+ // graph / wave refusals keep the pre-existing refusal face. The doc-face read
373
+ // path is the repoRoot-relative branded `RepoPath` (T4 §2.2 — a bare `string`
374
+ // never reaches the read faces `BoardView.readDocType`/`PreFlightDoc.path`; the
375
+ // CLI feeds the funnel-shaped relative value, each read face erasing to the
376
+ // absolute syscall form through its OWN `RepoRoot`). Both branches yield the
377
+ // brand through the ONE conversion entry (`relativize` of the doc path; the
378
+ // empty path relativizes to the empty `RepoPath`) — no cast (F3).
379
+ const docRel = root.relativize(scene.target !== null && (scene.target.kind === "plan" || scene.target.kind === "spec")
380
+ ? scene.target.doc
381
+ : "");
382
+ const preflight = await this.#preflight.vet({
383
+ verb: verb,
384
+ type,
385
+ repoRoot: scene.workspace.root.repoRoot,
386
+ planText: scene.planText,
387
+ tasks: type === "wave" ? new Set(this.#gate.tasksOf(parsed)) : null,
388
+ ledger: scene.ledger,
389
+ doc: type === "spec" || type === "plan"
390
+ ? {
391
+ // The ONE declaration reading face (spec §12 · D34) — both the spec and
392
+ // the plan dispatch read the doc's front-matter `doc-type:` key;
393
+ // a key-less doc reads null and the seam BLOCKs (zero command-type
394
+ // carve-out, zero filename-suffix fallback).
395
+ docKey: BoardView.readDocType(root, docRel),
396
+ path: docRel,
397
+ }
398
+ : null,
399
+ });
400
+ if (!preflight.ok) {
401
+ this.#renderPreflightBlocked(verb, preflight, scene);
402
+ return 1;
403
+ }
404
+ // The real run's first write point (P11 · §4.2): the workspace — and the
405
+ // namespace's `.gitignore` keep-out marker — is built HERE, after the
406
+ // pre-flight verdict and before the brief render / the child dispatch, for
407
+ // EVERY face (wave / spec / plan / branch). Scene assembly no longer
408
+ // pre-creates it, so a read-only command leaves `.kairos/` absent while a
409
+ // real dispatch always lands in an existing workspace (the child's
410
+ // OUTPUT_REPORT / OUTPUT_HANDOFF targets, and the keep-out marker published
411
+ // before the child can dirty the tree). `Workspace.writeJson` keeps its own
412
+ // internal ensure; `CliGate#renderBrief` no longer ensures. The `--dry-run`
413
+ // preview never reaches it — the preview path returns before any write
414
+ // (P11 T5 · §3.2: a preview is a pure read).
415
+ if (!parsed.dryRun)
416
+ scene.workspace.ensure();
417
+ // The unconditional extract (§4.1): every wave-face dispatch re-renders the
418
+ // brief from the CURRENT plan text — implement, review and fix alike (a
419
+ // mid-run plan amendment reflects into the next dispatch; no "exists → leave
420
+ // it" reuse). The doc/branch faces carry no wave brief (planText is null there).
421
+ // The preview skips it — the brief is a WRITE (`Workspace#writeText`), and the
422
+ // preview names the same path through RoundNaming instead of rendering it.
423
+ if (!parsed.dryRun && type === "wave" && scene.planText !== null)
424
+ scene.briefPath = this.#gate.renderBrief(scene, parsed);
425
+ const expected = verb === "implement" ? "implement" : verb === "fix" ? "fix" : scene.face.product.reviewLead;
426
+ // The per-invocation batch cursor: the in-memory done set mirrors the on-disk
427
+ // ledger's closed waves (the C5 closure single face) — NOT a "every non-group
428
+ // task pre-done" shortcut. The old shortcut made the frontier yield exactly the
429
+ // requested group, but it also emptied readyBatch() at every closure: a mid-run
430
+ // wave's fix rendered `next: done` instead of the next wave (the {16,22,24} →
431
+ // {25,26,27} bug — the closure routing judged a per-invocation cursor, not the
432
+ // plan's real remaining frontier). The ledger mirror keeps the progress face
433
+ // cross-invocation: the dispatched group's own closure marks in #markTerminal
434
+ // as the loop advances, and the next wave surfaces from the live closed set.
435
+ let group = null;
436
+ if (type === "wave") {
437
+ group = new Set(this.#gate.tasksOf(parsed));
438
+ const planIds = scene.planText !== null
439
+ ? new PlanDocType("plan")
440
+ .parse(scene.planText.split("\n"))
441
+ .taskBlocks.map((block) => block.id)
442
+ : [];
443
+ for (const id of group) {
444
+ if (!planIds.includes(id)) {
445
+ this.#usage(node, `cdd ${verb}: task ${id} not found in the plan`);
446
+ }
447
+ }
448
+ for (const id of scene.ledger.closedWaves())
449
+ scene.state.markDone(id);
450
+ }
451
+ const statuses = [];
452
+ const dispatch = this.#dispatchOf(scene, parsed);
453
+ const run = new Lifecycle({
454
+ face: scene.face,
455
+ state: scene.state,
456
+ ledger: scene.ledger,
457
+ router: scene.router,
458
+ // The dispatch-entry pre-flight wiring (P4.1 T1): the single seam verdict the
459
+ // work command computed rides the lifecycle's gate — a refused frame is
460
+ // structurally never passed to the child (the lifecycle's hard "child zero-dispatch"
461
+ // guarantee; the CLI already returned above when the seam refused).
462
+ preflight: { gate: () => (preflight.ok ? null : preflight) },
463
+ dispatch: async (frame) => {
464
+ const outcome = await dispatch(frame);
465
+ statuses.push(outcome.status ?? null);
466
+ return outcome;
467
+ },
468
+ target: scene.target ?? undefined,
469
+ capsule: new Capsule(this.#words, ARGV_CHANNEL, HostDetect.detect(process.env), scene.workspace.root.basis),
470
+ planPath: scene.planPath,
471
+ });
472
+ // The requested-phase gate — the line faces (branch/spec/plan) keep the
473
+ // line-phase readiness check; the task face needs no second gate (the WaveGate's
474
+ // wrong-phase verdict above IS the phase authority for the requested wave).
475
+ if (group === null) {
476
+ const { phase: open, verdict, reviewed } = this.#gate.lineGate(scene);
477
+ if (open !== expected) {
478
+ const pendingBlock = verdict === "pending-fix" ? this.#gate.pendingFixBlock(scene, reviewed) : null;
479
+ const docBlock = open === null ? this.#gate.docLineBlock(scene, reviewed) : null;
480
+ this.#io.stderr(`cdd ${verb}: cannot dispatch a ${expected} round — ${pendingBlock ?? docBlock ?? (open === null ? "the line holds no open round" : `the next round is ${open}${this.#phaseHint(open)}`)}\n`);
481
+ return 1;
482
+ }
483
+ }
484
+ // Advance the requested phase across the wave (one dispatch per frame — the
485
+ // lifecycle's "one dispatch, one advance" step), keeping only the LAST step's
486
+ // capsule for the invocation's single stdout face (the per-step intermediate
487
+ // next-wave lines stay in the router, never on the CLI face). The loop PEEKS
488
+ // before every advance: advance() dispatches on entry, so an expected-phase
489
+ // mismatch must be judged against the next frame BEFORE it spends the round —
490
+ // the {16,22,24} bug's lookahead-after-dispatch consumed the next wave's round
491
+ // in the same invocation (implement 1 silently closed wave 1's review round).
492
+ let dispatched = 0;
493
+ let latest = [];
494
+ let lastStatus = null;
495
+ for (;;) {
496
+ const frame = run.peekNext();
497
+ if (frame === null)
498
+ break;
499
+ const waveTasks = frame.target.kind === "wave" ? frame.target.tasks : null;
500
+ const mismatch = frame.phase !== expected ||
501
+ (group !== null && (waveTasks === null || !waveTasks.every((id) => group.has(id))));
502
+ if (mismatch) {
503
+ if (dispatched === 0) {
504
+ this.#io.stderr(`cdd ${verb}: cannot dispatch a ${expected} round — the next round is ${frame.phase}${waveTasks !== null ? ` for wave ${waveTasks.join(",")}` : ""}${this.#phaseHint(frame.phase)}\n`);
505
+ return 1;
506
+ }
507
+ break;
508
+ }
509
+ // The `--dry-run` preview (P11 T5 · §3.3) — the SAME frame the real run would
510
+ // dispatch, rendered as the five-row forecast instead of dispatched: the
511
+ // frontier read above is the preview's single step source (zero second
512
+ // derivation), and the early return means no write point below ever runs
513
+ // (`renderBrief` skipped above, `#bookkeep`/`#reject` never reached).
514
+ if (parsed.dryRun) {
515
+ for (const line of new Preview({ scene }).render(verb, frame))
516
+ this.#io.stdout(`${line}\n`);
517
+ return 0;
518
+ }
519
+ const step = await run.advance();
520
+ if (step === null)
521
+ break;
522
+ // The dispatch-entry gate's refusal (the lifecycle's hard child zero-dispatch wiring —
523
+ // structurally unreachable here: the seam already returned above on refusal).
524
+ if (step.preflight !== undefined) {
525
+ this.#renderPreflightBlocked(verb, step.preflight, scene);
526
+ return 1;
527
+ }
528
+ dispatched += 1;
529
+ latest = step.capsuleLines;
530
+ lastStatus = statuses[statuses.length - 1] ?? null;
531
+ // NO manual done-marking here: the lifecycle's markTerminal is the single
532
+ // closure gate (C5) — a dispatched wave advances the frontier only through
533
+ // its concluded round's route. The old dispatch-then-markDone shortcut drove
534
+ // the loop across waves without a closure verdict: after implement of wave 1
535
+ // it marked wave 1 done, so the loop dispatched wave 2 in the same call
536
+ // (dry-run) and rendered every mid-run closure as `next: done` (the per-step
537
+ // next was already consumed). The ledger-mirrored cursor above + markTerminal
538
+ // together keep one wave phase per invocation.
539
+ if (lastStatus === "BLOCKED" || lastStatus === "TIMEOUT") {
540
+ // The timeout counter's call site (§4.2): a TIMEOUT round lands, the count
541
+ // goes up by one — the counter's only production writer.
542
+ if (lastStatus === "TIMEOUT")
543
+ scene.ledger.incrementTimeoutCount();
544
+ for (const line of latest)
545
+ this.#io.stdout(`${line}\n`);
546
+ return 1;
547
+ }
548
+ // The no-next hard error (v1.20): a completed non-failed round must produce a
549
+ // `next:` line — null after a passed BLOCKED/TIMEOUT check is an abnormal
550
+ // completion, never a silent approved-without-next.
551
+ if (step.route === null) {
552
+ for (const line of latest)
553
+ this.#io.stdout(`${line}\n`);
554
+ this.#io.stderr(`${this.#words.station("blocked")} the round concluded ${lastStatus ?? "APPROVED"} with no next: line — a completed non-failed round must yield a next-hop route (re-run the same command to continue)\n`);
555
+ return 1;
556
+ }
557
+ }
558
+ if (dispatched === 0) {
559
+ this.#io.stderr(`cdd ${verb}: nothing to dispatch — the line holds no open frame\n`);
560
+ return 1;
561
+ }
562
+ for (const line of latest)
563
+ this.#io.stdout(`${line}\n`);
564
+ return 0;
565
+ }
566
+ /** The dispatch seam — the injected override, else the harness production default.
567
+ * The call itself is unconditional (the caller resolves the step before the
568
+ * preview branch), but under `--dry-run` the preview path returns before the
569
+ * step is INVOKED — `dispatch(frame)` is never called (P11 T5 · §3.2) — so the
570
+ * retired synthetic approval (`() => ({ status: "APPROVED", findings: [] })`)
571
+ * has no remaining caller: a preview books no round and fabricates no
572
+ * conclusion. */
573
+ #dispatchOf(scene, parsed) {
574
+ if (this.#dispatch !== null)
575
+ return this.#dispatch;
576
+ const harness = new CliLifecycle({
577
+ env: process.env,
578
+ sync: this.#sync,
579
+ config: this.#config,
580
+ template: this.#template,
581
+ io: this.#io,
582
+ scene: {
583
+ workspace: scene.workspace,
584
+ ledger: scene.ledger,
585
+ planPath: scene.planPath,
586
+ briefPath: scene.briefPath,
587
+ baseBranch: this.#baseBranchOf(scene),
588
+ specLink: scene.specLink,
589
+ },
590
+ reviews: parsed.paths.reviews,
591
+ });
592
+ return harness.step();
593
+ }
594
+ /** The branch scope anchor (BASE_BRANCH) — the base artifact's branch name read
595
+ * from the line's own workspace (`base.json`, the same `base get` source the CLI
596
+ * writes). "" when the artifact is absent or malformed (the slot stays empty and
597
+ * the assembler drops it — the wave/branch review then judges the live tree). */
598
+ #baseBranchOf(scene) {
599
+ const read = scene.workspace.readJson("base.json");
600
+ const artifact = read.kind === "ok" ? read.value : null;
601
+ return typeof artifact?.base === "string" ? artifact.base : "";
602
+ }
603
+ /** The phase-mismatch hint — what to run instead. */
604
+ #phaseHint(phase) {
605
+ switch (phase) {
606
+ case "implement":
607
+ return " — run cdd implement first";
608
+ case "review":
609
+ case "branch-review":
610
+ return " — run cdd review first";
611
+ default:
612
+ return " — run cdd fix first";
613
+ }
614
+ }
615
+ /** Render a refused pre-flight verdict — the work command's BLOCK face (P4.1 T1).
616
+ * The dirty-tree / doc-contract refusals ride the CDD_BLOCKED channel (the
617
+ * commit/discard guidance + the named structural findings); the graph / wave
618
+ * refusals keep the pre-existing refusal face (the wave-board hint renders for the
619
+ * wave gate's split row — its done face rides the SAME closedWaves() read the gate
620
+ * judged, one closed set, one source). */
621
+ #renderPreflightBlocked(verb, verdict, scene) {
622
+ if (verdict.gate === "tree-clean" || verdict.gate === "doc-contract") {
623
+ this.#io.stderr(`${this.#words.station("blocked")} ${verdict.message ?? ""}\n`);
624
+ for (const detail of verdict.details ?? [])
625
+ this.#io.stderr(` ${detail}\n`);
626
+ return;
627
+ }
628
+ this.#io.stderr(`cdd ${verb}: ${verdict.message ?? "the dispatch gate refused the request"}\n`);
629
+ for (const detail of verdict.details ?? [])
630
+ this.#io.stderr(` ${detail}\n`);
631
+ if (verdict.gate === "wave" && verdict.reason === "split" && scene.planText !== null) {
632
+ const graph = new TaskGraph(new PlanDocType("plan").parse(scene.planText.split("\n")));
633
+ const closed = scene.ledger.closedWaves();
634
+ // The graph title's plan path renders repoRoot-relative (D47 · the ONE shape;
635
+ // `scene.planPath` is argv-origin) — normalized through the scene's OWN basis
636
+ // value object (F2: never a per-call re-wrap).
637
+ const titlePlan = scene.workspace.root.basis.relativize(scene.planPath ?? "");
638
+ for (const line of this.#graphView
639
+ .render(graph.report(closed), `graph: ${titlePlan}`)
640
+ .split("\n"))
641
+ this.#io.stderr(` ${line}\n`);
642
+ }
643
+ }
644
+ // ---------------------------------------------------------------------------
645
+ // the work scene — the composition of contract/session/face objects
646
+ // ---------------------------------------------------------------------------
647
+ /** Assemble one work command's scene: the workspace (repo root + the plan/spec
648
+ * slug), the ledger, the run state (TaskGraph from the plan parse for the task
649
+ * face, the empty single-target state otherwise), the fixed target. The repo root
650
+ * is derived at the ONE conversion point (T2) — a cwd outside a git repo returns
651
+ * null, which the caller turns into the BLOCKED exit (§2.6). The path-typed argv
652
+ * values ride the input funnel (T3 · `#funnel`) so the scene consumes canonical
653
+ * repoRoot-relative `RepoPath`s. */
654
+ async #sceneOf(verb, type, node, root, parsed) {
655
+ const config = this.#config;
656
+ const face = targetFaces[type];
657
+ const repoRoot = root.absolute;
658
+ const rootPath = new WorkspaceRoot(repoRoot, config.handoffNamespace().workspaceRoot);
659
+ // The argv paths ride the ONE funnel (T3 §2.3): the READ faces consume the branded
660
+ // `RepoPath` (`parsed.paths`), while the scene's own `planPath`/`target.doc` — the
661
+ // facts the ledger persists and the syscalls read — are the value object's `resolve`
662
+ // erasure (the absolute syscall form; their persisted shape is T4's face). Both
663
+ // derive from the same funnel, so there is zero second normalization — the brand
664
+ // reaches here with NO downcast (F7).
665
+ const planRel = parsed.paths.plan;
666
+ const planPath = planRel === null ? null : root.resolve(planRel);
667
+ const specRel = parsed.paths.spec;
668
+ const specPath = specRel === null ? null : root.resolve(specRel);
669
+ let slug;
670
+ let planText = null;
671
+ let specLink = null;
672
+ let target = null;
673
+ switch (type) {
674
+ case "wave": {
675
+ if (planPath === null || planRel === null)
676
+ this.#usage(node, `cdd ${verb} --type wave: missing required --plan <path>`);
677
+ slug = Workspace.slugFromDoc(planPath);
678
+ planText = this.#artifacts.readText(node, root, planRel);
679
+ break;
680
+ }
681
+ case "spec": {
682
+ if (specPath === null)
683
+ this.#usage(node, `cdd ${verb} --type spec: missing required --spec <path>`);
684
+ slug = Workspace.slugFromDoc(specPath);
685
+ target = { kind: "spec", doc: specPath };
686
+ break;
687
+ }
688
+ case "plan":
689
+ // fallthrough to the shared plan-sourced derivation below
690
+ case "branch": {
691
+ // The plan-doc seam (shared by the plan + branch lines): the target plan
692
+ // must exist (a required fact for both — the branch review/fix faces carry
693
+ // `--plan`), its text is read ONCE, and the plan's design-spec reference
694
+ // (the `spec:` front-matter key — the §2.2 delivery seam: the ONE head-
695
+ // REQUIRED parse call site) is derived from that text as the round context's
696
+ // extra read input (no second file read). Rebased to repoRoot-relative
697
+ // (D46 · T3): the raw header form is markdown link-space (relative to the
698
+ // plan's own dir), so it is first resolved to an absolute path, then routed
699
+ // through the ONE value object (`RepoRoot.relativize`) — every round-context
700
+ // path token speaks ONE basis (the child is spawned at cwd = repoRoot). The
701
+ // plan review judges the plan doc; the branch line carries no commit identity
702
+ // (the audit target is the branch itself, its workspace identity is the plan
703
+ // path, and the review's scope anchor BASE_BRANCH is engine-injected from the
704
+ // base artifact) — both faces carry the plan + its spec anchor.
705
+ if (planPath === null || planRel === null)
706
+ this.#usage(node, `cdd ${verb} --type ${type}: missing required --plan <path>`);
707
+ slug = Workspace.slugFromDoc(planPath);
708
+ planText = this.#artifacts.readText(node, root, planRel);
709
+ const split = FrontMatterExtractor.split(planText);
710
+ const rawSpecLink = new PlanDocType("plan").parse(split.body.split("\n"), split.head).chain.specLink
711
+ ?.target ?? null;
712
+ specLink =
713
+ rawSpecLink === null
714
+ ? null
715
+ : root.relativize(this.#resolveSpecLink(repoRoot, planPath, rawSpecLink));
716
+ target = type === "plan" ? { kind: "plan", doc: planPath } : { kind: "branch" };
717
+ break;
718
+ }
719
+ }
720
+ // The workspace is NOT built here (P11 · §4.2): scene assembly is a READ face —
721
+ // the real run's single write point builds it (`Cli#runWork`'s explicit ensure,
722
+ // every face), so a read-only command never creates `.kairos/`. The one-time
723
+ // legacy migration retired with this build: the `Workspace.readJson` read-time
724
+ // normalization is the ONE heal path, covering `base.json` alongside
725
+ // `progress.json` (a second healing point is gone).
726
+ const workspace = new Workspace(rootPath, slug);
727
+ const ledger = new Ledger(workspace, config);
728
+ const state = type === "wave"
729
+ ? new TaskGraph(new PlanDocType("plan").parse(planText.split("\n")))
730
+ : EMPTY_RUN_STATE;
731
+ return {
732
+ workspace,
733
+ ledger,
734
+ planPath,
735
+ planText,
736
+ type,
737
+ face,
738
+ target,
739
+ state,
740
+ router: new NextStepRouter(),
741
+ briefPath: null,
742
+ specLink,
743
+ };
744
+ }
745
+ /** The input funnel — the ONE path normalization landing (T3 · §2.3): every
746
+ * path-typed argv value is relativized to the repo root EXACTLY once, here,
747
+ * before the scene or any downstream face reads it, so no face ever sees a raw
748
+ * argv path shape. The covered face: `--plan` · `--spec` · `--reviews` (the
749
+ * schema `--output skeleton` `<target>` positional and base `--plan` reach the
750
+ * SAME landing through `#relativizePath` — branch-review-1 F6: one relativize+warn
751
+ * helper, one landing). An out-of-repo input (a `..` segment after relativize) is
752
+ * ACCEPTED with a stderr warning — the shape is what is judged, never the location
753
+ * (§2.10). */
754
+ #funnel(root, parsed) {
755
+ const raw = parsed.args;
756
+ // The three path keys move OUT of the generic string record into the branded
757
+ // `paths` face (F7) — splitting them out means the raw path string exists in
758
+ // exactly ONE form downstream (the normalized `RepoPath`), never duplicated
759
+ // (the Data Clumps F2 targets).
760
+ const { plan, spec, reviews, ...rest } = raw;
761
+ return {
762
+ ...parsed,
763
+ args: rest,
764
+ paths: {
765
+ plan: plan === undefined ? null : this.#relativizePath(root, plan),
766
+ spec: spec === undefined ? null : this.#relativizePath(root, spec),
767
+ reviews: reviews === undefined ? null : this.#relativizePath(root, reviews),
768
+ },
769
+ };
770
+ }
771
+ /** The ONE path normalization landing (T3 §2.3 · F6) — relativize a raw argv path
772
+ * to the branded repoRoot-relative `RepoPath` through the value object, then warn
773
+ * on the stderr CDD_WARN channel when the result lies outside the repo. The
774
+ * work-command funnel (`#funnel`) and the pure-command path argv (schema
775
+ * `--output skeleton` `<target>` · base `--plan`) all reach THIS helper, so there
776
+ * is literally ONE relativize+warn site. An out-of-repo input (a `..` segment after
777
+ * relativize) is ACCEPTED — the shape is what is judged, never the location
778
+ * (§2.10). An empty input normalizes to the empty path (no warning). */
779
+ #relativizePath(root, raw) {
780
+ const rel = root.relativize(raw);
781
+ if (rel.split(path.sep).includes("..")) {
782
+ this.#io.stderr(`${this.#words.station("warn")} path is outside the repository: ${rel}\n`);
783
+ }
784
+ return rel;
785
+ }
786
+ /** The repo root — the ONE conversion point (T2 · §2.4/§2.6): the single
787
+ * working-dir → git-top-level resolution of the engine. Zero injection seams
788
+ * (`--root` is retired; the composition options carry no root/cwd), zero
789
+ * fallback. A cwd outside any git repository (a null top level) is a missing
790
+ * run-environment fact: the existing CDD_BLOCKED channel carries the reason and
791
+ * the caller exits 1 (never a usage error — exit 2). */
792
+ async #rootOf() {
793
+ const root = await this.#git.topLevel(process.cwd());
794
+ if (root === null) {
795
+ const blocked = this.#words.station("blocked");
796
+ this.#io.stderr(`${blocked} cannot resolve the repository root — the current directory is not inside a git repository (run cdd from within the repo)\n`);
797
+ return null;
798
+ }
799
+ return root;
800
+ }
801
+ /** The plan's `spec:` link target resolved to an ABSOLUTE path (D46) — the
802
+ * plan-review round context's `INPUT_SPEC` (the round-context exit relativizes it
803
+ * to repoRoot along with every other path token). The raw header form is markdown
804
+ * link-space (relative to the plan's own dir — the skeleton's form) or a repoRoot
805
+ * form; the resolution IS the doc-contract's own chain-link judgment, delegated
806
+ * to its ONE home (`FileExistenceInvariant.targetPath`) so a future contract
807
+ * change cannot silently diverge from this mirror (P9 branch-review-1 F8 — never
808
+ * a re-implemented chain). The fallback (neither reading exists) resolves against
809
+ * the plan's own dir — the link-space semantic — so the exit still receives an
810
+ * absolute path (the doc-contract's file-existence finding owns the truly-missing
811
+ * case). */
812
+ #resolveSpecLink(repoRoot, planPath, target) {
813
+ return FileExistenceInvariant.targetPath(repoRoot, planPath, target, (p) => existsSync(p));
814
+ }
815
+ // ---------------------------------------------------------------------------
816
+ // the pure commands — schema / issue / base
817
+ // ---------------------------------------------------------------------------
818
+ /** `cdd schema get <type> [--output json|skeleton] [<target>]` — the merged D19
819
+ * single leaf: the json render face (the default — the derived doc-structure
820
+ * schema JSON to stdout, no target) and the skeleton render face (`--output
821
+ * skeleton` — the derived doc skeleton written DIRECTLY into the target
822
+ * document, the target required). The type vocabulary = the one shared
823
+ * schema-type table (`SCHEMA_TYPE_KEYS` in face/declare.ts: the primary DocKey
824
+ * spellings + the legacy alias normalized to kebab, spec §5.3). */
825
+ async #runSchema(node, parsed) {
826
+ this.#assertDryRunScope(node, parsed.dryRun);
827
+ const [type, target] = parsed.positionals;
828
+ if (type === undefined)
829
+ this.#usage(node, "cdd schema get: missing <type>");
830
+ const output = parsed.args.output ?? "json";
831
+ if (output === "skeleton") {
832
+ // The skeleton render face — the engine-declared target (D19): the authoring
833
+ // scaffold lands in the target document, zero shell-redirection indirection.
834
+ if (target === undefined) {
835
+ this.#usage(node, "cdd schema get --output skeleton: missing <target>");
836
+ }
837
+ // The positional `<target>` reaches the SAME one normalization landing (T3 §2.3
838
+ // · F6) as the work-command path argv (`#relativizePath`), then is erased
839
+ // through the value object at the write boundary.
840
+ const repoRoot = await this.#rootOf();
841
+ if (repoRoot === null)
842
+ return 1;
843
+ const root = new RepoRoot(repoRoot);
844
+ const targetPath = this.#relativizePath(root, target);
845
+ return this.#artifacts.runSchemaSkeleton(node, root, type, targetPath);
846
+ }
847
+ if (target !== undefined) {
848
+ this.#usage(node, "cdd schema get: unexpected <target> — the json render takes no target (use --output skeleton <target> to render the scaffold into a document)");
849
+ }
850
+ this.#io.stdout(`${JSON.stringify(this.#projector.schema()[type], null, 2)}\n`);
851
+ return 0;
852
+ }
853
+ /** `cdd base <set|get> --plan <path>` — the base artifact read/write (T20: the
854
+ * command face `base`; the artifact file carries the base face too). */
855
+ async #runBase(node, parsed) {
856
+ this.#assertDryRunScope(node, parsed.dryRun);
857
+ const planArg = parsed.args.plan;
858
+ if (planArg === undefined) {
859
+ this.#usage(node, "cdd base: missing --plan — the sole target is --plan <path>");
860
+ }
861
+ const repoRoot = await this.#rootOf();
862
+ if (repoRoot === null)
863
+ return 1;
864
+ const root = new RepoRoot(repoRoot);
865
+ // The base `--plan` reaches the SAME one normalization landing (T3 §2.3 · F6) as
866
+ // the work-command path argv: the stored artifact's path field speaks the ONE
867
+ // canonical shape (repoRoot-relative).
868
+ const planPath = this.#relativizePath(root, planArg);
869
+ // The workspace is not built here (P11 · §4.2): `base set` builds it through
870
+ // `Workspace.writeJson`'s internal ensure, while the read-only `base get`
871
+ // creates nothing. The read rides `Workspace.readJson`, so the P9 read-time
872
+ // normalization covers `base.json` (the retired migration's job).
873
+ const workspace = new Workspace(new WorkspaceRoot(repoRoot, this.#config.handoffNamespace().workspaceRoot), Workspace.slugFromDoc(planPath));
874
+ if (parsed.leaf === "set")
875
+ return this.#artifacts.baseSet(node, parsed, planPath, workspace, root);
876
+ if (parsed.leaf === "get")
877
+ return this.#artifacts.baseGet(workspace, root);
878
+ this.#usage(node, "cdd base: missing <set|get> subcommand");
879
+ }
880
+ /**
881
+ * Cli.create(opts?) — the composition root's static factory: wires the engine's
882
+ * object graph (contract: the projector over the declared registries · session: the
883
+ * ledger + lifecycle + task graph + next router · face: the words + capsule ·
884
+ * infra: the config loader + git + the sync process seam) into the ONE Cli the bin
885
+ * thin entry boots. Every collaborator is overridable for the hermetic test face
886
+ * (io / dispatch / repoRoot); the defaults bind the living process.
887
+ */
888
+ static create(opts = {}) {
889
+ return new Cli(opts);
890
+ }
891
+ }