@oscaner-skills/cdd-engine 1.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/README.md +11 -10
  2. package/README.zh-CN.md +11 -10
  3. package/package.json +16 -22
  4. package/src-next/__tests__/bin.test.ts +128 -0
  5. package/src-next/__tests__/dead-decl.guard.test.ts +39 -0
  6. package/src-next/__tests__/floor.guard.test.ts +69 -0
  7. package/src-next/__tests__/issue-body.guard.test.ts +66 -0
  8. package/src-next/__tests__/phase-suffix.guard.test.ts +72 -0
  9. package/src-next/__tests__/smoke.integration.test.ts +185 -0
  10. package/src-next/__tests__/support/strip-comments.ts +99 -0
  11. package/src-next/__tests__/zero-dep.test.ts +94 -0
  12. package/src-next/bin.ts +61 -0
  13. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +256 -0
  14. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +165 -0
  15. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +190 -0
  16. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +106 -0
  17. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +240 -0
  18. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +165 -0
  19. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +190 -0
  20. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +100 -0
  21. package/src-next/contract/__tests__/declare.test.ts +481 -0
  22. package/src-next/contract/__tests__/doc.test.ts +527 -0
  23. package/src-next/contract/__tests__/dockey.guard.test.ts +58 -0
  24. package/src-next/contract/__tests__/edge-conditions.guard.test.ts +81 -0
  25. package/src-next/contract/__tests__/frontmatter.test.ts +164 -0
  26. package/src-next/contract/__tests__/judge.test.ts +1111 -0
  27. package/src-next/contract/__tests__/lint.test.ts +324 -0
  28. package/src-next/contract/__tests__/project.test.ts +460 -0
  29. package/src-next/contract/__tests__/structure-pin.test.ts +186 -0
  30. package/src-next/contract/__tests__/translate.test.ts +96 -0
  31. package/src-next/contract/declare.ts +1071 -0
  32. package/src-next/contract/doc.ts +816 -0
  33. package/src-next/contract/frontmatter.ts +233 -0
  34. package/src-next/contract/home-extractors.ts +397 -0
  35. package/src-next/contract/invariants.ts +1413 -0
  36. package/src-next/contract/judge.ts +151 -0
  37. package/src-next/contract/lint.ts +239 -0
  38. package/src-next/contract/project.ts +656 -0
  39. package/src-next/contract/skill-anatomy.ts +301 -0
  40. package/src-next/contract/translate.ts +113 -0
  41. package/src-next/face/__tests__/board-view.test.ts +1151 -0
  42. package/src-next/face/__tests__/capsule.test.ts +300 -0
  43. package/src-next/face/__tests__/channel-closure.guard.test.ts +129 -0
  44. package/src-next/face/__tests__/cli.test.ts +4897 -0
  45. package/src-next/face/__tests__/face.test.ts +289 -0
  46. package/src-next/face/__tests__/graph-view.test.ts +61 -0
  47. package/src-next/face/__tests__/host.test.ts +24 -0
  48. package/src-next/face/__tests__/install-rows.guard.test.ts +58 -0
  49. package/src-next/face/__tests__/negation.ts +6 -0
  50. package/src-next/face/__tests__/preview.test.ts +374 -0
  51. package/src-next/face/__tests__/projection.test.ts +303 -0
  52. package/src-next/face/__tests__/repo-root.guard.test.ts +120 -0
  53. package/src-next/face/__tests__/termination.test.ts +650 -0
  54. package/src-next/face/__tests__/words.guard.test.ts +93 -0
  55. package/src-next/face/artifacts.ts +248 -0
  56. package/src-next/face/board-view.ts +652 -0
  57. package/src-next/face/capsule.ts +163 -0
  58. package/src-next/face/cli.ts +1028 -0
  59. package/src-next/face/declare.ts +323 -0
  60. package/src-next/face/gate.ts +171 -0
  61. package/src-next/face/graph-view.ts +74 -0
  62. package/src-next/face/host.ts +302 -0
  63. package/src-next/face/lifecycle.ts +725 -0
  64. package/src-next/face/preview.ts +151 -0
  65. package/src-next/face/projection.ts +285 -0
  66. package/src-next/face/route-render.ts +185 -0
  67. package/src-next/face/termination.ts +573 -0
  68. package/src-next/face/words.ts +314 -0
  69. package/src-next/infra/__tests__/infra.test.ts +333 -0
  70. package/src-next/infra/__tests__/root.test.ts +56 -0
  71. package/src-next/infra/config.ts +42 -0
  72. package/src-next/infra/doc-roots.ts +29 -0
  73. package/src-next/infra/git.ts +39 -0
  74. package/src-next/infra/process.ts +34 -0
  75. package/src-next/infra/root.ts +73 -0
  76. package/src-next/infra/runtime.ts +132 -0
  77. package/src-next/infra/workspace.ts +322 -0
  78. package/src-next/render/__tests__/render.test.ts +550 -0
  79. package/src-next/render/__tests__/skeleton.test.ts +684 -0
  80. package/src-next/render/brief.ts +121 -0
  81. package/src-next/render/issue-body.ts +162 -0
  82. package/src-next/render/skeleton.ts +502 -0
  83. package/src-next/render/templates.ts +645 -0
  84. package/src-next/session/__tests__/graph.test.ts +277 -0
  85. package/src-next/session/__tests__/handoff-plane.guard.test.ts +48 -0
  86. package/src-next/session/__tests__/handoff-schema.test.ts +310 -0
  87. package/src-next/session/__tests__/ledger.test.ts +745 -0
  88. package/src-next/session/__tests__/next.test.ts +460 -0
  89. package/src-next/session/__tests__/preflight.test.ts +545 -0
  90. package/src-next/session/__tests__/round-naming.test.ts +142 -0
  91. package/src-next/session/__tests__/run.test.ts +1026 -0
  92. package/src-next/session/__tests__/wave-line-phase.guard.test.ts +49 -0
  93. package/src-next/session/__tests__/wave.test.ts +476 -0
  94. package/src-next/session/faces.ts +110 -0
  95. package/src-next/session/graph.ts +411 -0
  96. package/src-next/session/handoff-schema.ts +373 -0
  97. package/src-next/session/ledger.ts +1076 -0
  98. package/src-next/session/next.ts +293 -0
  99. package/src-next/session/preflight.ts +271 -0
  100. package/src-next/session/round-naming.ts +84 -0
  101. package/src-next/session/run.ts +610 -0
  102. package/src-next/session/state.ts +30 -0
  103. package/src-next/session/wave.ts +139 -0
  104. package/templates/report/issue-body.json +17 -65
  105. package/dist/chunks/branch.mjs +0 -480
  106. package/dist/chunks/docs.mjs +0 -253
  107. package/dist/chunks/task.mjs +0 -913
  108. package/dist/cli.mjs +0 -5457
  109. package/dist/documents/schema/add-phase-protocol.json +0 -126
  110. package/dist/documents/schema/overall.json +0 -361
  111. package/dist/documents/schema/phase-spec.json +0 -145
  112. package/dist/documents/schema/plan.json +0 -191
  113. package/dist/documents/schema/skill-anatomy.json +0 -233
  114. package/dist/resources/harness-registry.json +0 -49
  115. package/dist/shared/cdd-engine.liioziig.mjs +0 -184
  116. package/templates/engine-config.json +0 -302
  117. package/templates/schema/cache-profile-schema.json +0 -23
  118. package/templates/schema/docs-handoff-schema.json +0 -129
  119. package/templates/schema/task-handoff-schema.json +0 -332
  120. package/templates/template-contract.json +0 -231
