@oscaner-skills/cdd-engine 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oscaner Miao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # @oscaner-skills/cdd-engine
2
+
3
+ [English](README.md) | [中文](README.zh-CN.md)
4
+
5
+ CDD engine CLI — the task runner, document/branch reviewer, and harness dispatcher behind the osuperpowers `cli-driven-development` skill. Published as a standalone package so the engine (`cdd`) can be installed and invoked on its own.
6
+
7
+ ## What this package is
8
+
9
+ The engine runs the implement / review / fix phases of the CDD workflow against a plan file, writes the dispatch's handoff artifacts, reads and writes the `base-branch` artifact, and dispatches each phase to the host harness CLI through its embedded harness registry. It is consumed by the [osuperpowers plugin](https://www.npmjs.com/package/@oscaner-skills/osuperpowers)'s `cli-driven-development` skill and is also usable directly from the command line.
10
+
11
+ ## Installation
12
+
13
+ Requires Node.js `>= 22.12.0`.
14
+
15
+ ```bash
16
+ # global CLI (provides the `cdd` binary)
17
+ npm install -g @oscaner-skills/cdd-engine
18
+
19
+ # or as a dependency
20
+ npm install @oscaner-skills/cdd-engine
21
+ ```
22
+
23
+ ## CLI
24
+
25
+ Global option: `--dry-run` — simulate the dispatch without writing handoff artifacts.
26
+
27
+ | Subcommand | Usage | Purpose |
28
+ |------------|-------|---------|
29
+ | `implement` | `cdd implement --tasks=<n> [--plan=<path>]` | Run the task implement phase |
30
+ | `review` | `cdd review --type=<task\|branch\|spec\|plan>` | Run a review — task, branch, spec, or plan |
31
+ | `fix` | `cdd fix --type=<task\|branch\|spec\|plan>` | Fix review findings — task, branch, spec, or plan |
32
+ | `base-branch` | `cdd base-branch set\|get` | Read/write the `base-branch.json` artifact (single CDD `--plan` target) |
33
+ | `schema` | `cdd schema get <type>` | Print the canonical doc-structure schema (discovery-only, zero enforcement) |
34
+ | `issue` | `cdd issue render` | Render an aggregate issue body from stdin findings (pure rendering, zero enforcement) |
35
+
36
+ Use `cdd <command> --help` for a command's full option list (for example `cdd review --tasks` / `--base` / `--head` / `--spec` / `--round`).
37
+
38
+ ## Development
39
+
40
+ The package lives in the [Oscaner/skills](https://github.com/Oscaner/skills) monorepo at `packages/cdd-engine` (TypeScript, built with unbuild, tested with vitest; tests are colocated at `src/**/__tests__/**/*.test.ts`).
41
+
42
+ ```bash
43
+ pnpm --filter @oscaner-skills/cdd-engine dev:stub # rebuild the jiti immediate-load dev stub
44
+ node packages/cdd-engine/dist/cli.mjs schema get plan # invoke the engine from the working tree
45
+ pnpm --filter @oscaner-skills/cdd-engine test # run the engine test suite
46
+ ```
47
+
48
+ During repository development the engine is invoked straight from the working tree (`dist/cli.mjs`) — never through a global install or link, which can go stale.
49
+
50
+ ## License
51
+
52
+ MIT
@@ -0,0 +1,54 @@
1
+ # @oscaner-skills/cdd-engine
2
+
3
+ > 🔗 **Mirror 同步声明**:本文件(`README.zh-CN.md`)是英文源 [README.md](README.md) 的同步中文 **mirror**——顶层章节集合逐条一致,节点按位置一一对应;本文为对外宣讲面的中文口径,语义以英文源为准。**同步时间戳**:2026-09-26。
4
+
5
+ [English](README.md) | [中文](README.zh-CN.md)
6
+
7
+ CDD 引擎 CLI——osuperpowers `cli-driven-development` 技能背后的任务运行器、文档/分支评审器与 harness 派发器。以独立包发布,使引擎(`cdd`)可单独安装与调用。
8
+
9
+ ## 包定位
10
+
11
+ 引擎针对计划文件运行 CDD 工作流的 implement / review / fix 阶段,写出派发的 handoff 产物,读写 `base-branch` 产物,并通过其内嵌的 harness 注册表将每个阶段派发给宿主 harness CLI。它被 [osuperpowers 插件](https://www.npmjs.com/package/@oscaner-skills/osuperpowers)的 `cli-driven-development` 技能消费,也可直接从命令行使用。
12
+
13
+ ## 安装
14
+
15
+ 需要 Node.js `>= 22.12.0`。
16
+
17
+ ```bash
18
+ # 全局 CLI(提供 `cdd` 二进制)
19
+ npm install -g @oscaner-skills/cdd-engine
20
+
21
+ # 或作为依赖
22
+ npm install @oscaner-skills/cdd-engine
23
+ ```
24
+
25
+ ## CLI
26
+
27
+ 全局选项:`--dry-run`——模拟派发而不写 handoff 产物。
28
+
29
+ | 子命令 | 用法 | 用途 |
30
+ |--------|------|------|
31
+ | `implement` | `cdd implement --tasks=<n> [--plan=<path>]` | 运行任务 implement 阶段 |
32
+ | `review` | `cdd review --type=<task\|branch\|spec\|plan>` | 运行评审——task、branch、spec 或 plan |
33
+ | `fix` | `cdd fix --type=<task\|branch\|spec\|plan>` | 修复评审发现——task、branch、spec 或 plan |
34
+ | `base-branch` | `cdd base-branch set\|get` | 读写 `base-branch.json` 产物(单一 CDD `--plan` 目标) |
35
+ | `schema` | `cdd schema get <type>` | 打印 canonical 文档结构 schema(发现型、零执法) |
36
+ | `issue` | `cdd issue render` | 依据 stdin 发现渲染聚合 issue 正文(纯渲染、零执法) |
37
+
38
+ 用 `cdd <command> --help` 查看某命令的完整选项列表(例如 `cdd review --tasks` / `--base` / `--head` / `--spec` / `--round`)。
39
+
40
+ ## 开发说明
41
+
42
+ 包位于 [Oscaner/skills](https://github.com/Oscaner/skills) monorepo 的 `packages/cdd-engine`(TypeScript,unbuild 构建,vitest 测试;测试与源码同地放置于 `src/**/__tests__/**/*.test.ts`)。
43
+
44
+ ```bash
45
+ pnpm --filter @oscaner-skills/cdd-engine dev:stub # 重建 jiti 即时加载开发 stub
46
+ node packages/cdd-engine/dist/cli.mjs schema get plan # 从工作树直接调用引擎
47
+ pnpm --filter @oscaner-skills/cdd-engine test # 运行引擎测试套件
48
+ ```
49
+
50
+ 仓库开发期间引擎须从工作树直接调用(`dist/cli.mjs`)——绝不要经全局安装或链接,可能过期。
51
+
52
+ ## 许可
53
+
54
+ MIT
@@ -0,0 +1,480 @@
1
+ import { existsSync, readFileSync, mkdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { B as getRoot, I as resolveWorkspace, J as familyConfig, s as exitWithCode, h as handoffName, w as writeHandoff, d as ReturnBlockParser, K as exitOk, u as resolveDocArg, r as readJson, k as writeBlockedCarrier, T as TemplateLoader, f as finalizeHandoff, a as writeOwnHandoff, b as DispatchLifecycle, l as FAILURE_CATEGORIES, R as ResidueManager, H as HandoffSchemaValidator, m as recoverHandoff, L as resolveNextRound, x as prevHandoffPath, M as ConvergenceChecker } from '../cli.mjs';
4
+ import { E as EngineInvoker, R as Registry, a as REG_PATH, C as CddBlockedError } from '../shared/cdd-engine.liioziig.mjs';
5
+ import 'node:process';
6
+ import 'citty';
7
+ import 'node:url';
8
+ import 'tinyglobby';
9
+ import 'node:child_process';
10
+ import 'ajv';
11
+ import 'execa';
12
+ import 'simple-git';
13
+ import 'node:crypto';
14
+ import 'hookable';
15
+ import 'handlebars';
16
+
17
+ const registry = new Registry();
18
+ const invoker = new EngineInvoker();
19
+ const templates = new TemplateLoader();
20
+ const convergence = new ConvergenceChecker();
21
+ const schema = new HandoffSchemaValidator();
22
+ const residue = new ResidueManager();
23
+ const returnBlocks = new ReturnBlockParser();
24
+ class BranchLifecycle extends DispatchLifecycle {
25
+ opts;
26
+ entry = null;
27
+ repoRoot = "";
28
+ workspace = "";
29
+ handoffPath = "";
30
+ /** invoke result code of the just-finished agent dispatch (schemaValidate reads it for the
31
+ * failure-without-handoff lanes). */
32
+ agentRc = 0;
33
+ /** the schema-validated / recovered handoff (schemaValidate → normalizeResult handoff). */
34
+ agentHandoff = null;
35
+ /** post-finalization exit code — normalizeResult stores it; the fix wrapper emits it AFTER the
36
+ * inherited exit gate ran (the gate failure rewrites the handoff and exits 1 before this is
37
+ * read; the review wrapper never reads it — review's normalizeResult exits immediately). */
38
+ finalExitCode = 0;
39
+ /** The stored round conclusion (post-run read for the fix wrapper's exit). */
40
+ get exitCode() {
41
+ return this.finalExitCode;
42
+ }
43
+ constructor(options) {
44
+ const { ctx, ...opts } = options;
45
+ super({ ctx });
46
+ this.opts = { ...opts };
47
+ }
48
+ /** Branch-family entry gate: NO-OP — branch review/fix rounds are ref-driven and never gate on
49
+ * the pre-commit clean tree (the former cli flat bodies ran none). The working-tree contract of
50
+ * the fix channel lives at the EXIT gate (inherited default commitPostCheck). */
51
+ async commitPreCheck(_hookCtx) {
52
+ }
53
+ /** Lane-declared doc-audit target (T3 ④「lane 声明审计对象」): the branch channel audits its
54
+ * `--plan` ref (the same plan the review/fix round derives its workspace from) — the base default
55
+ * docContractValidate walks plan → `**Spec:**` → Parent program → overall and gates on the
56
+ * parent-overall four tables when the lineage resolves. */
57
+ docAuditTarget() {
58
+ if (!this.opts.plan) return null;
59
+ try {
60
+ return resolveDocArg(this.opts.plan, this.repoRoot, "plan");
61
+ } catch {
62
+ return this.opts.plan;
63
+ }
64
+ }
65
+ /** Plan-bearing declaration (P2 T4): the branch lane is ALWAYS plan-bearing — the closeout
66
+ * terminal-debt hard gate and the base-default statusValidate key off its `--plan` ref (v1.12:
67
+ * the v1.11 lane boundary is rescinded — branch-review's precondition IS the ended plan, so its
68
+ * backfill obligation is already due and the gate is the correct behavior). */
69
+ dispatchPlanPath() {
70
+ return this.docAuditTarget();
71
+ }
72
+ /** Doc-contract BLOCK face (T3 ④): the branch terminal convention — stderr CDD_BLOCKED +
73
+ * exitWithCode(1) (exit helpers throw ExitRequested, the bin maps the exact code; the default
74
+ * DispatchBlocked throw would escape the wrappers' gate filters and land on exit 2). */
75
+ docContractBlocked(guidance) {
76
+ process.stderr.write(
77
+ `CDD_BLOCKED: doc contract validation failed \u2014 fix the docs below:
78
+ ${guidance}
79
+ `
80
+ );
81
+ exitWithCode(1);
82
+ }
83
+ /** Registry ship gate (spec step 1): resolve the harness entry + dry-run-path CLI-existence
84
+ * check. Failure → the message on stderr + the kind's exit code (cli-missing → 2, blocked → 1;
85
+ * the CLI 0/1/2 table preserved — CddBlockedError.exitCode IS that code). A non-CddBlockedError
86
+ * registry failure (e.g. corrupt registry JSON) rethrows to the caller surface. */
87
+ registryGate() {
88
+ try {
89
+ this.entry = registry.checkHarness(
90
+ registry.load(this.opts.registryPath ?? REG_PATH),
91
+ this.opts.harness,
92
+ {
93
+ dryRun: this.opts.dryRun
94
+ }
95
+ );
96
+ } catch (e) {
97
+ if (e instanceof CddBlockedError) {
98
+ process.stderr.write(`${e.message}
99
+ `);
100
+ exitWithCode(e.exitCode);
101
+ }
102
+ throw e;
103
+ }
104
+ }
105
+ /** BLOCKED-carrier commits — only when the base satisfies the schema's `^[0-9a-f]{40}$`: a
106
+ * short-form base is carried by the AC15 base7..head7 file name, and a BLOCKED payload must
107
+ * always pass its own validation. head included only when present (branch-review carries the
108
+ * reviewed range head; branch-fix has no head yet). */
109
+ branchCarrierCommits(base, head) {
110
+ const fullBase = typeof base === "string" && /^[0-9a-f]{40}$/.test(base) ? base : null;
111
+ if (!fullBase) return void 0;
112
+ return { base: fullBase, ...typeof head === "string" && head ? { head } : {} };
113
+ }
114
+ /** Shared schema-validate lane (single implementation for both branch channels — the former two
115
+ * hook bodies were structurally identical parallel implementations of the same sequence; one
116
+ * helper keeps the agent-failure / no-handoff / schema-recovery lanes from drifting between
117
+ * branch-review and branch-fix). Every lane writes the BLOCKED carrier and exits 1; on recovery
118
+ * the normalized handoff replaces the agent's file. `phase` is the handoff phase field, `label`
119
+ * the channel word in the CDD_BLOCKED diagnostics, `reRun` the re-run command phrase in the
120
+ * blockers, `commits` the channel's BLOCKED-carrier commits subset. T25: the execution-failure
121
+ * lane records the death diagnosis (recovery.cause + exit_code) and preserves the dirty-tree
122
+ * residue INLINE (these lanes abort via exitWithCode — the template post-flight settleResidue
123
+ * step never fires on the branch channel). */
124
+ async schemaValidateBranch(options) {
125
+ const { phase, label, reRun, commits } = options;
126
+ if (this.agentRc !== 0 && !existsSync(this.handoffPath)) {
127
+ writeBlockedCarrier(this.handoffPath, {
128
+ tasks: [1],
129
+ phase,
130
+ ...commits ? { commits } : {},
131
+ recovery: { cause: FAILURE_CATEGORIES.EXECUTION_FAILURE.id, exit_code: this.agentRc },
132
+ blocker: `cli exited ${this.agentRc}${this.agentRc === 143 ? " (SIGTERM \u2014 externally killed)" : ""} without writing handoff \u2192 worktree residue is preserved as a stash (\`git stash list\` \u2192 \`git stash apply <ref>\` \u2192 review \u2192 commit to salvage or \`git stash drop\` to discard) \u2192 re-run ${reRun}`
133
+ });
134
+ process.stderr.write(`CDD_BLOCKED: ${label} failed (exit ${this.agentRc})
135
+ `);
136
+ await residue.preserveAndAnnounceResidue(this.repoRoot, this.handoffPath, this.repoRoot);
137
+ exitWithCode(1);
138
+ }
139
+ if (!existsSync(this.handoffPath)) {
140
+ writeBlockedCarrier(this.handoffPath, {
141
+ tasks: [1],
142
+ phase,
143
+ ...commits ? { commits } : {},
144
+ blocker: `${path.basename(this.handoffPath)} not written after exit 0 \u2192 re-run ${reRun}`
145
+ });
146
+ process.stderr.write(`CDD_BLOCKED: ${label} handoff not written
147
+ `);
148
+ exitWithCode(1);
149
+ }
150
+ let agentHandoff;
151
+ try {
152
+ agentHandoff = JSON.parse(readFileSync(this.handoffPath, "utf8"));
153
+ } catch (e) {
154
+ writeBlockedCarrier(this.handoffPath, {
155
+ tasks: [1],
156
+ phase,
157
+ ...commits ? { commits } : {},
158
+ blocker: `${label} handoff JSON unparseable: ${e.message} \u2192 fix the handoff at ${this.handoffPath} and re-run ${reRun}`
159
+ });
160
+ process.stderr.write(`CDD_BLOCKED: ${label} handoff JSON unparseable
161
+ `);
162
+ exitWithCode(1);
163
+ }
164
+ let handoff = agentHandoff;
165
+ const sv = schema.validateHandoffSchema(agentHandoff, "task");
166
+ if (!sv.valid) {
167
+ const rec = recoverHandoff(agentHandoff, "task");
168
+ if (!rec.valid) {
169
+ writeBlockedCarrier(this.handoffPath, {
170
+ tasks: [1],
171
+ phase,
172
+ ...commits ? { commits } : {},
173
+ findings: rec.preservedFindings,
174
+ blocker: `${label} handoff schema invalid${rec.reason} \u2192 fix and re-run ${reRun}`,
175
+ fullReplace: true
176
+ // violating keys never stay on disk
177
+ });
178
+ process.stderr.write(`CDD_BLOCKED: ${label} handoff schema invalid
179
+ `);
180
+ exitWithCode(1);
181
+ }
182
+ writeOwnHandoff(this.handoffPath, rec.handoff);
183
+ handoff = rec.handoff;
184
+ }
185
+ this.agentHandoff = handoff;
186
+ }
187
+ }
188
+ class BranchReviewLifecycle extends BranchLifecycle {
189
+ #base;
190
+ #head;
191
+ constructor(options) {
192
+ super(options);
193
+ this.#base = options.base;
194
+ this.#head = options.head;
195
+ }
196
+ /** Round/ref derivation: per-ref round seq (resolveNextRound over the concrete base7/head7) +
197
+ * --round backfill validation (conflict → exit 2) + Convergence prev read (canonical
198
+ * prevHandoffPath concrete-matches the same ref) + the per-round handoff filename + workspace
199
+ * bootstrap. */
200
+ async resolveContext(_hookCtx) {
201
+ this.registryGate();
202
+ this.repoRoot = this.opts.root ?? getRoot();
203
+ const base = String(this.#base);
204
+ const head = String(this.#head);
205
+ const base7 = base.slice(0, 7);
206
+ const head7 = head.slice(0, 7);
207
+ this.workspace = resolveWorkspace(this.opts.plan, this.repoRoot);
208
+ const round = resolveNextRound(this.workspace, "review", "branch", {
209
+ base7,
210
+ head7
211
+ });
212
+ if (this.opts.round && Number(this.opts.round) !== round) {
213
+ process.stderr.write(`--round ${this.opts.round} \u2260 engine round ${round}
214
+ `);
215
+ exitWithCode(2);
216
+ }
217
+ const prevPath = prevHandoffPath(this.workspace, "review", "branch", round, {
218
+ base7,
219
+ head7
220
+ });
221
+ let prev = null;
222
+ if (prevPath && existsSync(prevPath)) {
223
+ try {
224
+ prev = JSON.parse(readFileSync(prevPath, "utf8"));
225
+ } catch {
226
+ process.stderr.write(
227
+ `CDD_INFO: corrupt prev branch handoff ${prevPath} ignored \u2192 fail-open
228
+ `
229
+ );
230
+ prev = null;
231
+ }
232
+ }
233
+ if (prev) convergence.reviewConvergenceGuard(prev, "branch", round, `${base7}..${head7}`);
234
+ this.handoffPath = path.join(
235
+ this.workspace,
236
+ handoffName("review", "branch", { base7, head7, round })
237
+ );
238
+ mkdirSync(this.workspace, { recursive: true });
239
+ }
240
+ /** Steps 7/8: render the branch-review prompt (docs-family shell + REVIEW_REFERENCE
241
+ * base..head + review-family round-context slots) and spawn the harness CLI. Dry-run:
242
+ * APPROVED stub handoff + the 5-line return block (assembleReturnBlock — the return-block single
243
+ * point) + exit 0. */
244
+ async dispatch(_hookCtx) {
245
+ const base = String(this.#base);
246
+ const head = String(this.#head);
247
+ if (this.opts.dryRun) {
248
+ writeHandoff(this.handoffPath, {
249
+ tasks: [1],
250
+ phase: "branch-review",
251
+ status: "APPROVED",
252
+ commits: { base, head },
253
+ findings: [],
254
+ artifacts: {},
255
+ blocker: "dry-run"
256
+ });
257
+ const returnBlock = returnBlocks.assembleReturnBlock(
258
+ {
259
+ status: "APPROVED",
260
+ commits: `base=${base} head=${head}`,
261
+ artifacts: "",
262
+ blocker: "dry-run"
263
+ },
264
+ this.workspace
265
+ );
266
+ for (const line of returnBlock) process.stdout.write(`${line}
267
+ `);
268
+ exitOk();
269
+ return;
270
+ }
271
+ const cfg = templates.reviewTypeConfig("branch");
272
+ const art = templates.reviewArtifactConfig("branch");
273
+ const prompt = templates.renderTemplate(
274
+ "review",
275
+ {
276
+ MODE: "review",
277
+ REVIEW_TYPE: "branch",
278
+ WORKSPACE: this.workspace,
279
+ WORKSPACE_SLUG: path.basename(this.workspace),
280
+ REVIEW_LENS_GUIDE: cfg.lensEnum.join(" \xB7 "),
281
+ REVIEW_REFERENCE: `${base}..${head}`,
282
+ REVIEW_AXES: cfg.axesGuide,
283
+ HANDOFF_TARGET: this.handoffPath,
284
+ RETURN_FORMAT: art.returnFormat,
285
+ REVIEW_PLAN_LINE: this.opts.plan ? `**Plan:** ${this.opts.plan}` : "",
286
+ HANDOFF_WRITE_GATE: templates.reviewHardGate(art.returnFormat, this.handoffPath)
287
+ },
288
+ "cdd review"
289
+ );
290
+ const terminationCfg = invoker.resolveTerminationConfig("review", void 0, this.workspace);
291
+ const res = await invoker.invokeCliWithRetry(
292
+ this.entry,
293
+ prompt,
294
+ { op: "review", type: "branch" },
295
+ process.env,
296
+ this.repoRoot,
297
+ terminationCfg
298
+ );
299
+ this.agentRc = res.code;
300
+ }
301
+ /** Steps 8.8/10/10.5: agent-failure / no-handoff lanes (BLOCKED carrier writes) + schema
302
+ * recovery + the review-family finalization read-back. */
303
+ async schemaValidate(_hookCtx) {
304
+ const base = String(this.#base);
305
+ const head = String(this.#head);
306
+ await this.schemaValidateBranch({
307
+ phase: "branch-review",
308
+ label: "branch-review",
309
+ reRun: "branch-review",
310
+ commits: this.branchCarrierCommits(base, head)
311
+ });
312
+ }
313
+ /** Status single authority (T5/T7) — branch review (review family) reads back through finalizeHandoff
314
+ * finalization (rollup derived override, SP-4 exempts failure rounds); the finalized write uses
315
+ * writeOwnHandoff (the engine is the carrier's sole author, full-replace). The three consumers
316
+ * (runner/docs-runner/cdd) share the same finalizeHandoff single point.
317
+ * The exit comes from the finalized round conclusion (Task 23 ③: BLOCKED → 1,
318
+ * APPROVED/CHANGES_REQUESTED → 0) — this is the sole exit path once the agent wrote a handoff. */
319
+ async normalizeResult(_hookCtx) {
320
+ const base = String(this.#base);
321
+ const head = String(this.#head);
322
+ const finalized = await finalizeHandoff({ mode: "review", agentHandoff: this.agentHandoff });
323
+ let handoff = finalized.handoff;
324
+ if (handoff && typeof handoff === "object" && handoff.commits === void 0) {
325
+ const cc = this.branchCarrierCommits(base, head);
326
+ if (cc) handoff = { ...handoff, commits: cc };
327
+ }
328
+ if (handoff && handoff !== this.agentHandoff) writeOwnHandoff(this.handoffPath, handoff);
329
+ exitWithCode(finalized.exitCode);
330
+ }
331
+ /** Review-family exit gate: NO-OP — a review writes no code, there is no commit contract to
332
+ * validate (the branch-fix channel inherits the base default instead). */
333
+ async commitPostCheck(_hookCtx) {
334
+ }
335
+ }
336
+ class BranchFixLifecycle extends BranchLifecycle {
337
+ #base7 = "";
338
+ #head7 = "";
339
+ #fixRound = 0;
340
+ /** the derived FIX_BASE (source review's commits.base — the reviewed range base). */
341
+ fixBase = "";
342
+ constructor(options) {
343
+ super(options);
344
+ }
345
+ /** Round/ref derivation from the source review file name (the --findings path). The findings
346
+ * name must mirror the source's ref + round: the ref segments are re-derived from the SAME
347
+ * canonical family template with capturing groups (identical placeholder substitution rules as
348
+ * roundPattern → the config name stays the single truth). Group order: [1]=base7 [2]=head7
349
+ * [3]=round. A non-matching findings name → usage error exit 2 (before any path resolution — the
350
+ * guard order contract, §2.4.2); a fixRound < 1 → usage error exit 2. */
351
+ async resolveContext(_hookCtx) {
352
+ this.registryGate();
353
+ this.repoRoot = this.opts.root ?? getRoot();
354
+ this.workspace = resolveWorkspace(this.opts.plan, this.repoRoot);
355
+ const findingsBase = path.basename(this.opts.findings);
356
+ const refRoundRe = new RegExp(
357
+ "^" + familyConfig("review", "branch").name.replace("{round}", "(\\d+)").replace("{base7}", "([0-9a-f]{7})").replace("{head7}", "([0-9a-f]{7})").replaceAll(".", "\\.") + "$"
358
+ );
359
+ const refRound = findingsBase.match(refRoundRe);
360
+ if (!refRound) {
361
+ process.stderr.write(
362
+ `cdd fix --type branch: --findings must name a branch-review-{base7}..{head7}-r{R}.json file (round + ref derived from the source review); got: ${this.opts.findings}
363
+ `
364
+ );
365
+ exitWithCode(2);
366
+ }
367
+ this.#base7 = refRound[1];
368
+ this.#head7 = refRound[2];
369
+ this.#fixRound = Number(refRound[3]);
370
+ if (!Number.isInteger(this.#fixRound) || this.#fixRound < 1) {
371
+ process.stderr.write(
372
+ `cdd fix --type branch: --findings round must be >= 1 (round derived from the source review); got: ${this.opts.findings}
373
+ `
374
+ );
375
+ exitWithCode(2);
376
+ }
377
+ this.handoffPath = path.join(
378
+ this.workspace,
379
+ handoffName("fix", "branch", {
380
+ base7: this.#base7,
381
+ head7: this.#head7,
382
+ round: this.#fixRound
383
+ })
384
+ );
385
+ this.ctx = { ...this.ctx, handoffPath: this.handoffPath, repoRoot: this.repoRoot };
386
+ }
387
+ /** Steps 7/8: derive the FIX_BASE (source review's commits.base; missing/unknown → BLOCKED
388
+ * carrier + exit 1), render the fix prompt (task-family shell + RETURN_STDOUT_BLOCK), spawn the
389
+ * fix agent CLI. Dry-run: APPROVED stub handoff + the 5-line return block + exit 0. */
390
+ async dispatch(_hookCtx) {
391
+ if (this.opts.dryRun) {
392
+ writeHandoff(this.handoffPath, {
393
+ tasks: [1],
394
+ phase: "fix",
395
+ status: "APPROVED",
396
+ commits: { base: "dry-run", head: "dry-run" },
397
+ findings: [],
398
+ artifacts: {},
399
+ blocker: "dry-run"
400
+ });
401
+ const returnBlock = returnBlocks.assembleReturnBlock(
402
+ {
403
+ status: "APPROVED",
404
+ commits: "base=dry-run head=dry-run",
405
+ artifacts: "",
406
+ blocker: "dry-run"
407
+ },
408
+ this.workspace
409
+ );
410
+ for (const line of returnBlock) process.stdout.write(`${line}
411
+ `);
412
+ exitOk();
413
+ return;
414
+ }
415
+ const findingsPath = resolveDocArg(this.opts.findings, this.repoRoot, "findings");
416
+ const src = readJson(findingsPath);
417
+ const fixBase = src?.commits?.base;
418
+ if (!fixBase || fixBase === "unknown") {
419
+ writeBlockedCarrier(this.handoffPath, {
420
+ tasks: [1],
421
+ phase: "fix",
422
+ blocker: `source review handoff ${findingsPath} has no valid commits.base \u2192 cannot derive the fix BASE; fix the source review and re-run cdd fix --type branch`
423
+ });
424
+ process.stderr.write(`CDD_BLOCKED: branch-fix source review missing commits.base
425
+ `);
426
+ exitWithCode(1);
427
+ }
428
+ this.fixBase = fixBase;
429
+ const prompt = templates.renderTemplate(
430
+ "fix",
431
+ {
432
+ MODE: "fix",
433
+ WORKSPACE: this.workspace,
434
+ WORKSPACE_SLUG: path.basename(this.workspace),
435
+ FINDINGS: findingsPath,
436
+ FIXED_POINT: fixBase,
437
+ BRIEF: this.opts.plan,
438
+ HANDOFF_TARGET: this.handoffPath,
439
+ REVIEW_PLAN_LINE: this.opts.plan ? `**Plan:** ${this.opts.plan}` : "",
440
+ RETURN_FORMAT: "RETURN_STDOUT_BLOCK",
441
+ HANDOFF_WRITE_GATE: templates.reviewHardGate("RETURN_STDOUT_BLOCK", this.handoffPath)
442
+ },
443
+ "cdd fix"
444
+ );
445
+ const terminationCfg = invoker.resolveTerminationConfig("review", void 0, this.workspace);
446
+ const res = await invoker.invokeCliWithRetry(
447
+ this.entry,
448
+ prompt,
449
+ { op: "fix", type: "branch" },
450
+ process.env,
451
+ this.repoRoot,
452
+ terminationCfg
453
+ );
454
+ this.agentRc = res.code;
455
+ }
456
+ /** Steps 8.8/10/10.5: agent-failure / no-handoff lanes + schema recovery (the commit-contract
457
+ * BLOCKED rewrite rides the inherited exit gate in the next step). BLOCKED carrier commits carry
458
+ * ONLY the FIX_BASE when 40-hex — a BLOCKED fix has no head yet (mirror of the former
459
+ * writeBranchFixBlocked shape). */
460
+ async schemaValidate(_hookCtx) {
461
+ await this.schemaValidateBranch({
462
+ phase: "fix",
463
+ label: "branch-fix",
464
+ reRun: "cdd fix --type branch",
465
+ commits: this.branchCarrierCommits(this.fixBase)
466
+ });
467
+ }
468
+ /** Finalize through the single finalization point (mode=fix → work-type passthrough: the
469
+ * agent-declared status stays, vetoed by the commit-contract layer just below). Task 23 ③: the
470
+ * fix round conclusion → exit (BLOCKED → 1, APPROVED/CHANGES_REQUESTED → 0) — captured here,
471
+ * emitted by the wrapper AFTER the (inherited) exit gate ran clean. */
472
+ async normalizeResult(_hookCtx) {
473
+ const finalized = await finalizeHandoff({ mode: "fix", agentHandoff: this.agentHandoff });
474
+ if (finalized.handoff && finalized.handoff !== this.agentHandoff)
475
+ writeOwnHandoff(this.handoffPath, finalized.handoff);
476
+ this.finalExitCode = finalized.exitCode;
477
+ }
478
+ }
479
+
480
+ export { BranchFixLifecycle, BranchLifecycle, BranchReviewLifecycle };