@oscaner-skills/cdd-engine 2.0.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/{src-next/bin.ts → dist/bin.js} +18 -21
  4. package/dist/contract/declare.js +998 -0
  5. package/dist/contract/doc.js +565 -0
  6. package/dist/contract/frontmatter.js +209 -0
  7. package/dist/contract/home-extractors.js +379 -0
  8. package/dist/contract/invariants.js +1030 -0
  9. package/dist/contract/judge.js +109 -0
  10. package/dist/contract/lint.js +206 -0
  11. package/dist/contract/project.js +371 -0
  12. package/dist/contract/skill-anatomy.js +156 -0
  13. package/dist/contract/translate.js +85 -0
  14. package/dist/face/artifacts.js +189 -0
  15. package/dist/face/board-view.js +522 -0
  16. package/dist/face/capsule.js +141 -0
  17. package/dist/face/cli.js +891 -0
  18. package/dist/face/declare.js +241 -0
  19. package/dist/face/gate.js +158 -0
  20. package/dist/face/graph-view.js +66 -0
  21. package/dist/face/host.js +211 -0
  22. package/dist/face/lifecycle.js +603 -0
  23. package/dist/face/preview.js +136 -0
  24. package/dist/face/projection.js +259 -0
  25. package/dist/face/route-render.js +162 -0
  26. package/dist/face/termination.js +482 -0
  27. package/dist/face/words.js +220 -0
  28. package/{src-next/infra/config.ts → dist/infra/config.js} +19 -24
  29. package/dist/infra/doc-roots.js +19 -0
  30. package/dist/infra/git.js +37 -0
  31. package/dist/infra/process.js +22 -0
  32. package/dist/infra/root.js +62 -0
  33. package/dist/infra/runtime.js +85 -0
  34. package/dist/infra/workspace.js +276 -0
  35. package/dist/render/brief.js +82 -0
  36. package/dist/render/issue-body.js +129 -0
  37. package/dist/render/skeleton.js +434 -0
  38. package/dist/render/templates.js +520 -0
  39. package/dist/session/faces.js +38 -0
  40. package/dist/session/graph.js +309 -0
  41. package/dist/session/handoff-schema.js +295 -0
  42. package/dist/session/ledger.js +762 -0
  43. package/dist/session/next.js +211 -0
  44. package/dist/session/preflight.js +194 -0
  45. package/dist/session/round-naming.js +73 -0
  46. package/dist/session/run.js +441 -0
  47. package/dist/session/state.js +8 -0
  48. package/dist/session/wave.js +92 -0
  49. package/package.json +8 -7
  50. package/templates/report/issue-body.json +0 -46
  51. package/src-next/__tests__/bin.test.ts +0 -128
  52. package/src-next/__tests__/smoke.integration.test.ts +0 -202
  53. package/src-next/__tests__/zero-dep.test.ts +0 -134
  54. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +0 -238
  55. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +0 -153
  56. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +0 -173
  57. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +0 -89
  58. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +0 -225
  59. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +0 -155
  60. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +0 -175
  61. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +0 -85
  62. package/src-next/contract/__tests__/declare.test.ts +0 -242
  63. package/src-next/contract/__tests__/doc.test.ts +0 -358
  64. package/src-next/contract/__tests__/judge.test.ts +0 -873
  65. package/src-next/contract/__tests__/lint.test.ts +0 -314
  66. package/src-next/contract/__tests__/project.test.ts +0 -419
  67. package/src-next/contract/__tests__/translate.test.ts +0 -96
  68. package/src-next/contract/declare.ts +0 -983
  69. package/src-next/contract/doc.ts +0 -753
  70. package/src-next/contract/invariants.ts +0 -1268
  71. package/src-next/contract/judge.ts +0 -142
  72. package/src-next/contract/lint.ts +0 -275
  73. package/src-next/contract/project.ts +0 -596
  74. package/src-next/contract/skill-anatomy.ts +0 -273
  75. package/src-next/contract/translate.ts +0 -113
  76. package/src-next/face/__tests__/board-view.test.ts +0 -948
  77. package/src-next/face/__tests__/capsule.test.ts +0 -276
  78. package/src-next/face/__tests__/channel-closure.guard.test.ts +0 -102
  79. package/src-next/face/__tests__/cli.test.ts +0 -4643
  80. package/src-next/face/__tests__/face.test.ts +0 -289
  81. package/src-next/face/__tests__/graph-view.test.ts +0 -61
  82. package/src-next/face/__tests__/host.test.ts +0 -24
  83. package/src-next/face/__tests__/negation.ts +0 -6
  84. package/src-next/face/__tests__/projection.test.ts +0 -301
  85. package/src-next/face/__tests__/sync-runner.test.ts +0 -70
  86. package/src-next/face/__tests__/words.guard.test.ts +0 -93
  87. package/src-next/face/artifacts.ts +0 -195
  88. package/src-next/face/board-view.ts +0 -662
  89. package/src-next/face/capsule.ts +0 -149
  90. package/src-next/face/cli.ts +0 -819
  91. package/src-next/face/declare.ts +0 -326
  92. package/src-next/face/gate.ts +0 -170
  93. package/src-next/face/graph-view.ts +0 -74
  94. package/src-next/face/host.ts +0 -326
  95. package/src-next/face/lifecycle.ts +0 -700
  96. package/src-next/face/projection.ts +0 -282
  97. package/src-next/face/route-render.ts +0 -160
  98. package/src-next/face/words.ts +0 -296
  99. package/src-next/infra/__tests__/infra.test.ts +0 -287
  100. package/src-next/infra/git.ts +0 -39
  101. package/src-next/infra/process.ts +0 -34
  102. package/src-next/infra/runtime.ts +0 -185
  103. package/src-next/infra/workspace.ts +0 -232
  104. package/src-next/render/__tests__/render.test.ts +0 -499
  105. package/src-next/render/__tests__/skeleton.test.ts +0 -466
  106. package/src-next/render/brief.ts +0 -121
  107. package/src-next/render/issue-body.ts +0 -159
  108. package/src-next/render/skeleton.ts +0 -437
  109. package/src-next/render/templates.ts +0 -650
  110. package/src-next/session/__tests__/graph.test.ts +0 -270
  111. package/src-next/session/__tests__/handoff-plane.guard.test.ts +0 -48
  112. package/src-next/session/__tests__/handoff-schema.test.ts +0 -310
  113. package/src-next/session/__tests__/ledger.test.ts +0 -744
  114. package/src-next/session/__tests__/next.test.ts +0 -368
  115. package/src-next/session/__tests__/preflight.test.ts +0 -491
  116. package/src-next/session/__tests__/run.test.ts +0 -1014
  117. package/src-next/session/__tests__/wave-line-phase.guard.test.ts +0 -49
  118. package/src-next/session/__tests__/wave.test.ts +0 -469
  119. package/src-next/session/faces.ts +0 -110
  120. package/src-next/session/graph.ts +0 -411
  121. package/src-next/session/handoff-schema.ts +0 -373
  122. package/src-next/session/ledger.ts +0 -1004
  123. package/src-next/session/next.ts +0 -192
  124. package/src-next/session/preflight.ts +0 -240
  125. package/src-next/session/run.ts +0 -606
  126. package/src-next/session/state.ts +0 -30
  127. package/src-next/session/wave.ts +0 -139
