@oscaner-skills/cdd-engine 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/package.json +4 -3
  4. package/src-next/__tests__/dead-decl.guard.test.ts +39 -0
  5. package/src-next/__tests__/floor.guard.test.ts +69 -0
  6. package/src-next/__tests__/issue-body.guard.test.ts +66 -0
  7. package/src-next/__tests__/phase-suffix.guard.test.ts +72 -0
  8. package/src-next/__tests__/smoke.integration.test.ts +60 -77
  9. package/src-next/__tests__/support/strip-comments.ts +99 -0
  10. package/src-next/__tests__/zero-dep.test.ts +6 -46
  11. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +39 -21
  12. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +40 -28
  13. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +40 -23
  14. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +38 -21
  15. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +21 -6
  16. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +22 -12
  17. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +23 -8
  18. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +21 -6
  19. package/src-next/contract/__tests__/declare.test.ts +251 -12
  20. package/src-next/contract/__tests__/doc.test.ts +214 -45
  21. package/src-next/contract/__tests__/dockey.guard.test.ts +58 -0
  22. package/src-next/contract/__tests__/edge-conditions.guard.test.ts +81 -0
  23. package/src-next/contract/__tests__/frontmatter.test.ts +164 -0
  24. package/src-next/contract/__tests__/judge.test.ts +410 -172
  25. package/src-next/contract/__tests__/lint.test.ts +49 -39
  26. package/src-next/contract/__tests__/project.test.ts +60 -19
  27. package/src-next/contract/__tests__/structure-pin.test.ts +186 -0
  28. package/src-next/contract/declare.ts +179 -91
  29. package/src-next/contract/doc.ts +227 -164
  30. package/src-next/contract/frontmatter.ts +233 -0
  31. package/src-next/contract/home-extractors.ts +397 -0
  32. package/src-next/contract/invariants.ts +214 -69
  33. package/src-next/contract/judge.ts +28 -19
  34. package/src-next/contract/lint.ts +5 -41
  35. package/src-next/contract/project.ts +103 -43
  36. package/src-next/contract/skill-anatomy.ts +39 -11
  37. package/src-next/face/__tests__/board-view.test.ts +318 -115
  38. package/src-next/face/__tests__/capsule.test.ts +49 -25
  39. package/src-next/face/__tests__/channel-closure.guard.test.ts +28 -1
  40. package/src-next/face/__tests__/cli.test.ts +1091 -837
  41. package/src-next/face/__tests__/face.test.ts +5 -5
  42. package/src-next/face/__tests__/install-rows.guard.test.ts +58 -0
  43. package/src-next/face/__tests__/preview.test.ts +374 -0
  44. package/src-next/face/__tests__/projection.test.ts +5 -3
  45. package/src-next/face/__tests__/repo-root.guard.test.ts +120 -0
  46. package/src-next/face/__tests__/termination.test.ts +650 -0
  47. package/src-next/face/artifacts.ts +90 -37
  48. package/src-next/face/board-view.ts +128 -138
  49. package/src-next/face/capsule.ts +30 -16
  50. package/src-next/face/cli.ts +306 -97
  51. package/src-next/face/declare.ts +15 -18
  52. package/src-next/face/gate.ts +19 -18
  53. package/src-next/face/host.ts +6 -30
  54. package/src-next/face/lifecycle.ts +213 -188
  55. package/src-next/face/preview.ts +151 -0
  56. package/src-next/face/projection.ts +4 -1
  57. package/src-next/face/route-render.ts +39 -14
  58. package/src-next/face/termination.ts +573 -0
  59. package/src-next/face/words.ts +20 -2
  60. package/src-next/infra/__tests__/infra.test.ts +49 -3
  61. package/src-next/infra/__tests__/root.test.ts +56 -0
  62. package/src-next/infra/doc-roots.ts +29 -0
  63. package/src-next/infra/root.ts +73 -0
  64. package/src-next/infra/runtime.ts +12 -65
  65. package/src-next/infra/workspace.ts +95 -5
  66. package/src-next/render/__tests__/render.test.ts +92 -41
  67. package/src-next/render/__tests__/skeleton.test.ts +282 -64
  68. package/src-next/render/issue-body.ts +5 -2
  69. package/src-next/render/skeleton.ts +155 -90
  70. package/src-next/render/templates.ts +51 -56
  71. package/src-next/session/__tests__/graph.test.ts +11 -4
  72. package/src-next/session/__tests__/ledger.test.ts +3 -2
  73. package/src-next/session/__tests__/next.test.ts +100 -8
  74. package/src-next/session/__tests__/preflight.test.ts +79 -25
  75. package/src-next/session/__tests__/round-naming.test.ts +142 -0
  76. package/src-next/session/__tests__/run.test.ts +140 -128
  77. package/src-next/session/__tests__/wave.test.ts +11 -4
  78. package/src-next/session/ledger.ts +96 -24
  79. package/src-next/session/next.ts +116 -15
  80. package/src-next/session/preflight.ts +41 -10
  81. package/src-next/session/round-naming.ts +84 -0
  82. package/src-next/session/run.ts +24 -20
  83. package/templates/report/issue-body.json +0 -46
  84. package/src-next/face/__tests__/sync-runner.test.ts +0 -70