@@ -0,0 +1,277 @@
1
+ // packages/cdd-engine/src-next/session/__tests__/graph.test.ts
2
+ // T6 TaskGraph + ExecutionState suite (design spec §3.1 · §3.8 the normalization
3
+ // chain):
4
+ // · the shared parse consumption — the graph is built from the SAME doc.ts plan
5
+ // parse instance the dispatch and the lint read (never a re-parse);
6
+ // · the four validate classes — missing-edge / missing-id / self-loop / cycle,
7
+ // all judged on the NORMALIZED edges (the extraction layer dedupes, so the
8
+ // author's repeated declaration is never adjudicated — the duplicate class is
9
+ // retired); one negative fixture each, plus the forward-reference legality
10
+ // (the anti-dependency gate retired);
11
+ // · batches() — the topological wave decomposition, plus the halt-safe window
12
+ // when a dependency can never be satisfied;
13
+ // · frontier(done) — the pure dynamic readiness face;
14
+ // · ExecutionState — doneTasks() / readyBatch()/markDone as TaskGraph methods
15
+ // (the query surface, not a standalone state class).
16
+ // Fixtures are plan literals parsed through the plan parser — hermetic.
17
+
18
+ import { describe, expect, it } from "vitest";
19
+ import { PlanDocType } from "../../contract/doc.ts";
20
+ import type { GraphIssue } from "../graph.ts";
21
+ import { TaskGraph } from "../graph.ts";
22
+
23
+ /** A plan document over `### Task N:` blocks + `- **DependsOn**:` values (the
24
+ * front-matter head the plan parser reads). */
25
+ const planDoc = (blocks: readonly (readonly string[])[]): string => {
26
+ return [
27
+ "---",
28
+ "title: Test Plan",
29
+ "doc-type: plan",
30
+ "version: v1.0",
31
+ "date: 2026-10-09",
32
+ "spec: docs/kairos/specs/x-design.md",
33
+ "parent-program: docs/kairos/specs/x-overall.md",
34
+ "parent-version: v1.0",
35
+ "---",
36
+ "",
37
+ "## Constraints",
38
+ "",
39
+ "- delta",
40
+ "",
41
+ ...blocks.flat(),
42
+ ].join("\n");
43
+ };
44
+
45
+ /** One task block with an optional `- **DependsOn**:` line (null = the field is absent). */
46
+ const task = (id: number, dependsOn: string | null): readonly string[] => {
47
+ return [
48
+ `### Task ${id}: task ${id}`,
49
+ dependsOn === null ? [] : [`- **DependsOn**: ${dependsOn}`],
50
+ ].flat();
51
+ };
52
+
53
+ /** Parse a fixture through the plan parser (the dispatch's parse home) and build the graph. */
54
+ const graphOf = (lines: readonly (readonly string[])[]): TaskGraph => {
55
+ return new TaskGraph(new PlanDocType("plan").parse(planDoc(lines).split("\n")));
56
+ };
57
+
58
+ const kindsOf = (issues: readonly GraphIssue[]): readonly string[] =>
59
+ issues.map((issue) => issue.kind);
60
+
61
+ describe("the shared doc.ts parse consumption", () => {
62
+ it("builds nodes and edges from the same parse instance the dispatch reads — no re-parse", () => {
63
+ const parsed = new PlanDocType("plan").parse(
64
+ planDoc([task(1, "none"), task(2, "1"), task(3, "1, 2")]).split("\n"),
65
+ );
66
+ expect(parsed.taskBlocks.map((block) => block.id)).toEqual([1, 2, 3]);
67
+ const graph = new TaskGraph(parsed);
68
+ expect(graph.validate()).toEqual([]);
69
+ expect(graph.batches()).toEqual([[1], [2], [3]]);
70
+ });
71
+
72
+ it("parses the brief's own comma forms (`3,4`, `1, 2`) as edge values", () => {
73
+ const graph = graphOf([
74
+ task(1, "none"),
75
+ task(2, "none"),
76
+ task(3, "none"),
77
+ task(4, "1, 2"),
78
+ task(5, "3,4"),
79
+ ]);
80
+ expect(graph.validate()).toEqual([]);
81
+ expect(graph.batches()).toEqual([[1, 2, 3], [4], [5]]);
82
+ });
83
+ });
84
+
85
+ describe("the four validate classes — one negative fixture each", () => {
86
+ it("missing-edge — a task block declaring no **DependsOn** field", () => {
87
+ const graph = graphOf([task(1, "none"), task(2, null)]);
88
+ const issues = graph.validate();
89
+ expect(kindsOf(issues)).toEqual(["missing-edge"]);
90
+ expect(issues[0]!.task).toBe(2);
91
+ });
92
+
93
+ it("missing-id — an edge references a task id absent from the plan (the gap case stays forward-clean)", () => {
94
+ const graph = graphOf([task(1, "none"), task(3, "2")]); // 2 is a gap — backward, still unregistered
95
+ const issues = graph.validate();
96
+ expect(kindsOf(issues)).toEqual(["missing-id"]);
97
+ expect(issues[0]!.task).toBe(3);
98
+ });
99
+
100
+ it("self-loop — a task depends on itself", () => {
101
+ const graph = graphOf([task(1, "none"), task(2, "1"), task(3, "3")]);
102
+ const issues = graph.validate();
103
+ expect(kindsOf(issues)).toEqual(["self-loop"]);
104
+ expect(issues[0]!.task).toBe(3);
105
+ });
106
+
107
+ it("a forward reference is legal — the anti-dependency gate is retired (T24)", () => {
108
+ const graph = graphOf([task(1, "2"), task(2, "none")]);
109
+ expect(graph.validate()).toEqual([]); // 1→2 forward edge — no contradiction class
110
+ expect(graph.batches()).toEqual([[2], [1]]);
111
+ });
112
+
113
+ it("the edge value-domain truncation — a trailing parenthetical's numbers never join the edge (§3.8)", () => {
114
+ // the plan's DependsOn lines may carry a rationale in parens (`…(ascending, 24 last…)`);
115
+ // the extraction reads only the pre-paren list — no duplicate/self-loop from prose
116
+ const graph = graphOf([task(1, "none"), task(2, "1(prose 2 here)")]);
117
+ expect(graph.validate()).toEqual([]);
118
+ expect(graph.batches()).toEqual([[1], [2]]);
119
+ });
120
+
121
+ it("cycle — a directed dependency cycle among the edges (the live gate)", () => {
122
+ const graph = graphOf([task(1, "2"), task(2, "1")]); // 1 ⇄ 2
123
+ const issues = graph.validate();
124
+ expect(kindsOf(issues)).toContain("cycle"); // no contradiction class — the forward edge is legal now
125
+ });
126
+
127
+ it("a conforming plan validates clean — zero false positives", () => {
128
+ const graph = graphOf([task(1, "none"), task(2, "1"), task(3, "1, 2")]);
129
+ expect(graph.validate()).toEqual([]);
130
+ });
131
+
132
+ it("a malformed edge value carries no edge — the whole-token token domain shared with the lint refuses `1.2`", () => {
133
+ const graph = graphOf([task(1, "none"), task(2, "1.2"), task(3, "2")]);
134
+ expect(graph.validate()).toEqual([]); // no edge parsed out of "1.2"
135
+ expect(graph.batches()).toEqual([[1, 2], [3]]); // task 2 joins the no-dependency wave
136
+ });
137
+ });
138
+
139
+ describe("the normalized edge surface (T24 — dedupe at extraction, four classes on the normalized face)", () => {
140
+ it("a duplicated declared dependency is deduped at the extraction layer — never a judgment", () => {
141
+ const graph = graphOf([task(1, "none"), task(2, "1, 1")]);
142
+ expect(graph.validate()).toEqual([]); // no duplicate class — the author's repetition is normalized away
143
+ expect(graph.batches()).toEqual([[1], [2]]);
144
+ expect(graph.reduction()[2]).toEqual([1]);
145
+ });
146
+
147
+ it("the per-block classes judge the normalized edge — a redundant declaration never manufactures a class (§3.8)", () => {
148
+ // 2 declares [1, 2]: the 2→1 edge is redundant (2 reaches 1 via itself) — the
149
+ // reduction drops it, the self-loop survives; validate reports self-loop ONLY.
150
+ const graph = graphOf([task(1, "none"), task(2, "2, 1")]);
151
+ const issues = graph.validate();
152
+ expect(kindsOf(issues)).toEqual(["self-loop"]);
153
+ expect(graph.batches()).toEqual([[1]]); // task 2 never becomes ready (self-loop)
154
+ });
155
+
156
+ it("the reduction preserves cycles — a redundant edge inside a cycle can never hide it", () => {
157
+ // 1 declares [2, 3]; 3 is already reachable from the declared 2→1 edge (2→1→3),
158
+ // so the direct 1→3 edge is redundant and dropped; the 2⇄1 cycle is preserved
159
+ // on the reduced face.
160
+ const graph = graphOf([task(1, "2, 3"), task(2, "1"), task(3, "none")]);
161
+ const issues = graph.validate();
162
+ expect(kindsOf(issues)).toEqual(expect.arrayContaining(["cycle"]));
163
+ expect(graph.reduction()[1]).toEqual([2]); // the redundant 1→3 normalized away
164
+ expect(graph.batches()).toEqual([[3]]); // the cycle leaves no fully-ready task
165
+ });
166
+ });
167
+
168
+ describe("batches() — the topological wave decomposition", () => {
169
+ it("decomposes a fan-in plan into readiness waves", () => {
170
+ const graph = graphOf([
171
+ task(1, "none"),
172
+ task(2, "none"),
173
+ task(3, "1"),
174
+ task(4, "1, 2"),
175
+ task(5, "3, 4"),
176
+ ]);
177
+ expect(graph.batches()).toEqual([[1, 2], [3, 4], [5]]);
178
+ });
179
+
180
+ it("decomposes a linear chain one task at a time", () => {
181
+ const graph = graphOf([task(1, "none"), task(2, "1"), task(3, "2"), task(4, "3")]);
182
+ expect(graph.batches()).toEqual([[1], [2], [3], [4]]);
183
+ });
184
+
185
+ it("a dependency that can never be satisfied stays unwaved — the halt-safe window (batch derivation does not recurse)", () => {
186
+ const graph = graphOf([task(1, "none"), task(2, "5"), task(3, "1")]); // 5 is a phantom
187
+ expect(graph.batches()).toEqual([[1], [3]]); // task 2 never becomes ready — safely left out
188
+ });
189
+
190
+ it("an empty plan decomposes to zero waves", () => {
191
+ expect(graphOf([]).batches()).toEqual([]);
192
+ });
193
+ });
194
+
195
+ describe("frontier(done) — the pure dynamic readiness face", () => {
196
+ const chain = () => graphOf([task(1, "none"), task(2, "1"), task(3, "2"), task(4, "3")]);
197
+
198
+ it("returns the first no-dependency wave from an empty done set", () => {
199
+ expect(chain().frontier(new Set())).toEqual([1]);
200
+ });
201
+
202
+ it("opens the next task once its dependencies complete", () => {
203
+ expect(chain().frontier(new Set([1]))).toEqual([2]);
204
+ expect(chain().frontier(new Set([1, 2]))).toEqual([3]);
205
+ expect(chain().frontier(new Set([1, 2, 3]))).toEqual([4]);
206
+ });
207
+
208
+ it("excludes done tasks and tolerates unknown / already-done ids", () => {
209
+ const graph = chain();
210
+ expect(graph.frontier(new Set([1, 2, 3, 4]))).toEqual([]);
211
+ expect(graph.frontier(new Set([0, 99]))).toEqual([1]);
212
+ });
213
+
214
+ it("never mutates the caller's done set", () => {
215
+ const done = new Set<number>([1]);
216
+ chain().frontier(done);
217
+ expect(done).toEqual(new Set([1]));
218
+ });
219
+ });
220
+
221
+ describe("ExecutionState — the query surface as TaskGraph methods", () => {
222
+ const chain = () => graphOf([task(1, "none"), task(2, "1"), task(3, "2"), task(4, "3")]);
223
+
224
+ it("starts empty — doneTasks() is the empty set and readyBatch() the seed wave", () => {
225
+ const graph = chain();
226
+ expect(graph.doneTasks()).toEqual(new Set());
227
+ expect(graph.readyBatch()).toEqual([1]);
228
+ });
229
+
230
+ it("progresses the run — doneTasks()/readyBatch() track markDone()", () => {
231
+ const graph = chain();
232
+ graph.markDone(1);
233
+ expect(graph.doneTasks()).toEqual(new Set([1]));
234
+ expect(graph.readyBatch()).toEqual([2]);
235
+ graph.markDone(2);
236
+ graph.markDone(3);
237
+ expect(graph.doneTasks()).toEqual(new Set([1, 2, 3]));
238
+ expect(graph.readyBatch()).toEqual([4]);
239
+ graph.markDone(4);
240
+ expect(graph.readyBatch()).toEqual([]);
241
+ });
242
+
243
+ it("ignores duplicate and unregistered markDone calls", () => {
244
+ const graph = chain();
245
+ graph.markDone(1);
246
+ graph.markDone(1);
247
+ graph.markDone(42);
248
+ expect(graph.doneTasks()).toEqual(new Set([1]));
249
+ expect(graph.readyBatch()).toEqual([2]);
250
+ });
251
+
252
+ it("doneTasks() returns a snapshot — mutating the result never touches the run state", () => {
253
+ const graph = chain();
254
+ graph.markDone(1);
255
+ graph.doneTasks().add(2);
256
+ expect(graph.doneTasks()).toEqual(new Set([1]));
257
+ expect(graph.readyBatch()).toEqual([2]);
258
+ });
259
+
260
+ it("readyBatch() equals the batches() wave at the matching completion point", () => {
261
+ const graph = graphOf([
262
+ task(1, "none"),
263
+ task(2, "none"),
264
+ task(3, "1"),
265
+ task(4, "1, 2"),
266
+ task(5, "3, 4"),
267
+ ]);
268
+ const waves = graph.batches();
269
+ expect(graph.readyBatch()).toEqual(waves[0]);
270
+ graph.markDone(1);
271
+ graph.markDone(2);
272
+ expect(graph.readyBatch()).toEqual(waves[1]);
273
+ graph.markDone(3);
274
+ graph.markDone(4);
275
+ expect(graph.readyBatch()).toEqual(waves[2]);
276
+ });
277
+ });
@@ -0,0 +1,48 @@
1
+ // packages/cdd-engine/src-next/session/__tests__/handoff-plane.guard.test.ts
2
+ // P5 — the handoff-plane audit, colocated after the D17 six-premise ownership-migration (the root
3
+ // guard's checkHandoffPlane assertion face re-homed into the session test
4
+ // plane — the engine's own suite holds the engine's own declaration checks). The
5
+ // two legs read the engine's single source (`session/handoff-schema.ts` — the
6
+ // declared writable subsets + the two projections), never a parallel table:
7
+ //
8
+ // ① the role-distinctive exclusives — the findings exclusive (`findings`)
9
+ // never rides the work declaration, the work exclusives (`status` /
10
+ // `failure_category`) never ride the findings declaration (the SHARED
11
+ // carrier rows — artifacts / notes — are both-faced by design; the
12
+ // exclusives ARE the role);
13
+ // ③ the prompt-injection projection — `schemaText(face)` parses byte-identically
14
+ // to the declared node (the declaration IS the writable plane — zero
15
+ // engine-only metadata to strip).
16
+ //
17
+ // Zero module-level bare functions — the read/scan helpers are `const` (the P5
18
+ // zero-`function`-declaration discipline).
19
+
20
+ import { describe, expect, it } from "vitest";
21
+
22
+ import { HandoffSchema } from "../handoff-schema.ts";
23
+
24
+ describe("the handoff-plane audit — the declared writable subsets (the engine's own declaration checks)", () => {
25
+ it("① the role-distinctive exclusives — the findings exclusive never rides work; the work exclusives never ride findings", () => {
26
+ const schema = new HandoffSchema();
27
+ const work = schema.faceSchema("work");
28
+ const findings = schema.faceSchema("findings");
29
+ expect(work.properties ?? {}).not.toHaveProperty("findings");
30
+ for (const key of ["status", "failure_category"] as const) {
31
+ expect(findings.properties ?? {}).not.toHaveProperty(key);
32
+ }
33
+ });
34
+
35
+ it("③ the prompt-injection projection — the schemaText fence parses to the declared writable subset", () => {
36
+ const schema = new HandoffSchema();
37
+ for (const face of ["work", "findings"] as const) {
38
+ const text = schema.schemaText(face, false);
39
+ const fence = text.split("```json\n")[1]?.split("\n```")[0];
40
+ expect(fence, `the ${face} projection carries a \`\`\`json fence`).toBeDefined();
41
+ if (fence === undefined) continue;
42
+ const parsed = JSON.parse(fence) as unknown;
43
+ expect(parsed, `the ${face} fence parses to the declared node`).toEqual(
44
+ schema.faceSchema(face),
45
+ );
46
+ }
47
+ });
48
+ });
@@ -0,0 +1,310 @@
1
+ // packages/cdd-engine/src-next/session/__tests__/handoff-schema.test.ts
2
+ // T15 v1.9 — the handoff schema face suite (one declaration, two projections):
3
+ // · projection ① — schemaText: the per-face writable-subset fence (work vs
4
+ // findings), the evidence-file fence on the task-family work rounds, and the
5
+ // byte-stability of the injected prompt text;
6
+ // · projection ② — violations/evidenceViolations: the child draft's read-back
7
+ // validation (the SAME declared objects the prompt showed; a violation is the
8
+ // engine's read-back BLOCK — no-overwrite on failure);
9
+ // · the status rollup — the review conclusion (blocker → CHANGES_REQUESTED ·
10
+ // warn/nit → REVIEW_FIX · none → APPROVED) + the findings normalization (the
11
+ // capsule's blocker face, never the judgment domain).
12
+
13
+ import { mkdtempSync, rmSync } from "node:fs";
14
+ import { tmpdir } from "node:os";
15
+ import path from "node:path";
16
+ import { describe, expect, it } from "vitest";
17
+ import { ConfigLoader } from "../../infra/config.ts";
18
+ import { Workspace, WorkspaceRoot } from "../../infra/workspace.ts";
19
+ import { HandoffSchema, type WorkCarrier } from "../handoff-schema.ts";
20
+ import { Ledger } from "../ledger.ts";
21
+
22
+ const schema = new HandoffSchema();
23
+
24
+ /** A hermetic ledger fixture — a fresh temp workspace (the buildHandoff carrier
25
+ * needs no on-disk state; the fixture keeps the per-face pins self-contained). */
26
+ const ledgerFixture = (): { ledger: Ledger; cleanup: () => void } => {
27
+ const repo = mkdtempSync(path.join(tmpdir(), "handoff-carrier-"));
28
+ const workspace = new Workspace(
29
+ new WorkspaceRoot(path.join(repo, ".kairos", "cdd"), "session"),
30
+ "test-slug",
31
+ );
32
+ return {
33
+ ledger: new Ledger(workspace, new ConfigLoader()),
34
+ cleanup: () => rmSync(repo, { recursive: true, force: true }),
35
+ };
36
+ };
37
+
38
+ /** The canonical valid work draft — the implement/fix child's write-back. */
39
+ const WORK = {
40
+ status: "APPROVED",
41
+ artifacts: { report: "/r", test_evidence: "/ws/tasks-1-test-evidence.json" },
42
+ notes: ["one note"],
43
+ };
44
+
45
+ /** The canonical valid review draft — the findings-only write-back. */
46
+ const FINDINGS = {
47
+ findings: [{ severity: "blocker", lens: "spec", summary: "drift" }],
48
+ notes: [],
49
+ };
50
+
51
+ /** The canonical valid evidence file — the evidence gate's read-back input. */
52
+ const EVIDENCE = {
53
+ command: "npx vitest run",
54
+ exit_code: 0,
55
+ passed: true,
56
+ warnings_count: 0,
57
+ typecheck: { command: "tsc --noEmit", exit_code: 0, passed: true },
58
+ };
59
+
60
+ describe("projection ① — the injected writable-subset schema text", () => {
61
+ it("renders the work face — the carrier fence + the evidence-file fence", () => {
62
+ const text = schema.schemaText("work", true);
63
+ expect(text).toContain("```json");
64
+ expect(text).toContain("Write the handoff draft at `OUTPUT_HANDOFF` per this writable subset");
65
+ expect(text).toContain('"status"');
66
+ expect(text).toContain('"artifacts"');
67
+ expect(text).not.toContain('"commits"');
68
+ expect(text).not.toContain('"changes"');
69
+ expect(text).toContain("The evidence file");
70
+ expect(text).toContain('"typecheck"');
71
+ // the reserved engine fields are NOT writable by the child — the subset refuses them
72
+ expect(JSON.parse(text.split("```json\n")[1]!.split("\n```")[0]!)).toMatchObject({
73
+ type: "object",
74
+ required: ["status", "artifacts"],
75
+ });
76
+ });
77
+
78
+ it("renders the findings face — findings only, no status, no evidence fence", () => {
79
+ const text = schema.schemaText("findings", false);
80
+ expect(text).toContain("```json");
81
+ expect(text).toContain('"findings"');
82
+ expect(text).not.toContain('"status"');
83
+ expect(text).not.toContain("The evidence file");
84
+ const json = JSON.parse(text.split("```json\n")[1]!.split("\n```")[0]!);
85
+ expect(json).toMatchObject({ type: "object", required: ["findings"] });
86
+ });
87
+
88
+ it("is byte-stable per (face, evidence) — the prompt's contract surface never shifts", () => {
89
+ // the SAME face renders identical text every dispatch (the prefix-tail cache fact)
90
+ expect(schema.schemaText("work", true)).toBe(schema.schemaText("work", true));
91
+ expect(schema.schemaText("findings", false)).toBe(schema.schemaText("findings", false));
92
+ expect(schema.schemaText("work", true)).not.toBe(schema.schemaText("findings", false));
93
+ });
94
+
95
+ it("the fence parses byte-identically to the declared face node — the one-hand projection pin (T3)", () => {
96
+ // The prompt-injection projection (schemaText) and the read-back declaration
97
+ // (faceSchema) are the SAME declared object's two projections: parses of the
98
+ // ```` ```json ```` fences must round-trip to the declared nodes verbatim (the
99
+ // declaration IS the writable plane — zero engine-only metadata to strip) — the
100
+ // prompt can never show a schema the engine does not enforce (the guard's
101
+ // checkHandoffPlane ③ asserts the same fact against the live tree).
102
+ for (const face of ["work", "findings"] as const) {
103
+ const text = schema.schemaText(face, false);
104
+ const parsed = JSON.parse(text.split("```json\n")[1]!.split("\n```")[0]!);
105
+ expect(JSON.stringify(parsed)).toBe(JSON.stringify(schema.faceSchema(face)));
106
+ }
107
+ });
108
+
109
+ it("the findings fence carries no status — the conclusion is derived, never a child-writable field (D27)", () => {
110
+ // The findings carrier holds no status field: the declaration plane IS the
111
+ // writable plane, and the round conclusion derives at judgment time
112
+ // (`conclusionOf("findings", carrier)` → rollup(findings)). The child-visible
113
+ // fence therefore never surfaces a `"status"` slot on the findings face.
114
+ expect(schema.schemaText("findings", false)).not.toContain('"status"');
115
+ });
116
+ });
117
+
118
+ describe("projection ② — the read-back validation (violations)", () => {
119
+ it("accepts the canonical work draft and the canonical findings draft", () => {
120
+ expect(schema.violations("work", WORK)).toEqual([]);
121
+ expect(schema.violations("findings", FINDINGS)).toEqual([]);
122
+ });
123
+
124
+ it("refuses a work draft missing the required status / artifacts", () => {
125
+ expect(schema.violations("work", { artifacts: { report: "/r" } })).toContain(
126
+ "status: required",
127
+ );
128
+ expect(schema.violations("work", { status: "APPROVED" })).toContain("artifacts: required");
129
+ });
130
+
131
+ it("refuses a non-object draft and an out-of-enum status", () => {
132
+ expect(schema.violations("work", "nope")).toEqual(["expected an object"]);
133
+ expect(schema.violations("work", { status: "NEEDS_CONTEXT", artifacts: {} })).toEqual([
134
+ "status: must be one of APPROVED | BLOCKED",
135
+ ]);
136
+ });
137
+
138
+ it("drops non-declared fields instead of BLOCKing (materialize judges the same way)", () => {
139
+ // a work draft carrying engine-reserved or extra keys is dropped by materialize
140
+ // and never refuses the draft (the drop-not-BLOCK ruling · §8.7)
141
+ expect(
142
+ schema.violations("work", { status: "APPROVED", artifacts: {}, phase: "implement" }),
143
+ ).toEqual([]);
144
+ expect(schema.violations("work", { status: "APPROVED", artifacts: {}, tasks: [1] })).toEqual(
145
+ [],
146
+ );
147
+ // a child-authored `status` on a findings draft is non-declared — dropped, not refused
148
+ expect(schema.violations("findings", { findings: [], status: "APPROVED" })).toEqual([]);
149
+ // a stray `commits` key on a work draft is no longer declared — dropped
150
+ expect(schema.violations("work", { ...WORK, commits: { base: "short" } })).toEqual([]);
151
+ });
152
+
153
+ it("refuses a findings draft with a missing findings array or a bad severity", () => {
154
+ expect(schema.violations("findings", {})).toEqual(["findings: required"]);
155
+ expect(schema.violations("findings", { findings: "nope" })).toEqual([
156
+ "findings: expected an array",
157
+ ]);
158
+ expect(
159
+ schema.violations("findings", {
160
+ findings: [{ severity: "fatal", lens: "spec", summary: "x" }],
161
+ }),
162
+ ).toEqual(["findings[0].severity: must be one of blocker | warn | nit"]);
163
+ expect(
164
+ schema.violations("findings", {
165
+ findings: [{ severity: "warn", lens: "spec" }],
166
+ }),
167
+ ).toEqual(["findings[0].summary: required"]);
168
+ });
169
+ });
170
+
171
+ describe("projection ② — the evidence read-back (evidenceViolations)", () => {
172
+ it("accepts the canonical evidence file", () => {
173
+ expect(schema.evidenceViolations(EVIDENCE)).toEqual([]);
174
+ });
175
+
176
+ it("refuses a missing evidence file (the null read-back face)", () => {
177
+ expect(schema.evidenceViolations(null)).toEqual(["the evidence file is missing"]);
178
+ });
179
+
180
+ it("refuses an incomplete typecheck item (the missing-typecheck = BLOCK pin)", () => {
181
+ expect(
182
+ schema.evidenceViolations({
183
+ command: "x",
184
+ exit_code: 0,
185
+ passed: true,
186
+ warnings_count: 0,
187
+ typecheck: { command: "tsc --noEmit", exit_code: 0 },
188
+ }),
189
+ ).toEqual(["typecheck.passed: required"]);
190
+ expect(
191
+ schema.evidenceViolations({
192
+ command: "x",
193
+ exit_code: 0,
194
+ passed: true,
195
+ warnings_count: 0,
196
+ }),
197
+ ).toEqual(["typecheck: required"]);
198
+ });
199
+
200
+ it("refuses a non-boolean passed and a non-integer exit_code", () => {
201
+ expect(schema.evidenceViolations({ ...EVIDENCE, passed: "yep" })).toEqual([
202
+ "passed: expected a boolean",
203
+ ]);
204
+ expect(schema.evidenceViolations({ ...EVIDENCE, exit_code: "0" })).toEqual([
205
+ "exit_code: expected an integer",
206
+ ]);
207
+ });
208
+ });
209
+
210
+ describe("the status rollup + the findings normalization", () => {
211
+ it("rolls the review conclusion up from the finding severities", () => {
212
+ expect(schema.rollup([])).toBe("APPROVED");
213
+ expect(schema.rollup([{ severity: "nit" }])).toBe("REVIEW_FIX");
214
+ expect(schema.rollup([{ severity: "warn" }])).toBe("REVIEW_FIX");
215
+ expect(schema.rollup([{ severity: "blocker" }])).toBe("CHANGES_REQUESTED");
216
+ expect(schema.rollup([{ severity: "warn" }, { severity: "blocker" }])).toBe(
217
+ "CHANGES_REQUESTED",
218
+ );
219
+ });
220
+
221
+ it("conclusionOf derives the findings conclusion from the findings, the work conclusion from the declared status (D27)", () => {
222
+ // the findings face NEVER reads a carrier status — its conclusion rolls up from
223
+ // the findings alone (the persisted findings carrier holds no status field)
224
+ expect(schema.conclusionOf("findings", { findings: [{ severity: "blocker" }] })).toBe(
225
+ "CHANGES_REQUESTED",
226
+ );
227
+ expect(schema.conclusionOf("findings", { findings: [{ severity: "nit" }] })).toBe("REVIEW_FIX");
228
+ expect(schema.conclusionOf("findings", { findings: [] })).toBe("APPROVED");
229
+ expect(schema.conclusionOf("findings", {})).toBe("APPROVED");
230
+ // a stray status on a findings carrier is ignored — the derivation is from findings
231
+ expect(
232
+ schema.conclusionOf("findings", { findings: [{ severity: "blocker" }], status: "APPROVED" }),
233
+ ).toBe("CHANGES_REQUESTED");
234
+ // the work face reads its declared status verbatim
235
+ expect(schema.conclusionOf("work", { status: "APPROVED", artifacts: {} })).toBe("APPROVED");
236
+ expect(schema.conclusionOf("work", { status: "BLOCKED", artifacts: {} })).toBe("BLOCKED");
237
+ // a PRESENT-but-invalid work status byte degrades to BLOCKED — a malformed
238
+ // declaration is a failure signal, never silently approved
239
+ expect(schema.conclusionOf("work", { status: "garbage", artifacts: {} })).toBe("BLOCKED");
240
+ expect(schema.conclusionOf("work", { status: "CHANGES_REQUESTED", artifacts: {} })).toBe(
241
+ "BLOCKED",
242
+ );
243
+ // an ABSENT status is NOT a failure declaration — undefined (no conclusion
244
+ // declared), distinct from a declared BLOCKED. This is the legacy-carrier fact:
245
+ // a work carrier predating the status field never reads as a fabricated failure
246
+ // (the router treats undefined as "not failed"; BLOCKED as the failure face).
247
+ expect(schema.conclusionOf("work", {})).toBeUndefined();
248
+ expect(schema.conclusionOf("work", { artifacts: {} })).toBeUndefined();
249
+ });
250
+
251
+ it("normalizes the draft findings — unknown severities dropped, severity + summary kept", () => {
252
+ expect(schema.findingsOf(FINDINGS.findings)).toEqual([
253
+ { severity: "blocker", summary: "drift" },
254
+ ]);
255
+ expect(
256
+ schema.findingsOf([{ severity: "fatal" }, { severity: "nit", summary: "s" }, "garbage"]),
257
+ ).toEqual([{ severity: "nit", summary: "s" }]);
258
+ expect(schema.findingsOf("nope")).toEqual([]);
259
+ });
260
+ });
261
+
262
+ describe("the derived carrier types — buildHandoff per-face shaping (T1)", () => {
263
+ it("the work carrier's flat keys equal the declared properties set, zero findings (the runtime fallback of the type derivation)", () => {
264
+ const { ledger, cleanup } = ledgerFixture();
265
+ try {
266
+ const carrier = ledger.buildHandoff("work", { artifacts: { report: "/r" } });
267
+ carrier.status = "APPROVED";
268
+ carrier.failure_category = "none";
269
+ carrier.notes = ["one note"];
270
+ expect(Object.keys(carrier).sort()).toEqual(
271
+ Object.keys(schema.faceSchema("work").properties ?? {}).sort(),
272
+ );
273
+ expect("findings" in carrier).toBe(false);
274
+ } finally {
275
+ cleanup();
276
+ }
277
+ });
278
+
279
+ it("the findings carrier carries the schema-required findings key", () => {
280
+ const { ledger, cleanup } = ledgerFixture();
281
+ try {
282
+ const carrier = ledger.buildHandoff("findings", {
283
+ findings: [{ severity: "blocker", lens: "spec", summary: "drift" }],
284
+ });
285
+ expect(Object.keys(carrier)).toContain("findings");
286
+ expect(carrier.findings).toEqual([{ severity: "blocker", lens: "spec", summary: "drift" }]);
287
+ } finally {
288
+ cleanup();
289
+ }
290
+ });
291
+
292
+ it("the type gate — the work face refuses a findings payload at compile time", () => {
293
+ const { ledger, cleanup } = ledgerFixture();
294
+ try {
295
+ // The compile-time twin of the runtime key-set pin above — a negative TYPE
296
+ // assertion (the repo's zero-debt escape ban forbids compile-error-suppression
297
+ // directives, so the gate is the assertion itself): `NoFindings<WorkCarrier>`
298
+ // only COMPILES while the work writable subset declares no findings field — a
299
+ // schema edit adding findings to the work face breaks this file's typecheck
300
+ // (Q1→c), and the `buildHandoff("work", …)` overload refuses a findings init
301
+ // by construction.
302
+ type NoFindings<T> = "findings" extends keyof T ? never : true;
303
+ const gate: NoFindings<WorkCarrier> = true;
304
+ expect(gate).toBe(true);
305
+ void ledger;
306
+ } finally {
307
+ cleanup();
308
+ }
309
+ });
310
+ });