@oscaner-skills/cdd-engine 3.0.0 → 3.1.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 (143) hide show
  1. package/{src-next/bin.ts → dist/bin.js} +18 -21
  2. package/dist/contract/declare.js +998 -0
  3. package/dist/contract/doc.js +565 -0
  4. package/dist/contract/frontmatter.js +209 -0
  5. package/dist/contract/home-extractors.js +379 -0
  6. package/dist/contract/invariants.js +1030 -0
  7. package/dist/contract/judge.js +109 -0
  8. package/dist/contract/lint.js +206 -0
  9. package/dist/contract/project.js +371 -0
  10. package/dist/contract/skill-anatomy.js +156 -0
  11. package/dist/contract/translate.js +85 -0
  12. package/dist/face/artifacts.js +189 -0
  13. package/dist/face/board-view.js +522 -0
  14. package/dist/face/capsule.js +149 -0
  15. package/dist/face/cli.js +893 -0
  16. package/dist/face/declare.js +241 -0
  17. package/dist/face/gate.js +158 -0
  18. package/dist/face/graph-view.js +66 -0
  19. package/dist/face/host.js +211 -0
  20. package/dist/face/lifecycle.js +702 -0
  21. package/dist/face/preview.js +136 -0
  22. package/dist/face/projection.js +259 -0
  23. package/dist/face/route-render.js +162 -0
  24. package/dist/face/termination.js +504 -0
  25. package/dist/face/words.js +258 -0
  26. package/{src-next/infra/config.ts → dist/infra/config.js} +19 -24
  27. package/{src-next/infra/doc-roots.ts → dist/infra/doc-roots.js} +3 -13
  28. package/dist/infra/git.js +37 -0
  29. package/dist/infra/process.js +22 -0
  30. package/{src-next/infra/root.ts → dist/infra/root.js} +25 -36
  31. package/dist/infra/runtime.js +85 -0
  32. package/dist/infra/workspace.js +276 -0
  33. package/dist/render/brief.js +82 -0
  34. package/dist/render/issue-body.js +129 -0
  35. package/dist/render/skeleton.js +434 -0
  36. package/dist/render/templates.js +520 -0
  37. package/dist/session/faces.js +38 -0
  38. package/dist/session/graph.js +309 -0
  39. package/dist/session/handoff-schema.js +295 -0
  40. package/dist/session/ledger.js +762 -0
  41. package/dist/session/next.js +211 -0
  42. package/dist/session/preflight.js +194 -0
  43. package/dist/session/round-naming.js +73 -0
  44. package/dist/session/run.js +453 -0
  45. package/dist/session/state.js +8 -0
  46. package/dist/session/wave.js +92 -0
  47. package/package.json +5 -5
  48. package/src-next/__tests__/bin.test.ts +0 -128
  49. package/src-next/__tests__/dead-decl.guard.test.ts +0 -39
  50. package/src-next/__tests__/floor.guard.test.ts +0 -69
  51. package/src-next/__tests__/issue-body.guard.test.ts +0 -66
  52. package/src-next/__tests__/phase-suffix.guard.test.ts +0 -72
  53. package/src-next/__tests__/smoke.integration.test.ts +0 -185
  54. package/src-next/__tests__/support/strip-comments.ts +0 -99
  55. package/src-next/__tests__/zero-dep.test.ts +0 -94
  56. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +0 -256
  57. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +0 -165
  58. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +0 -190
  59. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +0 -106
  60. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +0 -240
  61. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +0 -165
  62. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +0 -190
  63. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +0 -100
  64. package/src-next/contract/__tests__/declare.test.ts +0 -481
  65. package/src-next/contract/__tests__/doc.test.ts +0 -527
  66. package/src-next/contract/__tests__/dockey.guard.test.ts +0 -58
  67. package/src-next/contract/__tests__/edge-conditions.guard.test.ts +0 -81
  68. package/src-next/contract/__tests__/frontmatter.test.ts +0 -164
  69. package/src-next/contract/__tests__/judge.test.ts +0 -1111
  70. package/src-next/contract/__tests__/lint.test.ts +0 -324
  71. package/src-next/contract/__tests__/project.test.ts +0 -460
  72. package/src-next/contract/__tests__/structure-pin.test.ts +0 -186
  73. package/src-next/contract/__tests__/translate.test.ts +0 -96
  74. package/src-next/contract/declare.ts +0 -1071
  75. package/src-next/contract/doc.ts +0 -816
  76. package/src-next/contract/frontmatter.ts +0 -233
  77. package/src-next/contract/home-extractors.ts +0 -397
  78. package/src-next/contract/invariants.ts +0 -1413
  79. package/src-next/contract/judge.ts +0 -151
  80. package/src-next/contract/lint.ts +0 -239
  81. package/src-next/contract/project.ts +0 -656
  82. package/src-next/contract/skill-anatomy.ts +0 -301
  83. package/src-next/contract/translate.ts +0 -113
  84. package/src-next/face/__tests__/board-view.test.ts +0 -1151
  85. package/src-next/face/__tests__/capsule.test.ts +0 -300
  86. package/src-next/face/__tests__/channel-closure.guard.test.ts +0 -129
  87. package/src-next/face/__tests__/cli.test.ts +0 -4897
  88. package/src-next/face/__tests__/face.test.ts +0 -289
  89. package/src-next/face/__tests__/graph-view.test.ts +0 -61
  90. package/src-next/face/__tests__/host.test.ts +0 -24
  91. package/src-next/face/__tests__/install-rows.guard.test.ts +0 -58
  92. package/src-next/face/__tests__/negation.ts +0 -6
  93. package/src-next/face/__tests__/preview.test.ts +0 -374
  94. package/src-next/face/__tests__/projection.test.ts +0 -303
  95. package/src-next/face/__tests__/repo-root.guard.test.ts +0 -120
  96. package/src-next/face/__tests__/termination.test.ts +0 -650
  97. package/src-next/face/__tests__/words.guard.test.ts +0 -93
  98. package/src-next/face/artifacts.ts +0 -248
  99. package/src-next/face/board-view.ts +0 -652
  100. package/src-next/face/capsule.ts +0 -163
  101. package/src-next/face/cli.ts +0 -1028
  102. package/src-next/face/declare.ts +0 -323
  103. package/src-next/face/gate.ts +0 -171
  104. package/src-next/face/graph-view.ts +0 -74
  105. package/src-next/face/host.ts +0 -302
  106. package/src-next/face/lifecycle.ts +0 -725
  107. package/src-next/face/preview.ts +0 -151
  108. package/src-next/face/projection.ts +0 -285
  109. package/src-next/face/route-render.ts +0 -185
  110. package/src-next/face/termination.ts +0 -573
  111. package/src-next/face/words.ts +0 -314
  112. package/src-next/infra/__tests__/infra.test.ts +0 -333
  113. package/src-next/infra/__tests__/root.test.ts +0 -56
  114. package/src-next/infra/git.ts +0 -39
  115. package/src-next/infra/process.ts +0 -34
  116. package/src-next/infra/runtime.ts +0 -132
  117. package/src-next/infra/workspace.ts +0 -322
  118. package/src-next/render/__tests__/render.test.ts +0 -550
  119. package/src-next/render/__tests__/skeleton.test.ts +0 -684
  120. package/src-next/render/brief.ts +0 -121
  121. package/src-next/render/issue-body.ts +0 -162
  122. package/src-next/render/skeleton.ts +0 -502
  123. package/src-next/render/templates.ts +0 -645
  124. package/src-next/session/__tests__/graph.test.ts +0 -277
  125. package/src-next/session/__tests__/handoff-plane.guard.test.ts +0 -48
  126. package/src-next/session/__tests__/handoff-schema.test.ts +0 -310
  127. package/src-next/session/__tests__/ledger.test.ts +0 -745
  128. package/src-next/session/__tests__/next.test.ts +0 -460
  129. package/src-next/session/__tests__/preflight.test.ts +0 -545
  130. package/src-next/session/__tests__/round-naming.test.ts +0 -142
  131. package/src-next/session/__tests__/run.test.ts +0 -1026
  132. package/src-next/session/__tests__/wave-line-phase.guard.test.ts +0 -49
  133. package/src-next/session/__tests__/wave.test.ts +0 -476
  134. package/src-next/session/faces.ts +0 -110
  135. package/src-next/session/graph.ts +0 -411
  136. package/src-next/session/handoff-schema.ts +0 -373
  137. package/src-next/session/ledger.ts +0 -1076
  138. package/src-next/session/next.ts +0 -293
  139. package/src-next/session/preflight.ts +0 -271
  140. package/src-next/session/round-naming.ts +0 -84
  141. package/src-next/session/run.ts +0 -610
  142. package/src-next/session/state.ts +0 -30
  143. package/src-next/session/wave.ts +0 -139