@@ -106,11 +106,11 @@ describe("the capsule byte pin — the single output face", () => {
106
106
  expect(
107
107
  capsule.emit("CHANGES_REQUESTED", "1", "/h.json", {
108
108
  kind: "fix",
109
- findings: "tasks-1-review-1.json",
109
+ reviews: "tasks-1-review-1.json",
110
110
  }),
111
111
  ).toEqual([
112
112
  "status: CHANGES_REQUESTED · blocker: 1 · handoff: /h.json",
113
- `next: fix --findings tasks-1-review-1.json ${FIX_READBACK_SUFFIX}`,
113
+ `next: fix --reviews tasks-1-review-1.json ${FIX_READBACK_SUFFIX}`,
114
114
  ]);
115
115
  // a fix route without its input renders the bare classifier
116
116
  expect(capsule.emit("CHANGES_REQUESTED", "1", "/h.json", { kind: "fix" })).toEqual([
@@ -138,18 +138,18 @@ describe("the capsule byte pin — the single output face", () => {
138
138
  "status: REVIEW_FIX · blocker: 0 · handoff: /h.json",
139
139
  "next: review --type wave --tasks 1,2 --plan docs/kairos/plans/p.md",
140
140
  ]);
141
- // the one-way fix hop — `fix --type wave --tasks {tasks} --plan <p> --findings <f>`
141
+ // the one-way fix hop — `fix --type wave --tasks {tasks} --plan <p> --reviews <f>`
142
142
  expect(
143
143
  capsule.emit(
144
144
  "CHANGES_REQUESTED",
145
145
  "1",
146
146
  "/h.json",
147
- { kind: "fix", findings: "tasks-1,2-review-1.json" },
147
+ { kind: "fix", reviews: "tasks-1,2-review-1.json" },
148
148
  target,
149
149
  ),
150
150
  ).toEqual([
151
151
  "status: CHANGES_REQUESTED · blocker: 1 · handoff: /h.json",
152
- `next: fix --type wave --tasks 1,2 --plan docs/kairos/plans/p.md --findings tasks-1,2-review-1.json ${FIX_READBACK_SUFFIX}`,
152
+ `next: fix --type wave --tasks 1,2 --plan docs/kairos/plans/p.md --reviews tasks-1,2-review-1.json ${FIX_READBACK_SUFFIX}`,
153
153
  ]);
154
154
  // the other target types render their discriminator arg — branch (the
155
155
  // workspace --plan only — the review judges the live tree, no range rides the
@@ -0,0 +1,58 @@
1
+ // packages/cdd-engine/src-next/face/__tests__/install-rows.guard.test.ts
2
+ // T13 ⑦ (spec §3.3 ⑦) — the INSTALL_ROWS ↔ README gate. `face/host.ts`'s
3
+ // `INSTALL_ROWS` docstring declared "the README upstream dependency table renders
4
+ // from these rows", but no consumer actually read them for the README — a vacuous
5
+ // claim. This gate makes the claim true: it pins the `packages/kairos/README.md`
6
+ // upstream dependency table (and its zh mirror) to `INSTALL_ROWS` —
7
+ // · the table's row key set equals the `INSTALL_ROWS` key set;
8
+ // · each row's Claude Code cell equals `INSTALL_ROWS[key].join(";")` (the declared
9
+ // install banners, semicolon-joined — the README's cell shape).
10
+ // A README install-command drift fails here, never silently.
11
+ // Domicile: engine suite (§3.6 — the engine-internal ⑦ fact, single-sourced at host.ts).
12
+
13
+ import { readFileSync } from "node:fs";
14
+ import { fileURLToPath } from "node:url";
15
+ import { describe, expect, it } from "vitest";
16
+
17
+ import { INSTALL_ROWS } from "../host.ts";
18
+
19
+ const README_ROOT = fileURLToPath(new URL("../../../../kairos/", import.meta.url));
20
+ const read = (rel: string): string => readFileSync(`${README_ROOT}/${rel}`, "utf8");
21
+
22
+ /** The upstream dependency table's rows keyed by package name — the Claude Code cell
23
+ * (2nd column) of each `| <pkg> | … | … | … |` row, backticks stripped. The header +
24
+ * separator rows are skipped (their first cell is not a registered package key). */
25
+ const tableRows = (src: string): Map<string, string> => {
26
+ const rows = new Map<string, string>();
27
+ for (const line of src.split("\n")) {
28
+ const cells = line.split("|").map((cell) => cell.trim());
29
+ // A `| a | b | c | d |` row splits into ["", "a", "b", "c", "d", ""].
30
+ if (cells.length < 6) continue;
31
+ const key = cells[1]!;
32
+ if (!(key in INSTALL_ROWS)) continue;
33
+ rows.set(key, cells[2]!.replace(/`/g, ""));
34
+ }
35
+ return rows;
36
+ };
37
+
38
+ describe("INSTALL_ROWS ↔ the kairos README upstream dependency table (spec §3.3 ⑦)", () => {
39
+ it("the declared docstring claim holds — the table's key set equals the INSTALL_ROWS key set", () => {
40
+ for (const rel of ["README.md", "README.zh-CN.md"]) {
41
+ const keys = [...tableRows(read(rel)).keys()].sort();
42
+ expect(keys, `${rel}: the install table's package rows must match INSTALL_ROWS`).toEqual(
43
+ Object.keys(INSTALL_ROWS).sort(),
44
+ );
45
+ }
46
+ });
47
+
48
+ it("each table row's Claude Code cell equals the INSTALL_ROWS banners (semicolon-joined)", () => {
49
+ for (const rel of ["README.md", "README.zh-CN.md"]) {
50
+ const rows = tableRows(read(rel));
51
+ for (const [key, banners] of Object.entries(INSTALL_ROWS)) {
52
+ expect(rows.get(key), `${rel}: row "${key}" renders from INSTALL_ROWS["${key}"]`).toBe(
53
+ banners.join(";"),
54
+ );
55
+ }
56
+ }
57
+ });
58
+ });
@@ -0,0 +1,374 @@
1
+ // packages/cdd-engine/src-next/face/__tests__/preview.test.ts
2
+ // P11 T5 — the `--dry-run` preview pins. Two faces:
3
+ //
4
+ // · the renderer (face/preview.ts) — the §3.3 five-row block, byte for byte, over
5
+ // the four target faces; the `child:` row's detected-host and no-host forms.
6
+ // The renderer touches no disk for these (the names are pure path arithmetic),
7
+ // so the scene is constructed inline and the env is injected.
8
+ // · the CLI face — the preview's zero-write semantics on a real fixture repo
9
+ // (`.kairos/` absent, `git status --porcelain` byte-identical, no round
10
+ // consumed), the pre-flight refusal face's identity with the real run's, and
11
+ // the flag's narrowed scope (exit 2 off the three work verbs).
12
+
13
+ import { spawnSync } from "node:child_process";
14
+ import {
15
+ existsSync,
16
+ mkdirSync,
17
+ mkdtempSync,
18
+ readFileSync,
19
+ realpathSync,
20
+ rmSync,
21
+ writeFileSync,
22
+ } from "node:fs";
23
+ import { tmpdir } from "node:os";
24
+ import path from "node:path";
25
+ import { afterEach, describe, expect, it } from "vitest";
26
+ import { ConfigLoader } from "../../infra/config.ts";
27
+ import { Workspace, WorkspaceRoot } from "../../infra/workspace.ts";
28
+ import { Ledger } from "../../session/ledger.ts";
29
+ import type { DispatchOutcome, OpenFrame } from "../../session/run.ts";
30
+ import type { CliIo, CliOptions, DispatchScene } from "../cli.ts";
31
+ import { Cli } from "../cli.ts";
32
+ import { Preview } from "../preview.ts";
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // the renderer's inline scene (no disk)
36
+ // ---------------------------------------------------------------------------
37
+
38
+ const ROOT = "/repo";
39
+ const WORKSPACE = new Workspace(new WorkspaceRoot(ROOT, ".kairos/cdd"), "p3");
40
+
41
+ /** The scene the preview reads — the same DispatchScene shape the lifecycle
42
+ * dispatch reads (one scene shape, never a second). */
43
+ const scene = (over: Partial<DispatchScene> = {}): DispatchScene => ({
44
+ workspace: WORKSPACE,
45
+ ledger: new Ledger(WORKSPACE, new ConfigLoader()),
46
+ planPath: path.join(ROOT, "docs", "kairos", "plans", "p3.md"),
47
+ briefPath: null,
48
+ ...over,
49
+ });
50
+
51
+ /** A frame from the wave-review shape; `over` supplies the face. */
52
+ const frame = (over: Partial<OpenFrame> = {}): OpenFrame => ({
53
+ type: "wave",
54
+ phase: "review",
55
+ round: 1,
56
+ target: { kind: "wave", tasks: [1] },
57
+ params: { tasks: "1", round: 1 },
58
+ key: "1",
59
+ ...over,
60
+ });
61
+
62
+ /** A preview over the inline scene with a pinned env — `{}` detects no host, so
63
+ * the test process's own markers never leak into the `child:` row. */
64
+ const preview = (env: Record<string, string | undefined> = {}): Preview =>
65
+ new Preview({ scene: scene(), env });
66
+
67
+ describe("Preview — the §3.3 five-row block", () => {
68
+ it("renders the wave review block byte for byte", () => {
69
+ expect(preview().render("review", frame())).toEqual([
70
+ "cdd review: preview (no repo changes)",
71
+ " step: review round 1 — wave 1",
72
+ " reads: .kairos/cdd/p3/tasks-1-brief.md (would re-render from the current plan)",
73
+ " would write: .kairos/cdd/p3/tasks-1-review-1.json · .kairos/cdd/p3/tasks-1-review-1-report.md",
74
+ ' would record: progress.waves["1"].rounds.review += [1] · reviewedRevision(brief)',
75
+ " child: (no host detected — real run would BLOCK)",
76
+ ]);
77
+ });
78
+
79
+ it("names the work face's full prescribed write set — carrier, report and test evidence", () => {
80
+ const lines = preview().render(
81
+ "implement",
82
+ frame({
83
+ phase: "implement",
84
+ round: 1,
85
+ target: { kind: "wave", tasks: [2, 5] },
86
+ params: { tasks: "2,5" },
87
+ key: "2,5",
88
+ }),
89
+ );
90
+ expect(lines[1]).toBe(" step: implement round 1 — wave 2,5");
91
+ expect(lines[3]).toBe(
92
+ " would write: .kairos/cdd/p3/tasks-2,5-implement.json · .kairos/cdd/p3/tasks-2,5-implement-report.md · .kairos/cdd/p3/tasks-2,5-test-evidence.json",
93
+ );
94
+ // the implement round is never a review: no reviewed-revision write-back leg
95
+ expect(lines[4]).toBe(' would record: progress.waves["2,5"].rounds.implement += [1]');
96
+ });
97
+
98
+ it("renders the spec line — the judged document as the read input, no brief re-render", () => {
99
+ const lines = preview().render(
100
+ "review",
101
+ frame({
102
+ type: "spec",
103
+ round: 1,
104
+ target: { kind: "spec", doc: path.join(ROOT, "docs", "kairos", "specs", "p3-design.md") },
105
+ params: { round: 1 },
106
+ key: "spec",
107
+ }),
108
+ );
109
+ expect(lines[1]).toBe(" step: review round 1 — spec");
110
+ expect(lines[2]).toBe(" reads: docs/kairos/specs/p3-design.md");
111
+ expect(lines[3]).toBe(
112
+ " would write: .kairos/cdd/p3/spec-review-1.json · .kairos/cdd/p3/spec-review-1-report.md",
113
+ );
114
+ expect(lines[4]).toBe(
115
+ ' would record: progress.waves["spec"].rounds.review += [1] · reviewedRevision(doc)',
116
+ );
117
+ });
118
+
119
+ it("renders the branch line — its review binds no reviewed revision (the live-tree audit)", () => {
120
+ const lines = preview().render(
121
+ "review",
122
+ frame({
123
+ type: "branch",
124
+ phase: "branch-review",
125
+ round: 2,
126
+ target: { kind: "branch" },
127
+ params: { round: 2 },
128
+ key: "branch",
129
+ }),
130
+ );
131
+ expect(lines[1]).toBe(" step: branch-review round 2 — branch");
132
+ expect(lines[2]).toBe(" reads: docs/kairos/plans/p3.md");
133
+ expect(lines[3]).toBe(
134
+ " would write: .kairos/cdd/p3/branch-review-2.json · .kairos/cdd/p3/branch-review-2-report.md",
135
+ );
136
+ expect(lines[4]).toBe(' would record: progress.waves["branch"].rounds.branch-review += [2]');
137
+ });
138
+
139
+ it("the child row names the detected host id + the row's invoke string, never the detect marker", () => {
140
+ const lines = new Preview({
141
+ scene: scene(),
142
+ env: { CURSOR_TRACE_ID: "trace" },
143
+ }).render("review", frame());
144
+ // the leading token is the HOST ID ("cursor"); the harness row's binary name
145
+ // (the `cli` column) is a separate fact and never rides this row
146
+ expect(lines[5]).toBe(" child: cursor --print --output-format text --force");
147
+ });
148
+ });
149
+
150
+ // ---------------------------------------------------------------------------
151
+ // the CLI face (a hermetic fixture repo)
152
+ // ---------------------------------------------------------------------------
153
+
154
+ /** The captured io — the CLI's stdout/stderr seam (never the process). */
155
+ class CaptureIo implements CliIo {
156
+ stdoutText = "";
157
+ stderrText = "";
158
+ stdout(text: string): void {
159
+ this.stdoutText += text;
160
+ }
161
+ stderr(text: string): void {
162
+ this.stderrText += text;
163
+ }
164
+ }
165
+
166
+ interface CliFixture {
167
+ command: Cli;
168
+ io: CaptureIo;
169
+ repoRoot: string;
170
+ cleanup: () => void;
171
+ }
172
+
173
+ /** The process cwd before any fixture chdir — restored after every test (the
174
+ * engine resolves the repo root from the working directory). */
175
+ const ORIGINAL_CWD = process.cwd();
176
+ afterEach(() => {
177
+ process.chdir(ORIGINAL_CWD);
178
+ });
179
+
180
+ /** A hermetic CLI fixture — a fresh temp repo, the io captured, the cwd isolated
181
+ * into the temp root (taken through `realpathSync`: the engine's git-top-level
182
+ * resolution returns the REAL path, so the fixture must speak the same basis). */
183
+ const fixture = (opts: CliOptions = {}): CliFixture => {
184
+ const repoRoot = realpathSync(mkdtempSync(path.join(tmpdir(), "preview-")));
185
+ process.chdir(repoRoot);
186
+ const io = new CaptureIo();
187
+ const command = Cli.create({ io, ...opts });
188
+ return {
189
+ command,
190
+ io,
191
+ repoRoot,
192
+ cleanup: () => {
193
+ process.chdir(ORIGINAL_CWD);
194
+ rmSync(repoRoot, { recursive: true, force: true });
195
+ },
196
+ };
197
+ };
198
+
199
+ /** Init a git repo with one commit and a keep-out .gitignore (the dispatch's own
200
+ * `.kairos` writes and the fixture's synthetic docs stay out of the tree, so the
201
+ * clean-tree pre-flight gate judges the fixture's own edits alone). */
202
+ const gitInit = (repoRoot: string): void => {
203
+ spawnSync("git", ["init", "-q"], { cwd: repoRoot });
204
+ spawnSync("git", ["config", "user.email", "preview@test"], { cwd: repoRoot });
205
+ spawnSync("git", ["config", "user.name", "preview-test"], { cwd: repoRoot });
206
+ writeFileSync(path.join(repoRoot, ".gitignore"), ".kairos\n/docs/\n", "utf8");
207
+ writeFileSync(path.join(repoRoot, "seed.txt"), "seed\n", "utf8");
208
+ spawnSync("git", ["add", "-A"], { cwd: repoRoot });
209
+ spawnSync("git", ["commit", "-q", "-m", "seed"], { cwd: repoRoot });
210
+ };
211
+
212
+ /** A one-task plan document — the wave face's dispatch input. */
213
+ const planFor = (repoRoot: string): string => {
214
+ const file = path.join(repoRoot, "docs", "kairos", "plans", "p3.md");
215
+ mkdirSync(path.dirname(file), { recursive: true });
216
+ writeFileSync(
217
+ file,
218
+ [
219
+ "---",
220
+ "title: Test Plan",
221
+ "doc-type: plan",
222
+ "version: v1.0",
223
+ "date: 2026-10-09",
224
+ "spec: docs/kairos/specs/p3-design.md",
225
+ "parent-program: docs/kairos/specs/p3-overall.md",
226
+ "parent-version: v1.0",
227
+ "---",
228
+ "",
229
+ "## Constraints",
230
+ "",
231
+ "- delta",
232
+ "",
233
+ "### Task 1: task 1",
234
+ "- **Objective**: objective",
235
+ "- **Files**: `a.ts`",
236
+ "- **Consumes**: x",
237
+ "- **Produces**: y",
238
+ "- **Steps**:",
239
+ " - step — checkable: green",
240
+ "- **Acceptance**: ok",
241
+ "- **DependsOn**: none",
242
+ "",
243
+ ].join("\n"),
244
+ "utf8",
245
+ );
246
+ return file;
247
+ };
248
+
249
+ const porcelain = (repoRoot: string): string =>
250
+ spawnSync("git", ["status", "--porcelain"], { cwd: repoRoot }).stdout.toString();
251
+
252
+ const progressPath = (repoRoot: string): string =>
253
+ path.join(repoRoot, ".kairos", "cdd", "p3", "progress.json");
254
+
255
+ describe("cdd <verb> --dry-run — the read-only preview", () => {
256
+ it("writes nothing: `.kairos/` stays absent and the tree is byte-identical", async () => {
257
+ const { command, io, repoRoot, cleanup } = fixture();
258
+ try {
259
+ gitInit(repoRoot);
260
+ const plan = planFor(repoRoot);
261
+ const before = porcelain(repoRoot);
262
+ const code = await command.runArgv([
263
+ "implement",
264
+ "--tasks",
265
+ "1",
266
+ "--plan",
267
+ plan,
268
+ "--dry-run",
269
+ ]);
270
+ expect(code).toBe(0);
271
+ expect(io.stdoutText.startsWith("cdd implement: preview (no repo changes)\n")).toBe(true);
272
+ for (const label of ["step:", "reads:", "would write:", "would record:", "child:"])
273
+ expect(io.stdoutText).toContain(` ${label} `);
274
+ // a preview fabricates no conclusion and no next hop
275
+ expect(io.stdoutText).not.toContain("status:");
276
+ expect(io.stdoutText).not.toContain("next:");
277
+ expect(existsSync(path.join(repoRoot, ".kairos"))).toBe(false);
278
+ expect(porcelain(repoRoot)).toBe(before);
279
+ } finally {
280
+ cleanup();
281
+ }
282
+ });
283
+
284
+ it("consumes no round — the same line's real review still dispatches afterwards", async () => {
285
+ const dispatch = async (): Promise<DispatchOutcome> => ({ status: "APPROVED", findings: [] });
286
+ const { command, cleanup, repoRoot } = fixture({ dispatch });
287
+ try {
288
+ gitInit(repoRoot);
289
+ const plan = planFor(repoRoot);
290
+ expect(await command.runArgv(["implement", "--tasks", "1", "--plan", plan])).toBe(0);
291
+ // the preview of the next round: no write, no ledger row
292
+ expect(
293
+ await command.runArgv([
294
+ "review",
295
+ "--type",
296
+ "wave",
297
+ "--tasks",
298
+ "1",
299
+ "--plan",
300
+ plan,
301
+ "--dry-run",
302
+ ]),
303
+ ).toBe(0);
304
+ expect(existsSync(path.join(repoRoot, ".kairos", "cdd", "p3", "tasks-1-review-1.json"))).toBe(
305
+ false,
306
+ );
307
+ expect(JSON.parse(readFileSync(progressPath(repoRoot), "utf8")).waves).not.toContainEqual(
308
+ expect.objectContaining({ rounds: { implement: [1], review: [1] } }),
309
+ );
310
+ // the real review of the SAME command dispatches immediately (nothing consumed)
311
+ expect(
312
+ await command.runArgv(["review", "--type", "wave", "--tasks", "1", "--plan", plan]),
313
+ ).toBe(0);
314
+ const progress = JSON.parse(readFileSync(progressPath(repoRoot), "utf8")) as {
315
+ waves: { wave: string; rounds?: Record<string, number[]> }[];
316
+ };
317
+ expect(progress.waves.find((row) => row.wave === "1")?.rounds).toEqual({
318
+ implement: [1],
319
+ review: [1],
320
+ });
321
+ } finally {
322
+ cleanup();
323
+ }
324
+ });
325
+
326
+ it("a refused pre-flight renders the real run's refusal face verbatim and prints no preview", async () => {
327
+ const { command, io, repoRoot, cleanup } = fixture();
328
+ try {
329
+ gitInit(repoRoot);
330
+ const plan = planFor(repoRoot);
331
+ writeFileSync(path.join(repoRoot, "dirty.txt"), "dirty\n", "utf8");
332
+ const argv = ["implement", "--tasks", "1", "--plan", plan];
333
+ expect(await command.runArgv([...argv, "--dry-run"])).toBe(1);
334
+ const previewStderr = io.stderrText;
335
+ expect(io.stdoutText).not.toContain("preview");
336
+ io.stdoutText = "";
337
+ io.stderrText = "";
338
+ expect(await command.runArgv(argv)).toBe(1);
339
+ expect(io.stderrText).toBe(previewStderr);
340
+ } finally {
341
+ cleanup();
342
+ }
343
+ });
344
+
345
+ it("is scoped to the three work verbs — every pure command rejects the flag (exit 2)", async () => {
346
+ const { command, io, cleanup } = fixture();
347
+ try {
348
+ const cases: readonly (readonly string[])[] = [
349
+ ["schema", "get", "plan", "--dry-run"],
350
+ ["base", "get", "--plan", "docs/x.md", "--dry-run"],
351
+ [
352
+ "base",
353
+ "set",
354
+ "--plan",
355
+ "docs/x.md",
356
+ "--base",
357
+ "main",
358
+ "--source",
359
+ "plan-field",
360
+ "--dry-run",
361
+ ],
362
+ ["issue", "render", "--dry-run"],
363
+ ["board", "p3", "--dry-run"],
364
+ ];
365
+ for (const argv of cases) {
366
+ io.stderrText = "";
367
+ expect(await command.runArgv([...argv])).toBe(2);
368
+ expect(io.stderrText).toContain("--dry-run previews the next dispatch step");
369
+ }
370
+ } finally {
371
+ cleanup();
372
+ }
373
+ });
374
+ });
@@ -68,12 +68,14 @@ describe("CommandTreeBuilder — the declaration projection (the constructor is
68
68
  it("projects the review surface — every declared key option, --type as a requiredOption", () => {
69
69
  const { program } = new CommandTreeBuilder();
70
70
  const review = commandOf(program, "review");
71
- for (const key of ["--type", "--tasks", "--plan", "--spec", "--round", "--root"]) {
71
+ for (const key of ["--type", "--tasks", "--plan", "--spec", "--round"]) {
72
72
  expect(
73
73
  review.options.some((option) => option.flags.startsWith(key)),
74
74
  `review declares ${key}`,
75
75
  ).toBe(true);
76
76
  }
77
+ // `--root` is retired (T2 · §2.5) — the review node no longer declares it.
78
+ expect(review.options.some((option) => option.flags.startsWith("--root"))).toBe(false);
77
79
  // the branch range flags retired with the commit-sha surface (P7)
78
80
  expect(review.options.some((option) => option.flags.startsWith("--base"))).toBe(false);
79
81
  expect(review.options.some((option) => option.flags.startsWith("--head"))).toBe(false);
@@ -214,7 +216,7 @@ describe("the preAction conditional-required groups (§4.2 · REQUIRED_GROUPS)",
214
216
  ).not.toThrow();
215
217
  });
216
218
 
217
- it("rejects fix --type branch without --findings (the fix branch face)", () => {
219
+ it("rejects fix --type branch without --reviews (the fix branch face)", () => {
218
220
  const { program } = new CommandTreeBuilder();
219
221
  commandOf(program, "fix").action(() => undefined);
220
222
  const { code, message } = commanderError(() =>
@@ -223,7 +225,7 @@ describe("the preAction conditional-required groups (§4.2 · REQUIRED_GROUPS)",
223
225
  expect(code).toBe("commander.invalidArgument");
224
226
  // the branch fix carries both its findings carrier and the --plan workspace
225
227
  // identity (BranchRef retired — the plan is the branch line's identity · §2.3)
226
- expect(message).toContain("--findings --plan required when --type branch");
228
+ expect(message).toContain("--reviews --plan required when --type branch");
227
229
  });
228
230
 
229
231
  it("rejects review --type branch without --plan (the branch review face)", () => {
@@ -0,0 +1,120 @@
1
+ // packages/cdd-engine/src-next/face/__tests__/repo-root.guard.test.ts
2
+ // P9 T7 (spec §2.9) — the STRUCTURAL pin. It guards the conversion point, not
3
+ // the spawn: the engine production code must read the working directory exactly
4
+ // ONCE and resolve it to the repo root exactly ONCE. The historical lesson is
5
+ // that a single source + a single conversion point alone did not hold — the pin
6
+ // was dropped alongside them, so a stray second `process.cwd()` (or a second
7
+ // repo-root conversion) could re-seam the resolution silently. This guard fails
8
+ // the moment a second site appears.
9
+ //
10
+ // The pin stands apart from the BEHAVIOR pin (cli.test.ts's spawn-cwd behavior
11
+ // pin — the child is constructed with `call.cwd === repoRoot`): the structural
12
+ // pin guards the conversion point (§2.4/§2.9), the behavior pin guards the
13
+ // spawn cwd — two different facts, two separate pins.
14
+ //
15
+ // The scan reads the engine's OWN source face (the src-next production tree,
16
+ // `__tests__/` excluded — test fixtures spawn with their own `cwd` argv and are
17
+ // not production conversion points). Comments are stripped before the count so a
18
+ // docstring mentioning the symbol never builds a hit; string literals are NOT
19
+ // stripped (a `process.cwd()` inside a string would be a real defect). The
20
+ // stripper (shared with the retired-plane guard — `__tests__/support/strip-comments
21
+ // .ts`, F4) is string/template/regex-aware so a `//` inside a string, or a
22
+ // backtick-bearing regex literal, never truncates or desyncs the scan.
23
+ //
24
+ // Zero module-level bare functions — the walk/count helpers are `const`
25
+ // (the plan's zero-`function`-declaration discipline).
26
+
27
+ import { readdirSync, readFileSync } from "node:fs";
28
+ import path from "node:path";
29
+ import { fileURLToPath } from "node:url";
30
+ import { describe, expect, it } from "vitest";
31
+ import { stripComments } from "../../__tests__/support/strip-comments.ts";
32
+
33
+ /** The src-next plane root — the engine's own source face (the scan set). */
34
+ const SRC_ROOT = fileURLToPath(new URL("../../", import.meta.url));
35
+
36
+ /** The two tokens the structural pin counts, each pinned to exactly ONE hit:
37
+ * the working-directory read (`process.cwd()`) and the root conversion (the
38
+ * `.topLevel(` member-call form — receiver-agnostic, so a conversion through a
39
+ * renamed or destructured receiver still builds a hit; the method DEFINITION
40
+ * `async topLevel(` has no leading dot and stays outside the count). */
41
+ const PINNED = [
42
+ { token: "process.cwd()", label: "the working-directory read" },
43
+ { token: ".topLevel(", label: "the repo-root conversion" },
44
+ ] as const;
45
+
46
+ /** Walk the production tree collecting `.ts` files under `__tests__` excluded
47
+ * (the test plane is not the production conversion face). */
48
+ const collectProductionTs = (dir: string, out: string[]): void => {
49
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
50
+ if (entry.isDirectory()) {
51
+ if (entry.name === "__tests__") continue;
52
+ collectProductionTs(path.join(dir, entry.name), out);
53
+ } else if (entry.name.endsWith(".ts")) {
54
+ out.push(path.join(dir, entry.name));
55
+ }
56
+ }
57
+ };
58
+
59
+ /** Every `file:line` hit of one token over the production face (comments stripped). */
60
+ const hitsOf = (token: string): string[] => {
61
+ const files: string[] = [];
62
+ collectProductionTs(SRC_ROOT, files);
63
+ const hits: string[] = [];
64
+ for (const file of files) {
65
+ const lines = stripComments(readFileSync(file, "utf8")).split("\n");
66
+ for (let index = 0; index < lines.length; index += 1) {
67
+ if (lines[index]!.includes(token)) hits.push(`${path.relative(SRC_ROOT, file)}:${index + 1}`);
68
+ }
69
+ }
70
+ return hits;
71
+ };
72
+
73
+ describe("the structural pin — the engine resolves the repo root through exactly one conversion point (spec §2.9)", () => {
74
+ for (const { token, label } of PINNED) {
75
+ it(`${label} occurs exactly once on the engine production face — ${token}`, () => {
76
+ const hits = hitsOf(token);
77
+ // The pin is a count of ONE: zero hits would strand the resolution (no
78
+ // conversion at all), a second hit would re-seam it. Either way the guard
79
+ // is the machine check the spec's single-conversion invariant rides on.
80
+ expect(hits, `"${token}" must occur exactly once (found ${hits.length})`).toHaveLength(1);
81
+ });
82
+ }
83
+ });
84
+
85
+ describe("the structural pin's comment stripper — strings are counted, comments are not", () => {
86
+ it("counts a token inside a string literal but not one inside a line comment", () => {
87
+ // The header's contract, pinned behaviorally: a symbol inside a string is a
88
+ // real occurrence (the defect the guard exists to catch); a comment is not.
89
+ expect(stripComments('const a = "process.cwd()";').includes("process.cwd()")).toBe(true);
90
+ expect(stripComments("// process.cwd()").includes("process.cwd()")).toBe(false);
91
+ expect(stripComments("/* .topLevel( in prose */").includes(".topLevel(")).toBe(false);
92
+ });
93
+
94
+ it("does not let a `//` inside a string literal truncate the line (a real token after it still counts)", () => {
95
+ // The regression the stripper's string-awareness closes: a naive `//`-strip
96
+ // would drop everything after the in-string `//`, silently missing the real
97
+ // conversion call on the same line.
98
+ const line = 'const note = "see // the cwd"; const c = process.cwd();';
99
+ expect(stripComments(line).includes("process.cwd()")).toBe(true);
100
+ });
101
+
102
+ it("does not let a backtick-bearing regex literal desync the scan (later real tokens still count)", () => {
103
+ // A non-regex-aware tracker reads the backtick inside `/`+[^`]*`/` as a
104
+ // template-literal opener and swallows the rest of the file as a string,
105
+ // falsely reporting following comment tokens (or missing real ones).
106
+ const source = [
107
+ "const r = /`+[^`\\n]*`+/g;",
108
+ "// process.cwd()",
109
+ "const c = process.cwd();",
110
+ ].join("\n");
111
+ const stripped = stripComments(source);
112
+ expect(stripped.split("\n")[1]!.includes("process.cwd()")).toBe(false);
113
+ expect(stripped.split("\n")[2]!.includes("process.cwd()")).toBe(true);
114
+ });
115
+
116
+ it("preserves line count so a reported hit line stays true", () => {
117
+ const source = ["const a = 1;", "/* x", "y */", "// z", "const b = 2;"].join("\n");
118
+ expect(stripComments(source).split("\n")).toHaveLength(5);
119
+ });
120
+ });