@@ -0,0 +1,309 @@
1
+ // packages/cdd-engine/src-next/session/graph.ts
2
+ // T6 — the TaskGraph (design spec §3.1): the execution-order single home. The
3
+ // graph consumes the SAME doc.ts plan parse instance the dispatch and the lint
4
+ // read — the `### Task N:` blocks and their `- **DependsOn**:` fields (the parse
5
+ // single home in doc.ts) — and never re-parses the document text. It owns the
6
+ // four edge-validation classes (missing-edge / missing-id / self-loop / cycle —
7
+ // judged on the NORMALIZED edges: the author's literal is never adjudicated), the
8
+ // `batches()` wave decomposition and the `frontier(done)` dynamic face (state.ts's
9
+ // Frontier contract). The ExecutionState query surface (doneTasks() / readyBatch()
10
+ // as methods — never a standalone state class) is carried here as the run-state
11
+ // home (markDone) until the round ledger attests it.
12
+ //
13
+ // Edge judgment is single-homed here: the four classes are the ONLY edge
14
+ // judgments of the new tree — nothing else decides whether an edge is missing,
15
+ // dangling, looping or cyclic (the lint reads a block's declared values only to
16
+ // know what NOT to suspect, and judges nothing).
17
+ //
18
+ // Module-level exports are types / the class — zero behavior-carrying bare
19
+ // functions (the plan's zero-bare-function discipline).
20
+ var _a;
21
+ import { declaredRegistries } from "../contract/declare.js";
22
+ import { Projector } from "../contract/project.js";
23
+ /**
24
+ * The task graph — nodes are the plan's task ids, one declared edge per block.
25
+ * The task-base consumption, the six-class validate, the batch waves and the
26
+ * execution query surface all read the same shared parse instance.
27
+ */
28
+ export class TaskGraph {
29
+ /** The registered task ids, ascending. */
30
+ #nodes;
31
+ /** Each task's declared edge record, keyed by task id (the AUTHOR's declaration —
32
+ * validation reads it; the consumption face is the reduction). */
33
+ #edges;
34
+ /** The direct-only consumption surface — the transitive reduction of the declared
35
+ * edges, computed once. EVERY graph consumer (`#depsOf` — batches/frontier/report/
36
+ * hasPath) reads the REDUCED form; the closure — the wave basis — is preserved by
37
+ * the reduction, so a redundant declaration is inert, never a wave shift. */
38
+ #reduced;
39
+ /** The run's completed task ids — the ExecutionState carrier (markDone). */
40
+ #done = new Set();
41
+ /** The derived `DependsOn id` value pattern (whole-token — the declared-edge
42
+ * values; the SAME derived pattern the reference lint reads, so both edge
43
+ * consumers share one task-id token domain, never a re-typed literal). */
44
+ #depIdToken;
45
+ /** Build from a shared plan parse — the same instance the dispatch and the lint read. */
46
+ constructor(parsed) {
47
+ this.#depIdToken = new RegExp(_a.#valuePatternOf(new Projector(declaredRegistries).reference().plan.entries, "DependsOn id"));
48
+ this.#nodes = parsed.taskBlocks.map((block) => block.id).sort((a, b) => a - b);
49
+ const edges = new Map();
50
+ for (const block of parsed.taskBlocks) {
51
+ edges.set(block.id, this.#edgeOf(block));
52
+ }
53
+ this.#edges = edges;
54
+ // The direct-only consumption surface — the transitive reduction, computed once
55
+ // from the DECLARED edges: every edge (t → d) whose d is already reachable from
56
+ // another declared dependency of t is dropped. The author declares the full
57
+ // prerequisite set freely; the consumers read the reduced form, and the closure
58
+ // (the wave basis) is preserved by the reduction.
59
+ const reduced = new Map();
60
+ for (const id of this.#nodes) {
61
+ const raw = edges.get(id)?.deps ?? [];
62
+ reduced.set(id, raw.filter((dep) => !raw.some((other) => other !== dep && _a.#reaches(edges, other, dep))));
63
+ }
64
+ this.#reduced = reduced;
65
+ }
66
+ /** Reachability along a RAW edge map (the reduction's closure test — a DFS). */
67
+ static #reaches(edges, from, to) {
68
+ const seen = new Set();
69
+ const stack = [from];
70
+ while (stack.length > 0) {
71
+ const current = stack.pop();
72
+ if (current === to)
73
+ return true;
74
+ if (seen.has(current))
75
+ continue;
76
+ seen.add(current);
77
+ stack.push(...(edges.get(current)?.deps ?? []));
78
+ }
79
+ return false;
80
+ }
81
+ // -------------------------------------------------------------------------
82
+ // the four-class validate (all judged on the normalized edges)
83
+ // -------------------------------------------------------------------------
84
+ /** validate — every failure class of every task, in block order, with the cycle
85
+ * class last (the graph-level judgment). The per-block classes read the
86
+ * NORMALIZED edge surface (`#depsOf` — the deduped, transitive-reduced form the
87
+ * consumers read); the author's literal declaration is never adjudicated. */
88
+ validate() {
89
+ const issues = [];
90
+ const registered = new Set(this.#nodes);
91
+ for (const blockId of this.#nodes) {
92
+ issues.push(...this.#blockIssues(blockId, registered));
93
+ }
94
+ const cycleTask = this.#cycleMember();
95
+ if (cycleTask !== null) {
96
+ issues.push({
97
+ kind: "cycle",
98
+ task: cycleTask,
99
+ message: `a directed dependency cycle closes over task ${cycleTask}: task dependencies must form a DAG`,
100
+ fix: "break the cycle — no task may depend on a task that reaches back to it",
101
+ });
102
+ }
103
+ return issues;
104
+ }
105
+ /** The per-block failure classes, in a stable order (missing-edge, missing-id,
106
+ * self-loop) — judged on the block's NORMALIZED edge (`#depsOf`); a missing
107
+ * **DependsOn** field is the missing-edge class, judged before the edges. */
108
+ #blockIssues(blockId, registered) {
109
+ const edge = this.#edges.get(blockId) ?? { declared: false, deps: [] };
110
+ if (!edge.declared) {
111
+ return [
112
+ this.#issue("missing-edge", blockId, `task ${blockId} declares no **DependsOn** edge`, "add a - **DependsOn**: line (`none` = the explicit no-dependency declaration)"),
113
+ ];
114
+ }
115
+ const issues = [];
116
+ const deps = this.#depsOf(blockId); // the normalized surface (dedupe + reduction)
117
+ const missing = _a.#unique(deps.filter((id) => !registered.has(id)));
118
+ if (missing.length > 0) {
119
+ issues.push(this.#issue("missing-id", blockId, `task ${blockId} depends on unregistered task ${_a.#toList(missing)}`, `set **DependsOn** to a task id present in the plan (${_a.#toList(missing)} is not)`));
120
+ }
121
+ if (deps.includes(blockId)) {
122
+ issues.push(this.#issue("self-loop", blockId, `task ${blockId} depends on itself`, `a task may never depend on its own number — drop ${blockId} from the block's **DependsOn**`));
123
+ }
124
+ return issues;
125
+ }
126
+ /** The cycle class — the lowest task closing a directed cycle (self-loops
127
+ * excluded: they own the self-loop class); null when the edge graph is a DAG.
128
+ * Reads the NORMALIZED edge surface (`#depsOf`) — the same face every consumer
129
+ * reads; the reduction preserves closure, so a cycle can never be normalized
130
+ * away. */
131
+ #cycleMember() {
132
+ const indegree = new Map();
133
+ const dependents = new Map();
134
+ for (const id of this.#nodes) {
135
+ indegree.set(id, 0);
136
+ dependents.set(id, new Set());
137
+ }
138
+ for (const id of this.#nodes) {
139
+ for (const dep of _a.#unique(this.#depsOf(id).filter((value) => value !== id))) {
140
+ if (!indegree.has(dep))
141
+ continue; // a phantom can never join a real cycle
142
+ indegree.set(id, indegree.get(id) + 1); // id carries one more dependency
143
+ dependents.get(dep).add(id); // when dep resolves, id's indegree drops
144
+ }
145
+ }
146
+ const remaining = new Set(this.#nodes);
147
+ const queue = this.#nodes.filter((id) => indegree.get(id) === 0);
148
+ while (queue.length > 0) {
149
+ const id = queue.shift();
150
+ remaining.delete(id);
151
+ for (const dependent of dependents.get(id)) {
152
+ const next = indegree.get(dependent) - 1;
153
+ indegree.set(dependent, next);
154
+ if (next === 0)
155
+ queue.push(dependent);
156
+ }
157
+ }
158
+ return remaining.size === 0 ? null : Math.min(...remaining);
159
+ }
160
+ /**
161
+ * batches() — the topological wave decomposition: wave 0 is every no-dependency
162
+ * task, each later wave the tasks whose dependencies all sit in earlier waves.
163
+ * A dependency that can never be satisfied (a phantom target, or a cycle among
164
+ * real tasks) keeps its task unwaved — the derivation is halt-safe and never
165
+ * recurses.
166
+ */
167
+ batches() {
168
+ const waves = [];
169
+ const done = new Set();
170
+ let pending = [...this.#nodes];
171
+ while (pending.length > 0) {
172
+ const wave = pending.filter((id) => this.#depsOf(id).every((dep) => done.has(dep)));
173
+ if (wave.length === 0)
174
+ break;
175
+ waves.push(wave);
176
+ for (const id of wave)
177
+ done.add(id);
178
+ pending = pending.filter((id) => !done.has(id));
179
+ }
180
+ return waves;
181
+ }
182
+ // -------------------------------------------------------------------------
183
+ // the frontier dynamic face (state.ts Frontier)
184
+ // -------------------------------------------------------------------------
185
+ /** frontier(done) — the not-yet-done tasks whose dependencies are all done, ascending. */
186
+ frontier(done) {
187
+ return this.#nodes.filter((id) => !done.has(id) && this.#depsOf(id).every((dep) => done.has(dep)));
188
+ }
189
+ // -------------------------------------------------------------------------
190
+ // the ExecutionState query surface (state.ts ExecutionState) + the run carrier
191
+ // -------------------------------------------------------------------------
192
+ /** The completed task ids — a snapshot copy, never a live handle into the run. */
193
+ doneTasks() {
194
+ return new Set(this.#done);
195
+ }
196
+ /** The current ready batch — the frontier over the run's done set, ascending. */
197
+ readyBatch() {
198
+ return [...this.frontier(this.#done)];
199
+ }
200
+ /** Record a completed task — idempotent; an unknown id is a no-op. */
201
+ markDone(id) {
202
+ if (this.#nodes.includes(id))
203
+ this.#done.add(id);
204
+ }
205
+ /** The task-graph read projection — the task graph + the derived wave chain +
206
+ * the done/current/pending view one method, the board face and the pre-flight
207
+ * gates' shared surface (§3.8: one projection, two displays). The edges ride the
208
+ * TRANSITIVE REDUCTION (the direct-only display); the waves always derive over
209
+ * the declared closure — a redundant declaration is inert, never a wave shift. */
210
+ report(done) {
211
+ const edges = this.reduction();
212
+ const waves = this.batches();
213
+ const first = waves.find((wave) => wave.some((id) => !done.has(id))) ?? null;
214
+ return {
215
+ edges,
216
+ waves,
217
+ done: [...done].sort((a, b) => a - b),
218
+ current: first,
219
+ pending: this.#nodes.filter((id) => !done.has(id)),
220
+ };
221
+ }
222
+ /** The transitive reduction — the direct-only dependency surface: every edge
223
+ * (t → d) whose d is already reachable from ANOTHER declared dependency of t is
224
+ * removed. The author declares the full prerequisite set freely (redundancy is
225
+ * harmless — the waves derive over the closure); the engine normalizes the
226
+ * DISPLAY, never the semantics. */
227
+ reduction() {
228
+ const out = {};
229
+ for (const id of this.#nodes) {
230
+ const deps = this.#depsOf(id);
231
+ out[id] = deps.filter((dep) => !deps.some((other) => other !== dep && this.#hasPath(other, dep)));
232
+ }
233
+ return out;
234
+ }
235
+ /** Whether `to` is reachable from `from` along the declared edges (a DFS). */
236
+ #hasPath(from, to) {
237
+ const seen = new Set();
238
+ const stack = [from];
239
+ while (stack.length > 0) {
240
+ const current = stack.pop();
241
+ if (current === to)
242
+ return true;
243
+ if (seen.has(current))
244
+ continue;
245
+ seen.add(current);
246
+ stack.push(...this.#depsOf(current));
247
+ }
248
+ return false;
249
+ }
250
+ // -------------------------------------------------------------------------
251
+ // edge reading
252
+ // -------------------------------------------------------------------------
253
+ /** The dependency ids one task consumes — THE DIRECT-ONLY REDUCTION (§3.8 / direct-only
254
+ * engine rule): every consumer (batches / frontier / report / reduction / hasPath)
255
+ * reads the reduced form; the author's redundant declarations are inert. */
256
+ #depsOf(task) {
257
+ return this.#reduced.get(task) ?? [];
258
+ }
259
+ /** One block's declared edge record — the `**DependsOn**` field's numeric list,
260
+ * taken from the field's VALUE PREFIX only (the first `(`/`(` truncates: the
261
+ * trailing parenthetical rationale is prose — zero participation, §3.8's value
262
+ * domain contract; a round number in the rationale can never become a phantom
263
+ * dependency). The extraction layer DEDUPES (a repeated declaration is
264
+ * normalized away — the author's literal is never adjudicated, §3.8 the
265
+ * normalization chain). `none`/empty carries zero edges; the field's absence is
266
+ * recorded separately for the missing-edge class. */
267
+ #edgeOf(block) {
268
+ const field = block.fields.find((entry) => entry.key === "DependsOn");
269
+ if (field === undefined)
270
+ return { declared: false, deps: [] };
271
+ const deps = [];
272
+ for (const line of field.lines) {
273
+ const prefix = line.split(/[((]/)[0];
274
+ for (const token of prefix.split(/[,\s]+/)) {
275
+ const candidate = token.trim();
276
+ if (this.#depIdToken.test(candidate))
277
+ deps.push(Number(candidate));
278
+ }
279
+ }
280
+ return { declared: true, deps: [...new Set(deps)].sort((a, b) => a - b) };
281
+ }
282
+ /** The value pattern of a registered reference entry — a lookup that fails
283
+ * loudly when the declaration renames an anchor the graph consumes (the same
284
+ * loud-lookup contract the reference lint's edge scan keeps). */
285
+ static #valuePatternOf(entries, anchor) {
286
+ const entry = entries.find((row) => row.anchor === anchor);
287
+ if (entry === undefined) {
288
+ throw new Error(`task graph requires the registered reference entry "${anchor}"`);
289
+ }
290
+ return entry.valuePattern ?? "";
291
+ }
292
+ /** One constructed issue (the single message/fix assembly point of the graph). */
293
+ #issue(kind, task, message, fix) {
294
+ return { kind, task, message, fix };
295
+ }
296
+ // -------------------------------------------------------------------------
297
+ // shared render helpers — pure list/text shaping (class members, never module
298
+ // bare functions)
299
+ // -------------------------------------------------------------------------
300
+ /** The unique values of a candidate list, in first-occurrence order. */
301
+ static #unique(values) {
302
+ return [...new Set(values)];
303
+ }
304
+ /** The `1, 2`-style list renderer for the aggregate messages. */
305
+ static #toList(values) {
306
+ return values.join(", ");
307
+ }
308
+ }
309
+ _a = TaskGraph;
@@ -0,0 +1,295 @@
1
+ // packages/cdd-engine/src-next/session/handoff-schema.ts
2
+ // T15 v1.9 — the handoff schema face (design spec §3.6): the child's writable handoff
3
+ // contract as ONE typed declaration with TWO projections. The cutover deleted the old
4
+ // JSON schema file together with its Ajv loader; the structural constraint now lives
5
+ // here as a typed declaration — zero JSON schema files, one source, two consumers:
6
+ //
7
+ // · projections: ① the prompt-injection text (schemaText — the ```json fences
8
+ // byte-fixed per face, so the fixed prefix tail of the dispatch prompt stays
9
+ // cache-friendly) and ② the engine read-back validator (violations /
10
+ // evidenceViolations — the child draft is validated against exactly the same
11
+ // declared objects the prompt showed it).
12
+ // · faces: the per-family `schema` field of the handoff families (infra/runtime.ts)
13
+ // selects the face — `work` (implement/fix: status+artifacts, plus the separate
14
+ // test-evidence file for task-family rounds) or `findings` (reviews: findings-only
15
+ // carrier — the engine rolls the status up from the findings, never a
16
+ // child-authored status).
17
+ //
18
+ // The validator is a purpose-built walker over the declared schema objects (the
19
+ // keywords this contract uses — type / properties / required / items / enum /
20
+ // minLength / maxLength) — the new tree reads zero config files and takes no Ajv
21
+ // dependency; a wrong-shape child draft is the engine's read-back BLOCK, and the
22
+ // same declared objects drive both projections so the prompt can never show a
23
+ // schema the engine does not enforce. Non-declared fields are DROPPED by
24
+ // materialize and never refuse the draft — the validator and materialize judge the
25
+ // same field the same way (zero second-arbiter friction).
26
+ //
27
+ // Module-level exports are types / the declared schema objects / the class — zero
28
+ // behavior-carrying bare functions (the plan's zero-bare-function discipline).
29
+ /** One finding row — the shared base declaration of the findings face (severity +
30
+ * lens + summary required; the extra review columns — section / line / fix — are
31
+ * declared optional, and unknown extra fields ride along). */
32
+ const FINDING = {
33
+ type: "object",
34
+ required: ["severity", "lens", "summary"],
35
+ properties: {
36
+ severity: { type: "string", enum: ["blocker", "warn", "nit"] },
37
+ lens: { type: "string" },
38
+ section: { type: "string" },
39
+ line: { type: "integer" },
40
+ summary: { type: "string" },
41
+ fix: { type: "string" },
42
+ },
43
+ };
44
+ /** The `work` writable subset — implement/fix carrier. `status` and `artifacts` are
45
+ * the round's required core; notes rides the declared optional field. Reserved
46
+ * fields (phase · tasks) are NOT declared and are DROPPED by materialize (never a
47
+ * BLOCK) — the engine stays the carrier's single author.
48
+ * `as const` preserves the literal property keys — the carrier type family
49
+ * (`CarrierOf<F>` below) derives its field set FROM these declared keys. */
50
+ const CARRIER_WORK = {
51
+ type: "object",
52
+ required: ["status", "artifacts"],
53
+ properties: {
54
+ status: { type: "string", enum: ["APPROVED", "BLOCKED"] },
55
+ failure_category: { type: "string" },
56
+ artifacts: { type: "object" },
57
+ notes: { type: "array", items: { type: "string" } },
58
+ },
59
+ };
60
+ /** The `findings` writable subset — review + docs-fix carrier. NO status: the
61
+ * conclusion is derived from the findings at judgment time
62
+ * (`conclusionOf("findings", carrier)` → `rollup(findings)`), never a carrier field
63
+ * the child authors or the engine persists — the declaration plane IS the writable
64
+ * plane (one face, one field set). `as const` — see CARRIER_WORK. */
65
+ const CARRIER_FINDINGS = {
66
+ type: "object",
67
+ required: ["findings"],
68
+ properties: {
69
+ findings: { type: "array", items: FINDING },
70
+ artifacts: { type: "object" },
71
+ notes: { type: "array", items: { type: "string" } },
72
+ },
73
+ };
74
+ /** The test-evidence file schema — the evidence gate's engine read-back contract
75
+ * (the second fix for a prose-only claim: the old prompt asserted an engine read-back
76
+ * that the engine never performed; now both projections are real). A task-family
77
+ * work round missing or violating this file rewrites the round to BLOCKED. */
78
+ const EVIDENCE = {
79
+ type: "object",
80
+ required: ["command", "exit_code", "passed", "warnings_count", "typecheck"],
81
+ properties: {
82
+ command: { type: "string" },
83
+ exit_code: { type: "integer" },
84
+ passed: { type: "boolean" },
85
+ warnings_count: { type: "integer" },
86
+ typecheck: {
87
+ type: "object",
88
+ required: ["command", "exit_code", "passed"],
89
+ properties: {
90
+ command: { type: "string" },
91
+ exit_code: { type: "integer" },
92
+ passed: { type: "boolean" },
93
+ },
94
+ },
95
+ behavior_change: { type: "boolean" },
96
+ },
97
+ };
98
+ /** The face → declared writable-subset table (the single source both projections read).
99
+ * `as const` keeps the declarations' literal property keys visible — the carrier type
100
+ * family's `[K in keyof (typeof BY_FACE)[F]["properties"]]` derives its field set from
101
+ * exactly these tables, so a schema edit reshapes the carrier types by construction. */
102
+ const BY_FACE = {
103
+ work: CARRIER_WORK,
104
+ findings: CARRIER_FINDINGS,
105
+ };
106
+ /**
107
+ * HandoffSchema — one declaration, two projections. `violations(face, value)` is
108
+ * the read-back validator (projection ② — the engine's seat, session plane);
109
+ * `schemaText(face, evidence)` is the injected prompt text (projection ① — fixed
110
+ * prefix tail, byte-stable per face so the dispatch prompt stays cache-friendly).
111
+ * `rollup(findings)` derives the review conclusion the old JSON face rolled up.
112
+ */
113
+ export class HandoffSchema {
114
+ /** Projection ① — the `## Handoff schema` section text: the face's writable
115
+ * subset in a ```json fence + (work faces) the evidence file's schema in a second
116
+ * fence. The text is byte-stable per (face, evidence, prefix) — the fixed bytes
117
+ * of the dispatch prompt's contract surface. The evidence prefix is the family
118
+ * spine (§3.7 naming: `tasks-` for the task families, `branch-` for the branch
119
+ * fix — a branch evidence file never carries the misleading tasks- prefix). */
120
+ schemaText(face, evidence, evidencePrefix = "tasks") {
121
+ const carrier = this.#json(BY_FACE[face]);
122
+ let text = `Write the handoff draft at \`OUTPUT_HANDOFF\` per this writable subset — the engine validates it, then materializes the final carrier in place; fields not listed here are engine-reserved, do not write them.\n\n\`\`\`json\n${carrier}\n\`\`\``;
123
+ if (evidence) {
124
+ text += `\n\nThe evidence file (\`${evidencePrefix}-{key}-test-evidence.json\` under \`WORKSPACE_DIR\`) must comply with this schema — the engine reads it back with the same stakes:\n\n\`\`\`json\n${this.#json(EVIDENCE)}\n\`\`\``;
125
+ }
126
+ return text;
127
+ }
128
+ /** The declared evidence schema, as text (the evidence-gate prompt's shared fence). */
129
+ evidenceSchemaText() {
130
+ return this.#json(EVIDENCE);
131
+ }
132
+ /** Projection ② — validate a child draft against a face's writable subset. Every
133
+ * problem is a read-back BLOCK; the draft is left untouched for the child's
134
+ * resume (never overwritten — the engine never clobbers a child's work). */
135
+ violations(face, value) {
136
+ const problems = [];
137
+ this.#check(BY_FACE[face], value, "", problems);
138
+ return problems.map((problem) => problem.path.length === 0 ? problem.reason : `${problem.path}: ${problem.reason}`);
139
+ }
140
+ /** Projection ② — validate the test-evidence file (task-family work rounds). */
141
+ evidenceViolations(value) {
142
+ if (value === null || value === undefined)
143
+ return ["the evidence file is missing"];
144
+ const problems = [];
145
+ this.#check(EVIDENCE, value, "", problems);
146
+ return problems.map((problem) => problem.path.length === 0 ? problem.reason : `${problem.path}: ${problem.reason}`);
147
+ }
148
+ /** The round conclusion, DERIVED at judgment time from the face's own plane — the
149
+ * single source the review/fix ledger legs read (D27 · judgment face ⊥ input face).
150
+ * The findings face rolls its conclusion UP from its findings (defined for every
151
+ * carrier — a review never carries a child-authored status, and the persisted
152
+ * findings carrier holds none). The work face reads its DECLARED status, and the
153
+ * absence of a declaration is itself a fact: an ABSENT status → `undefined` (no
154
+ * conclusion was declared — never an invented approval OR an invented failure ·
155
+ * D27 present-facts-only), while a PRESENT-but-invalid byte (outside the enum the
156
+ * schema pinned) degrades to BLOCKED — the conservative reading of a malformed
157
+ * declaration. `undefined` is DISTINCT from BLOCKED to the caller (the router
158
+ * treats undefined as "not a failure", a declared BLOCKED as the failure face), so
159
+ * a work carrier that predates the status field never reads as a fabricated
160
+ * failure. `carrier` is the on-disk carrier (or a freshly built one) — the
161
+ * conclusion is never a stored field, so any face's carrier derives it the same way. */
162
+ conclusionOf(face, carrier) {
163
+ if (face === "findings") {
164
+ const findings = Array.isArray(carrier.findings) ? carrier.findings : [];
165
+ return this.rollup(findings);
166
+ }
167
+ // The work face reads its DECLARED status. Absent → undefined (no declaration);
168
+ // present-but-invalid → BLOCKED (a declared conclusion that is malformed is a
169
+ // failure signal, never silently approved). This is the ONE ruling for a work
170
+ // status: the reconstruct's work leg delegates here, so the read-back and the
171
+ // judgment-time derivation never disagree.
172
+ const status = carrier.status;
173
+ if (status === undefined)
174
+ return undefined;
175
+ return status === "APPROVED" || status === "BLOCKED" ? status : "BLOCKED";
176
+ }
177
+ /** The review conclusion rollup — status derived from the findings severities
178
+ * (the rollup the retired JSON-return channel performed; a review never carries
179
+ * a child-authored status). */
180
+ rollup(findings) {
181
+ const blockers = findings.filter((finding) => finding?.severity === "blocker").length;
182
+ return blockers > 0 ? "CHANGES_REQUESTED" : findings.length > 0 ? "REVIEW_FIX" : "APPROVED";
183
+ }
184
+ /** The draft findings presented as round findings — unknown severities dropped
185
+ * (the capsule's blocker count + the outcome's face, never the judgment domain). */
186
+ findingsOf(findings) {
187
+ if (!Array.isArray(findings))
188
+ return [];
189
+ const rows = [];
190
+ for (const entry of findings) {
191
+ const severity = entry?.severity;
192
+ if (severity !== "blocker" && severity !== "warn" && severity !== "nit")
193
+ continue;
194
+ const summary = entry?.summary;
195
+ rows.push({
196
+ severity: severity,
197
+ summary: typeof summary === "string" ? summary : undefined,
198
+ });
199
+ }
200
+ return rows;
201
+ }
202
+ /** The declared schema object of a face — the single-source introspection of this
203
+ * module's reparametrized `HandoffFamily.schema` value. */
204
+ faceSchema(face) {
205
+ return BY_FACE[face];
206
+ }
207
+ /** The draft keys materialize drops — every key the face does not declare as a
208
+ * child-writable `properties` slot (extra child fields such as a findings-draft
209
+ * `status`). The read-back validator judges these the same way (drop, never a
210
+ * BLOCK) — materialize surfaces them as the single §8.7 WARN on the carrier's
211
+ * notes. A non-object draft drops nothing here (its shape is the validator's
212
+ * semantic refusal). */
213
+ droppedKeys(face, value) {
214
+ if (typeof value !== "object" || value === null || Array.isArray(value))
215
+ return [];
216
+ const declared = new Set(Object.keys(BY_FACE[face].properties ?? {}));
217
+ return Object.keys(value).filter((key) => !declared.has(key));
218
+ }
219
+ /** Serialize a declared schema object into the prompt's fence — COMPACT (no pretty
220
+ * indent: the injected text is the per-mode fixed prefix's biggest token cost, and
221
+ * every dispatch pays it in the child context — minify keeps the round cheap). The
222
+ * declaration IS the writable plane (no engine-only metadata to strip) — the fence
223
+ * is the declared node verbatim. */
224
+ #json(node) {
225
+ return JSON.stringify(node);
226
+ }
227
+ /** Walk one schema node against a value; every mismatch is a `path: reason`. */
228
+ #check(node, value, path, problems) {
229
+ if (node.enum !== undefined && !node.enum.includes(value)) {
230
+ problems.push({ path, reason: `must be one of ${node.enum.join(" | ")}` });
231
+ return;
232
+ }
233
+ if (node.type !== undefined) {
234
+ if (node.type === "object") {
235
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
236
+ problems.push({ path, reason: "expected an object" });
237
+ return;
238
+ }
239
+ const obj = value;
240
+ for (const key of node.required ?? []) {
241
+ if (obj[key] === undefined)
242
+ problems.push({ path: this.#at(path, key), reason: "required" });
243
+ }
244
+ for (const [key, sub] of Object.entries(node.properties ?? {})) {
245
+ if (obj[key] !== undefined)
246
+ this.#check(sub, obj[key], this.#at(path, key), problems);
247
+ }
248
+ // Non-declared keys (extra child fields such as a findings-draft
249
+ // `status`) are DROPPED by materialize, never a BLOCK — the validator
250
+ // and materialize judge the same field the same way (§8.7). Only
251
+ // semantic errors on declared fields (required / type / enum / length)
252
+ // refuse the draft.
253
+ return;
254
+ }
255
+ if (node.type === "array") {
256
+ if (!Array.isArray(value)) {
257
+ problems.push({ path, reason: "expected an array" });
258
+ return;
259
+ }
260
+ if (node.items !== undefined) {
261
+ for (let index = 0; index < value.length; index += 1) {
262
+ this.#check(node.items, value[index], `${path}[${index}]`, problems);
263
+ }
264
+ }
265
+ return;
266
+ }
267
+ if (node.type === "string") {
268
+ if (typeof value !== "string") {
269
+ problems.push({ path, reason: "expected a string" });
270
+ return;
271
+ }
272
+ if (node.minLength !== undefined && value.length < node.minLength)
273
+ problems.push({ path, reason: `must be at least ${node.minLength} characters` });
274
+ if (node.maxLength !== undefined && value.length > node.maxLength)
275
+ problems.push({ path, reason: `must be at most ${node.maxLength} characters` });
276
+ return;
277
+ }
278
+ if (node.type === "integer") {
279
+ if (typeof value !== "number" || !Number.isInteger(value)) {
280
+ problems.push({ path, reason: "expected an integer" });
281
+ }
282
+ return;
283
+ }
284
+ if (node.type === "boolean") {
285
+ if (typeof value !== "boolean")
286
+ problems.push({ path, reason: "expected a boolean" });
287
+ return;
288
+ }
289
+ }
290
+ }
291
+ /** The JSON-path join — `.field` (or bare, at the root). */
292
+ #at(path, key) {
293
+ return path.length === 0 ? key : `${path}.${key}`;
294
+ }
295
+ }