@@ -1,650 +0,0 @@
1
- // packages/cdd-engine/src-next/face/__tests__/termination.test.ts
2
- // The Terminator's colocated pins — the asynchronous child-channel integrity the
3
- // retired sync face carried (spec §14 · D36), re-homed onto the `ChildRunner` seam
4
- // when the sync runner was retired:
5
- // · >1 MiB output (exactly the retired default-ceiling byte count + 1) arrives
6
- // whole — the child's stdout is byte-faithful (its consumers are the host log
7
- // and the crash record's `stdoutTail`; nothing downstream parses it);
8
- // · the round's closing prose survives the biggest pipe — the W1 failure class
9
- // (tail truncation losing the child's last words) is dead;
10
- // · stderr aggregates by the same face;
11
- // · the fail-open semantics hold — a non-zero child rides its own exit code, a
12
- // broken command never throws (a spawn failure has NO exit code: it rides
13
- // `code: null`, never a folded `1`, and its reason text survives on stderr).
14
- // The child is a real hermetic shell process (no network, no repo writes).
15
- //
16
- // The stall face's own pins live here too (spec §3.3): the judge's four-state truth
17
- // table (pure, window injected — the production window would make a case wait out the
18
- // real half hour) and the sampler's two legs (a real process group and a scratch tree).
19
- // The sampling loop's pins close the face (§3.4): every dispatch's heartbeat trail —
20
- // sampled at once, overwritten per tick, removed at a normal end, kept when the round
21
- // was terminated.
22
-
23
- import { spawn } from "node:child_process";
24
- import {
25
- existsSync,
26
- mkdirSync,
27
- mkdtempSync,
28
- readFileSync,
29
- rmSync,
30
- statSync,
31
- symlinkSync,
32
- utimesSync,
33
- writeFileSync,
34
- } from "node:fs";
35
- import { tmpdir } from "node:os";
36
- import path from "node:path";
37
- import { afterEach, describe, expect, it } from "vitest";
38
- import type { Sample, SampleRecord } from "../../session/ledger.ts";
39
- import {
40
- type ChildOutcome,
41
- type ChildRun,
42
- Sampler,
43
- StallJudge,
44
- TerminationPolicy,
45
- Terminator,
46
- } from "../termination.ts";
47
-
48
- /** One production-shaped child run over a scratch root — the child's cwd is the tree
49
- * leg's scan root, and the heartbeat lands inside it (the production wiring: the two
50
- * paths share one source, the dispatch's workspace). */
51
- const childRun = (
52
- root: string,
53
- command: string,
54
- args: readonly string[],
55
- policy: TerminationPolicy = TerminationPolicy.of("implement"),
56
- ): ChildRun => ({
57
- command,
58
- args,
59
- cwd: root,
60
- heartbeatPath: heartbeatOf(root),
61
- policy,
62
- });
63
-
64
- /** The heartbeat path of a scratch dispatch (`childRun`'s own derivation). */
65
- const heartbeatOf = (root: string): string => path.join(root, "liveness.json");
66
-
67
- describe("Terminator — the asynchronous child-channel collection (spec §14 · D36)", () => {
68
- const runner = new Terminator();
69
-
70
- it("collects >1 MiB stdout whole — exactly the retired default ceiling + 1 byte", async () => {
71
- // 1 MiB + 1 byte of 'x' — the byte count that trips the retired default
72
- // output-buffer cap; every byte must arrive.
73
- const result = await runner.run(
74
- childRun(scratch(), "sh", ["-c", "head -c 1048577 /dev/zero | tr '\\0' x"]),
75
- );
76
- expect(result.code).toBe(0);
77
- expect(result.stdout.length).toBe(1048577);
78
- expect(result.termination).toBeNull();
79
- });
80
-
81
- it("keeps the child's closing prose intact behind a huge narrative — the W1 truncation class is dead", async () => {
82
- // A big narrative stdout followed by the round's closing prose (the `## Return`
83
- // contract: plain sentences, no key-value lines) — the exact W1 incident shape
84
- // (work fine, tail lost). The closing lines MUST reach.
85
- const result = await runner.run(
86
- childRun(scratch(), "sh", [
87
- "-c",
88
- "head -c 2000000 /dev/zero | tr '\\0' x; printf '\\nThe round succeeded; every check is green.\\nThe handoff draft is the machine-readable result.\\n'",
89
- ]),
90
- );
91
- expect(result.code).toBe(0);
92
- expect(result.stdout.length).toBeGreaterThan(2000000);
93
- expect(result.stdout).toMatch(/^The round succeeded; every check is green\.$/m);
94
- expect(result.stdout).toMatch(/^The handoff draft is the machine-readable result\.$/m);
95
- });
96
-
97
- it("aggregates stderr by the same streaming face", async () => {
98
- const result = await runner.run(
99
- childRun(scratch(), "sh", ["-c", "head -c 1100000 /dev/zero | tr '\\0' e >&2"]),
100
- );
101
- expect(result.code).toBe(0);
102
- expect(result.stderr.length).toBe(1100000);
103
- expect(result.stderr).toMatch(/^e+$/);
104
- });
105
-
106
- it("stays fail-open — a non-zero child rides its code, a broken command never throws", async () => {
107
- const nonZero = await runner.run(childRun(scratch(), "sh", ["-c", "echo partial; exit 7"]));
108
- expect(nonZero.code).toBe(7);
109
- expect(nonZero.stdout).toBe("partial\n");
110
- expect(nonZero.termination).toBeNull();
111
- // A broken command never spawned: it has no exit code (null, never the retired
112
- // folded `1`), no signal event — so it is NOT a termination, and it is reported
113
- // with a reason text (execa's own diagnostic) on stderr.
114
- const broken = await runner.run(childRun(scratch(), "cdd-no-such-binary-xyz", []));
115
- expect(broken.code).toBeNull();
116
- expect(broken.stdout).toBe("");
117
- expect(broken.stderr.length).toBeGreaterThan(0);
118
- expect(broken.termination).toBeNull();
119
- });
120
-
121
- it("carries the phase's wall-clock ceiling as the child's timeout — the budget leg of the seam", async () => {
122
- // The production option face takes the phase's own budget key (the terminator
123
- // never invents a second clock): a policy whose budget has already elapsed
124
- // terminates the sleeping child on execa's own kill path, and the outcome
125
- // reports the termination fact rather than a fabricated exit code.
126
- const result = await runner.run(
127
- childRun(scratch(), "sh", ["-c", "sleep 30"], new TerminationPolicy(200)),
128
- );
129
- expect(result.termination).not.toBeNull();
130
- expect(result.termination?.cause).toBe("over-budget");
131
- expect(result.code).toBeNull();
132
- });
133
-
134
- it('kills a silently-hung child on the stall verdict — `cause: "stalled"` (issue #346 shape)', async () => {
135
- // The end-to-end stall case: a CPU-silent hung child (zero CPU growth, no
136
- // workspace writes, no output — the issue #346 field shape) with tiny injected
137
- // timing. The judge rules `stalled`, the terminator kills the group, and the
138
- // outcome attributes the kill to the engine's own judgment — never as an
139
- // external signal, despite execa reporting the kill as one.
140
- const root = scratch();
141
- plant(root, "work.md", EPOCH + 10);
142
- const result = await runner.run(
143
- childRun(root, "sh", ["-c", "sleep 30"], new TerminationPolicy(60_000, 300, 60)),
144
- );
145
- expect(result.termination).not.toBeNull();
146
- expect(result.termination?.cause).toBe("stalled");
147
- expect(result.code).toBeNull();
148
- // The last sample rode the termination in memory — the postmortem pair.
149
- expect(result.termination?.lastSample).not.toBeNull();
150
- expect(result.termination?.lastSample?.verdict).toBe("stalled");
151
- // The heartbeat file stays on disk for a human's postmortem.
152
- expect(existsSync(heartbeatOf(root))).toBe(true);
153
- });
154
-
155
- it("never kills a busy child — sustained CPU growth rules `progress`, the round ends by itself", async () => {
156
- // The discriminating-power positive: a child whose process group keeps burning
157
- // CPU is `progress` on every tick — the judge never rules `stalled`, no kill
158
- // fires, and the round ends by itself (exit 0, no termination).
159
- const result = await runner.run(
160
- childRun(
161
- scratch(),
162
- "sh",
163
- ["-c", "i=0; while [ $i -lt 4000000 ]; do i=$((i + 1)); done; echo busy-done"],
164
- new TerminationPolicy(60_000, 300, 60),
165
- ),
166
- );
167
- expect(result.termination).toBeNull();
168
- expect(result.code).toBe(0);
169
- expect(result.stdout).toContain("busy-done");
170
- });
171
-
172
- it('attributes an external signal — `cause: "signal"`, the semantic, never the literal', async () => {
173
- // A healthy child killed by an OUTSIDE actor: the terminator killed nothing
174
- // (no stall fired, the production budget is hours away) — the external signal
175
- // is the termination's attributed cause, by semantic, never the SIGTERM literal.
176
- const root = scratch();
177
- plant(root, "work.md", EPOCH + 10);
178
- // The child writes its own pid (it IS its own process group leader under the
179
- // killDescendants spawn shape) so the test — standing outside the seam — can
180
- // signal the group the way a real outside actor would.
181
- const dispatch = runner.run(
182
- childRun(
183
- root,
184
- "sh",
185
- ["-c", "echo $$ > pid.txt; sleep 30"],
186
- TerminationPolicy.of("implement"),
187
- ),
188
- );
189
- const pidFile = path.join(root, "pid.txt");
190
- const deadline = Date.now() + 8000;
191
- let pid = 0;
192
- while (Date.now() < deadline) {
193
- try {
194
- pid = Number(readFileSync(pidFile, "utf8").trim());
195
- if (pid > 0) break;
196
- } catch {
197
- // Not written yet — poll on.
198
- }
199
- await new Promise((resolve) => setTimeout(resolve, 50));
200
- }
201
- expect(pid).toBeGreaterThan(0);
202
- process.kill(-pid, "SIGTERM");
203
- const result = await dispatch;
204
- expect(result.termination?.cause).toBe("signal");
205
- expect(result.code).toBeNull();
206
- });
207
- });
208
-
209
- // ---------------------------------------------------------------------------
210
- // the derivation — the four-way table (§4.1)
211
- // ---------------------------------------------------------------------------
212
-
213
- describe("Terminator.terminationOf — the four-way derivation and its priority (spec §4.1)", () => {
214
- /** The postmortem sample every non-null case must carry verbatim — the cause and
215
- * its evidence ride together. */
216
- const lastSample: SampleRecord = {
217
- sampledAt: 1234,
218
- groupCpuMs: 42,
219
- newestMtimeMs: 987,
220
- verdict: "stalled",
221
- };
222
-
223
- /** One execa-result face with every fact independently set. */
224
- const face = (
225
- overrides: {
226
- timedOut?: boolean;
227
- killedByStall?: boolean;
228
- signal?: string;
229
- isTerminated?: boolean;
230
- } = {},
231
- ) => ({
232
- timedOut: false,
233
- killedByStall: false,
234
- signal: undefined as string | undefined,
235
- isTerminated: false,
236
- ...overrides,
237
- });
238
-
239
- const derive = (facts: ReturnType<typeof face>): unknown =>
240
- Terminator.terminationOf({ ...facts, lastSample });
241
-
242
- const table: Array<{ label: string; facts: ReturnType<typeof face>; cause: string }> = [
243
- {
244
- label: "the wall-clock ceiling alone → `over-budget`",
245
- facts: face({ timedOut: true, isTerminated: true }),
246
- cause: "over-budget",
247
- },
248
- {
249
- // The causes claim a kill in order: the ceiling is checked first.
250
- label: "the wall clock wins over our own kill too → `over-budget`",
251
- facts: face({ timedOut: true, killedByStall: true, isTerminated: true }),
252
- cause: "over-budget",
253
- },
254
- {
255
- label: "the engine's own stall kill alone → `stalled`",
256
- facts: face({ killedByStall: true, isTerminated: true }),
257
- cause: "stalled",
258
- },
259
- {
260
- // OUR kill also arrives as a signal: misreading it as external would falsify
261
- // the postmortem, so the stall leg is checked ahead of the signal leg.
262
- label: "our own kill wins over the signal it reports → `stalled`",
263
- facts: face({ killedByStall: true, signal: "SIGTERM", isTerminated: true }),
264
- cause: "stalled",
265
- },
266
- {
267
- label: "any other signal → `signal`, the semantic never the literal",
268
- facts: face({ signal: "SIGKILL", isTerminated: true }),
269
- cause: "signal",
270
- },
271
- {
272
- // The unattributable fallback: a terminated child that matches none of the
273
- // three causes (no real child produces it — the branch is still pinned).
274
- label: "terminated with no attributable cause → `unknown`",
275
- facts: face({ isTerminated: true }),
276
- cause: "unknown",
277
- },
278
- ];
279
-
280
- for (const { label, facts, cause } of table) {
281
- it(label, () => {
282
- expect(derive(facts)).toEqual({ cause, lastSample });
283
- });
284
- }
285
-
286
- it("derives `null` when the round ended by itself — no ceiling, no kill, no signal", () => {
287
- expect(derive(face())).toBeNull();
288
- });
289
-
290
- it("carries the last sample as-is — including the honest `null` of no observation", () => {
291
- const facts = { ...face({ isTerminated: true }), lastSample: null };
292
- expect(Terminator.terminationOf(facts)).toEqual({
293
- cause: "unknown",
294
- lastSample: null,
295
- });
296
- });
297
- });
298
-
299
- // ---------------------------------------------------------------------------
300
- // the stall face — the judge's truth table and the sampler's two legs (§3.3)
301
- // ---------------------------------------------------------------------------
302
-
303
- /** A fixed epoch for planted mtimes: every file's mtime is an explicit second, so a
304
- * leg's reading is exact and never `writeFileSync`'s wall clock. */
305
- const EPOCH = 1_700_000_000;
306
-
307
- const scratchRoots: string[] = [];
308
-
309
- /** A scratch directory (removed after each case). */
310
- const scratch = (): string => {
311
- const dir = mkdtempSync(path.join(tmpdir(), "stall-"));
312
- scratchRoots.push(dir);
313
- return dir;
314
- };
315
-
316
- /** Plant a file at `rel` under `root` with an explicit mtime (seconds since epoch). */
317
- const plant = (root: string, rel: string, seconds: number): string => {
318
- const target = path.join(root, rel);
319
- mkdirSync(path.dirname(target), { recursive: true });
320
- writeFileSync(target, `${rel}\n`);
321
- utimesSync(target, seconds, seconds);
322
- return target;
323
- };
324
-
325
- /** One sample tick of the two legs. */
326
- const tick = (groupCpuMs: number | null, newestMtimeMs: number | null): Sample => ({
327
- groupCpuMs,
328
- newestMtimeMs,
329
- });
330
-
331
- /** Spawn one detached child — its own process group (and session), the shape the
332
- * production `killDescendants` spawn gives every dispatch child. */
333
- const detachedChild = async (command: string, args: readonly string[]): Promise<number> => {
334
- const child = spawn(command, [...args], { detached: true, stdio: "ignore" });
335
- child.unref();
336
- // The group/session is the child's own (setsid at spawn); give the kernel a beat to
337
- // settle it before `ps` reads it.
338
- await new Promise((resolve) => setTimeout(resolve, 200));
339
- return child.pid ?? 0;
340
- };
341
-
342
- /** SIGKILL a detached child and wait for its exit — a leaked spinner would keep the
343
- * suite's process alive. */
344
- const reap = (pid: number): void => {
345
- if (pid === 0) return;
346
- try {
347
- process.kill(pid, "SIGKILL");
348
- } catch {
349
- // Already gone — nothing to reap.
350
- }
351
- };
352
-
353
- afterEach(() => {
354
- for (const dir of scratchRoots.splice(0)) rmSync(dir, { recursive: true, force: true });
355
- });
356
-
357
- describe("StallJudge — the four-state truth table (spec §3.3)", () => {
358
- it("rules `idled` while the injected window is open and `stalled` once it is spent", () => {
359
- const judge = new StallJudge(1000, 0);
360
- // The first tick has no previous observation: neither leg can have advanced,
361
- // and the idle clock runs from the spawn instant.
362
- expect(judge.observe(tick(100, 500), 500)).toBe("idled");
363
- expect(judge.observe(tick(100, 500), 999)).toBe("idled");
364
- // The window is spent — inclusive bound.
365
- expect(judge.observe(tick(100, 500), 1000)).toBe("stalled");
366
- });
367
-
368
- it("starts the idle clock at the spawn instant, never at the first sample", () => {
369
- const judge = new StallJudge(1000, 100);
370
- // A tree that already carried a fresh mtime at the first tick is not progress.
371
- expect(judge.observe(tick(100, 900), 500)).toBe("idled");
372
- expect(judge.observe(tick(100, 900), 1100)).toBe("stalled");
373
- });
374
-
375
- it("rules `progress` on the CPU leg's advance and restarts the window from that tick", () => {
376
- const judge = new StallJudge(1000, 0);
377
- expect(judge.observe(tick(100, 500), 0)).toBe("idled");
378
- // The process group burned CPU — the flat tree does not matter.
379
- expect(judge.observe(tick(120, 500), 400)).toBe("progress");
380
- // The window now runs from 400.
381
- expect(judge.observe(tick(120, 500), 900)).toBe("idled");
382
- expect(judge.observe(tick(120, 500), 1400)).toBe("stalled");
383
- });
384
-
385
- it("rules `progress` on the tree leg's advance alone — a rewrite under a flat CPU group", () => {
386
- const judge = new StallJudge(1000, 0);
387
- judge.observe(tick(100, 500), 0);
388
- expect(judge.observe(tick(100, 700), 200)).toBe("progress");
389
- });
390
-
391
- it("compares the tree leg against its historical maximum — a tree that only loses files makes no progress", () => {
392
- const judge = new StallJudge(1000, 0);
393
- judge.observe(tick(100, 900), 0);
394
- // The newest file was deleted — the reading went backwards, never an advance.
395
- expect(judge.observe(tick(100, 600), 500)).toBe("idled");
396
- // Below the historical maximum — still not an advance.
397
- expect(judge.observe(tick(100, 800), 900)).toBe("idled");
398
- // Above it — an advance.
399
- expect(judge.observe(tick(100, 950), 950)).toBe("progress");
400
- });
401
-
402
- it("rules `unknown` on an unreadable leg and never kills — however long the window has run", () => {
403
- const judge = new StallJudge(10, 0);
404
- expect(judge.observe(tick(null, 500), 10 ** 9)).toBe("unknown");
405
- expect(judge.observe(tick(100, null), 10 ** 9)).toBe("unknown");
406
- // An unreadable tick proves neither progress nor idleness: it never restarts the
407
- // window, so the first readable flat tick rules on the window that has run.
408
- expect(judge.observe(tick(100, 500), 10 ** 9)).toBe("stalled");
409
- });
410
- });
411
-
412
- describe("Sampler — the two legs (spec §3.3)", () => {
413
- it("reads the newest content mtime, excluding `.git/` and the heartbeat's exact path but not `.kairos/`", () => {
414
- const root = scratch();
415
- plant(root, "progress.md", EPOCH + 10);
416
- // A child's handoff draft under `.kairos/` IS real progress — the domain is never
417
- // excluded wholesale.
418
- const draft = plant(root, ".kairos/cdd/slug/tasks-1-handoff.md", EPOCH + 20);
419
- // The VCS internal and the engine's own heartbeat are newer, and neither counts.
420
- plant(root, ".git/COMMIT_EDITMSG", EPOCH + 900);
421
- const heartbeat = plant(root, ".kairos/cdd/slug/liveness.json", EPOCH + 1000);
422
- const sampler = new Sampler({
423
- pgid: 0,
424
- scanRoot: root,
425
- exclude: Sampler.excludesFor(root, heartbeat),
426
- });
427
- expect(sampler.probe().newestMtimeMs).toBe(statSync(draft).mtimeMs);
428
- });
429
-
430
- it("never follows a symlink — a linked-in file is not this tree's progress", () => {
431
- const outside = scratch();
432
- const target = plant(outside, "elsewhere.md", EPOCH + 5000);
433
- const root = scratch();
434
- const own = plant(root, "progress.md", EPOCH + 10);
435
- symlinkSync(target, path.join(root, "link.md"));
436
- symlinkSync(outside, path.join(root, "linkdir"));
437
- const sampler = new Sampler({ pgid: 0, scanRoot: root, exclude: [] });
438
- expect(sampler.probe().newestMtimeMs).toBe(statSync(own).mtimeMs);
439
- });
440
-
441
- it("stops descending at the declared depth ceiling", () => {
442
- const root = scratch();
443
- const shallow = plant(root, "a/b/deep.md", EPOCH + 10);
444
- const buried = Array.from({ length: Sampler.MAX_DEPTH + 1 }, (_, i) => `d${i}`).join("/");
445
- plant(root, `${buried}/too-deep.md`, EPOCH + 900);
446
- const sampler = new Sampler({ pgid: 0, scanRoot: root, exclude: [] });
447
- expect(sampler.probe().newestMtimeMs).toBe(statSync(shallow).mtimeMs);
448
- });
449
-
450
- it("fails open on an unreadable leg — `null` into the judge's `unknown`, never a kill", () => {
451
- // The window is zero: any judged tick would be `stalled` on the spot.
452
- const judge = new StallJudge(0, 0);
453
- const sampler = new Sampler({
454
- pgid: 2147483646,
455
- scanRoot: path.join(scratch(), "gone"),
456
- exclude: [],
457
- });
458
- const sample = sampler.probe();
459
- expect(sample.groupCpuMs).toBeNull();
460
- expect(sample.newestMtimeMs).toBeNull();
461
- expect(judge.observe(sample, 10 ** 9)).toBe("unknown");
462
- });
463
-
464
- it("sums the process group's own CPU — the busy leg the judge rules on", async () => {
465
- const pid = await detachedChild(process.execPath, ["-e", "while (true) {}"]);
466
- try {
467
- const sampler = new Sampler({ pgid: pid, scanRoot: scratch(), exclude: [] });
468
- // `ps -o time=` truncates to whole seconds off macOS, so a busy group's first
469
- // nonzero reading can take a moment — poll to the deadline rather than race it.
470
- const deadline = Date.now() + 8000;
471
- let cpuMs = sampler.probe().groupCpuMs;
472
- while ((cpuMs === null || cpuMs === 0) && Date.now() < deadline) {
473
- await new Promise((resolve) => setTimeout(resolve, 200));
474
- cpuMs = sampler.probe().groupCpuMs;
475
- }
476
- expect(cpuMs ?? 0).toBeGreaterThan(0);
477
- } finally {
478
- reap(pid);
479
- }
480
- });
481
-
482
- it("keeps the engine's own heartbeat out of the mtime leg — a tick never self-certifies progress", async () => {
483
- const pid = await detachedChild("sleep", ["30"]);
484
- try {
485
- const root = scratch();
486
- const draft = plant(root, ".kairos/cdd/slug/tasks-1-handoff.md", EPOCH + 100);
487
- const heartbeat = plant(root, ".kairos/cdd/slug/liveness.json", EPOCH + 100);
488
- const sampler = new Sampler({
489
- pgid: pid,
490
- scanRoot: root,
491
- exclude: Sampler.excludesFor(root, heartbeat),
492
- });
493
- const judge = new StallJudge(1000, 0);
494
- const first = sampler.probe();
495
- // An idle group is readable at zero CPU — the leg's teeth are `null` vs a number.
496
- expect(first.groupCpuMs).not.toBeNull();
497
- expect(first.newestMtimeMs).toBe(statSync(draft).mtimeMs);
498
- expect(judge.observe(first, 0)).toBe("idled");
499
- // One heartbeat tick later: the ONLY thing that changed is the engine's own
500
- // write, so the leg stays flat and the window is allowed to be spent.
501
- utimesSync(heartbeat, EPOCH + 900, EPOCH + 900);
502
- const second = sampler.probe();
503
- expect(second.newestMtimeMs).toBe(first.newestMtimeMs);
504
- expect(judge.observe(second, 1000)).toBe("stalled");
505
- } finally {
506
- reap(pid);
507
- }
508
- });
509
- });
510
-
511
- // ---------------------------------------------------------------------------
512
- // the sampling loop — the dispatch's heartbeat trail (§3.4)
513
- // ---------------------------------------------------------------------------
514
-
515
- /** The heartbeat file as the engine last wrote it — a reader racing an overwrite can
516
- * catch a partial file, so an unparsable read is "no observation", never a crash. */
517
- const readHeartbeat = (target: string): SampleRecord | null => {
518
- try {
519
- return JSON.parse(readFileSync(target, "utf8")) as SampleRecord;
520
- } catch {
521
- return null;
522
- }
523
- };
524
-
525
- /** Watch a dispatch's heartbeat while it runs: the terminal cleanup removes the file
526
- * at a normal end, so the mid-dispatch face is the only place a tick is visible.
527
- * Polls until the dispatch settles and returns every distinct record it saw (keyed by
528
- * the tick's own `sampledAt`, so a repeated read of one tick collapses). */
529
- const watchHeartbeat = async (
530
- dispatch: Promise<ChildOutcome>,
531
- target: string,
532
- ): Promise<{ result: ChildOutcome; records: SampleRecord[] }> => {
533
- const seen = new Map<number, SampleRecord>();
534
- let settled = false;
535
- const poll = (async () => {
536
- while (!settled) {
537
- const record = readHeartbeat(target);
538
- if (record !== null) seen.set(record.sampledAt, record);
539
- await new Promise((resolve) => setTimeout(resolve, 10));
540
- }
541
- })();
542
- try {
543
- const result = await dispatch;
544
- return { result, records: [...seen.values()] };
545
- } finally {
546
- settled = true;
547
- await poll;
548
- }
549
- };
550
-
551
- describe("SamplingLoop — the dispatch's heartbeat trail (spec §3.4)", () => {
552
- const runner = new Terminator();
553
-
554
- it("takes a sample the moment the child is spawned — not only from the first interval on", async () => {
555
- const root = scratch();
556
- plant(root, "work.md", EPOCH + 10);
557
- // The cadence (60 s) outlives this child many times over: any record at all can
558
- // only be the immediate first sample.
559
- const { result, records } = await watchHeartbeat(
560
- runner.run(
561
- childRun(root, "sh", ["-c", "sleep 0.4"], new TerminationPolicy(60_000, 60_000, 60_000)),
562
- ),
563
- heartbeatOf(root),
564
- );
565
- expect(result.termination).toBeNull();
566
- expect(records.length).toBe(1);
567
- });
568
-
569
- it("overwrites the heartbeat once per tick — the four-field SampleRecord", async () => {
570
- const root = scratch();
571
- const planted = statSync(plant(root, "work.md", EPOCH + 10)).mtimeMs;
572
- const { result, records } = await watchHeartbeat(
573
- runner.run(
574
- childRun(root, "sh", ["-c", "sleep 0.8"], new TerminationPolicy(60_000, 60_000, 60)),
575
- ),
576
- heartbeatOf(root),
577
- );
578
- expect(result.termination).toBeNull();
579
- // Several ticks of the declared 60 ms cadence fall inside the child's 800 ms.
580
- expect(records.length).toBeGreaterThanOrEqual(3);
581
- // Every observed tick is at least one interval after the previous one: the cadence
582
- // IS the policy's `sampleIntervalMs`.
583
- for (let index = 1; index < records.length; index += 1) {
584
- expect(records[index].sampledAt - records[index - 1].sampledAt).toBeGreaterThanOrEqual(50);
585
- }
586
- for (const record of records) {
587
- expect(Object.keys(record).sort()).toEqual([
588
- "groupCpuMs",
589
- "newestMtimeMs",
590
- "sampledAt",
591
- "verdict",
592
- ]);
593
- expect(["progress", "unknown", "idled", "stalled"]).toContain(record.verdict);
594
- }
595
- // The two legs are readable in this fixture (a real detached group, a real tree)…
596
- expect(records[0].groupCpuMs).not.toBeNull();
597
- // …and the engine's OWN heartbeat never enters the mtime leg: one tick's overwrite
598
- // is not progress, however many ticks run (the §3.3 exclusion, wired end to end).
599
- expect(records.every((record) => record.newestMtimeMs === planted)).toBe(true);
600
- });
601
-
602
- it("removes the heartbeat when the round ends by itself", async () => {
603
- const root = scratch();
604
- plant(root, "work.md", EPOCH + 10);
605
- const heartbeat = heartbeatOf(root);
606
- const { result, records } = await watchHeartbeat(
607
- runner.run(
608
- childRun(root, "sh", ["-c", "sleep 0.3"], new TerminationPolicy(60_000, 60_000, 60)),
609
- ),
610
- heartbeat,
611
- );
612
- expect(result.termination).toBeNull();
613
- // The trail existed while the child ran…
614
- expect(records.length).toBeGreaterThanOrEqual(1);
615
- // …and is gone once the round ended by itself.
616
- expect(existsSync(heartbeat)).toBe(false);
617
- });
618
-
619
- it("keeps the heartbeat when the round was terminated — the human's postmortem", async () => {
620
- const root = scratch();
621
- plant(root, "work.md", EPOCH + 10);
622
- const heartbeat = heartbeatOf(root);
623
- const { result } = await watchHeartbeat(
624
- runner.run(childRun(root, "sh", ["-c", "sleep 30"], new TerminationPolicy(300, 60_000, 60))),
625
- heartbeat,
626
- );
627
- expect(result.termination?.cause).toBe("over-budget");
628
- expect(result.code).toBeNull();
629
- // The file stays for a human to read…
630
- expect(existsSync(heartbeat)).toBe(true);
631
- const onDisk = readHeartbeat(heartbeat);
632
- expect(Object.keys(onDisk ?? {}).sort()).toEqual([
633
- "groupCpuMs",
634
- "newestMtimeMs",
635
- "sampledAt",
636
- "verdict",
637
- ]);
638
- // …and the round's last sample rode the termination in memory — the same
639
- // observation, never a re-read of the file the engine itself wrote.
640
- expect(result.termination?.lastSample).toEqual(onDisk);
641
- });
642
-
643
- it("writes no heartbeat when the child never spawned — nothing to sample", async () => {
644
- const root = scratch();
645
- plant(root, "work.md", EPOCH + 10);
646
- const result = await runner.run(childRun(root, "cdd-no-such-binary-xyz", []));
647
- expect(result.termination).toBeNull();
648
- expect(existsSync(heartbeatOf(root))).toBe(false);
649
- });
650
- });