@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
@@ -0,0 +1,504 @@
1
+ // packages/cdd-engine/src-next/face/termination.ts
2
+ // The process seam of one dispatch — spawn → (sample → judge → kill, T2/T3) →
3
+ // collect. The seam's interface is `ChildRunner`; `Terminator` is its production
4
+ // implementation (execa's asynchronous face, which owns process-group creation,
5
+ // group kill, the SIGTERM → SIGKILL escalation, the parent-exit cleanup and the
6
+ // wall-clock ceiling — the engine holds no signal logic of its own).
7
+ //
8
+ // The seam's two ends are value objects, so the whole child lifecycle speaks one
9
+ // shape:
10
+ // · `ChildRun` — one dispatch's full context (command/args/cwd + the heartbeat
11
+ // path the sampler writes + the termination policy of the phase);
12
+ // · `ChildOutcome` — the child's result (its own exit code, verbatim streams)
13
+ // plus the `termination` fact: non-null ⟺ the round was cut short. The
14
+ // terminated round's downstream judgments all read that one fact, never the
15
+ // exit code (a never-spawned child has neither an exit code nor a termination).
16
+ //
17
+ // Module-level exports are types / the value object / the class — zero
18
+ // behavior-carrying bare functions.
19
+ var _a;
20
+ import { execFileSync } from "node:child_process";
21
+ import { readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
22
+ import path from "node:path";
23
+ import { execa } from "execa";
24
+ // ---------------------------------------------------------------------------
25
+ // the constant single source — budget and timing, per dispatch phase
26
+ // ---------------------------------------------------------------------------
27
+ /** TerminationPolicy — the budget/timing constant single source (code constants
28
+ * only: zero environment variables, zero config plane). The budget key set IS the
29
+ * dispatch-phase set, so no phase falls through to another phase's ceiling. The
30
+ * timing pair is injectable (the production values are the constants below; tests
31
+ * inject tiny ones, so an end-to-end stall case need not wait out the real window). */
32
+ export class TerminationPolicy {
33
+ /** The per-phase wall-clock ceiling (ms) — the implement round is the long one. */
34
+ static BUDGET_MS = {
35
+ implement: 6 * 60 * 60 * 1000,
36
+ review: 3 * 60 * 60 * 1000,
37
+ fix: 3 * 60 * 60 * 1000,
38
+ "branch-review": 3 * 60 * 60 * 1000,
39
+ };
40
+ /** The stall window (ms) — how long a round may make no progress before the
41
+ * judge rules it stalled (not per phase: "no progress" means the same thing on
42
+ * every phase). */
43
+ static IDLE_WINDOW_MS = 30 * 60 * 1000;
44
+ /** The sampling cadence (ms) — one sample tick per interval. */
45
+ static SAMPLE_INTERVAL_MS = 60 * 1000;
46
+ /** The round's wall-clock ceiling (ms) — the execa `timeout` value. */
47
+ budgetMs;
48
+ /** The stall window the judge rules on (ms). */
49
+ idleWindowMs;
50
+ /** The sampler's tick interval (ms). */
51
+ sampleIntervalMs;
52
+ constructor(budgetMs, idleWindowMs = TerminationPolicy.IDLE_WINDOW_MS, sampleIntervalMs = TerminationPolicy.SAMPLE_INTERVAL_MS) {
53
+ this.budgetMs = budgetMs;
54
+ this.idleWindowMs = idleWindowMs;
55
+ this.sampleIntervalMs = sampleIntervalMs;
56
+ }
57
+ /** The production policy of one dispatch phase — its own budget key plus the
58
+ * shared timing constants. */
59
+ static of(phase) {
60
+ return new TerminationPolicy(TerminationPolicy.BUDGET_MS[phase]);
61
+ }
62
+ }
63
+ // ---------------------------------------------------------------------------
64
+ // the stall judge — the running judgment over one dispatch, pure logic
65
+ // ---------------------------------------------------------------------------
66
+ /** StallJudge — is this dispatch still moving? Not a comparison of two samples but a
67
+ * judgment over the round: the judge holds its own accumulating state and is fed one
68
+ * tick at a time through `observe`, which returns the tick's verdict. Zero I/O: it
69
+ * reads the two legs of a `Sample` and nothing else (the OS reads live in `Sampler`),
70
+ * so its truth table is testable without a process or a tree. Both the idle window
71
+ * and the spawn instant are injected — the window never comes from a module constant
72
+ * and the clock never comes from the wall (a stall case must not wait out the real
73
+ * half hour), and the spawn instant seeds the idle clock.
74
+ *
75
+ * The rules, in the order they are applied:
76
+ * · an unreadable leg (`null`) → `unknown`, and unknown never kills (fail-open: no
77
+ * reading of a leg means no evidence of a stall, and an unreadable tick carries no
78
+ * observation either way);
79
+ * · CPU above the PREVIOUS observation, or mtime above the HISTORICAL MAXIMUM →
80
+ * `progress`, and the idle clock restarts at this tick;
81
+ * · no progress and the window is still open → `idled`;
82
+ * · no progress and the window is spent → `stalled` (the kill).
83
+ * Neither leg authorizes a kill alone (`unknown` covers the unreadable case) and
84
+ * output activity is deliberately NOT a signal: a thinking child is silent, and using
85
+ * silence against it would kill a child that is working. */
86
+ export class StallJudge {
87
+ #idleWindowMs;
88
+ /** The instant of the last progress — the spawn instant until the first one. */
89
+ #idleSince;
90
+ /** The previous tick's process-group CPU (ms) — `null` until the first readable one. */
91
+ #lastCpuMs = null;
92
+ /** The largest mtime (ms) the tree leg has ever reported. */
93
+ #maxMtimeMs = null;
94
+ constructor(idleWindowMs, spawnedAt) {
95
+ this.#idleWindowMs = idleWindowMs;
96
+ this.#idleSince = spawnedAt;
97
+ }
98
+ /** The idle time (ms) at `now` — how long since the last progress (the spawn instant
99
+ * until the first one). */
100
+ idleMs(now) {
101
+ return Math.max(0, now - this.#idleSince);
102
+ }
103
+ /** Judge one tick: feed the tick's sample and the instant it was taken. */
104
+ observe(sample, now) {
105
+ const cpuMs = sample.groupCpuMs;
106
+ const mtimeMs = sample.newestMtimeMs;
107
+ // Both legs must be readable to judge at all.
108
+ if (cpuMs === null || mtimeMs === null)
109
+ return "unknown";
110
+ // Progress is an advance over what has already been seen — this CPU over the
111
+ // previous observation, this mtime over the historical maximum. The first readable
112
+ // tick has neither, so it can never be a progress tick: the idle clock has been
113
+ // running since the spawn instant, exactly as if that tick had been flat.
114
+ const advanced = (this.#lastCpuMs !== null && cpuMs > this.#lastCpuMs) ||
115
+ (this.#maxMtimeMs !== null && mtimeMs > this.#maxMtimeMs);
116
+ this.#lastCpuMs = cpuMs;
117
+ if (this.#maxMtimeMs === null || mtimeMs > this.#maxMtimeMs)
118
+ this.#maxMtimeMs = mtimeMs;
119
+ if (advanced) {
120
+ this.#idleSince = now;
121
+ return "progress";
122
+ }
123
+ return now - this.#idleSince < this.#idleWindowMs ? "idled" : "stalled";
124
+ }
125
+ }
126
+ // ---------------------------------------------------------------------------
127
+ // the sampler — the two legs' heavy lifting (the only OS I/O of the stall face)
128
+ // ---------------------------------------------------------------------------
129
+ /** Sampler — one dispatch's two legs, read once per tick: the process group's
130
+ * cumulative CPU and the newest content mtime of the scanned tree. The I/O lives
131
+ * here and the judgment lives in `StallJudge`, so each face is testable on its own
132
+ * (the truth table without a process, the fail-open `null` without a judge).
133
+ *
134
+ * · The group id is the child's own pid, never recomputed: `killDescendants` forces
135
+ * the spawn-layer detachment, so the child IS its process group leader — the same
136
+ * fact execa's own `process.kill(-pid)` kill rides.
137
+ * · The scan root is the child's cwd (the repo root), so the "scan root ≡ child cwd"
138
+ * correspondence is structural.
139
+ * · `exclude` is the engine's own writes — `Sampler.excludesFor` is its single
140
+ * source: the repo's `.git/` and the dispatch's heartbeat file. The rest of
141
+ * `.kairos/` is NOT excluded: a child's handoff draft there is real progress. */
142
+ export class Sampler {
143
+ /** The deepest tree level the walk descends to. */
144
+ static MAX_DEPTH = 32;
145
+ /** The VCS internal every scan skips — its mtime is never a round's progress. */
146
+ static VCS_DIR = ".git";
147
+ /** A `ps -o time=` reading: `[DD-][HH:]MM:SS[.ff]` (BSD gives centiseconds, Linux
148
+ * whole seconds — both ride the same pattern). */
149
+ static TIME_PATTERN = /^(?:(\d+)-)?(?:(\d+):(\d+):(\d+(?:\.\d+)?)|(\d+):(\d+(?:\.\d+)?))$/;
150
+ #pgid;
151
+ #scanRoot;
152
+ #exclude;
153
+ constructor(options) {
154
+ this.#pgid = options.pgid;
155
+ // Absolute, normalized forms on both sides of the comparison below, so an
156
+ // exclusion matches the walked path it names.
157
+ this.#scanRoot = path.resolve(options.scanRoot);
158
+ this.#exclude = new Set(options.exclude.map((entry) => path.resolve(entry)));
159
+ }
160
+ /** The exclusion single source for one dispatch: the repo's VCS internal plus the
161
+ * heartbeat path the engine itself writes (a tick must never self-certify). */
162
+ static excludesFor(scanRoot, heartbeatPath) {
163
+ return [path.join(scanRoot, _a.VCS_DIR), heartbeatPath];
164
+ }
165
+ /** Read both legs of this tick — each independently fail-open: a leg the platform
166
+ * cannot read is `null`, never a fabricated reading. */
167
+ probe() {
168
+ return { groupCpuMs: this.#groupCpuMs(), newestMtimeMs: this.#newestMtimeMs() };
169
+ }
170
+ /** The process group's cumulative CPU (ms), summed over the group's processes. A
171
+ * non-zero `ps` exit (no such group, or no `ps` at all) or any unparseable line
172
+ * makes the leg unreadable — `null`. An empty reading is unreadable too: a group
173
+ * with no observable member is not evidence of zero CPU. */
174
+ #groupCpuMs() {
175
+ let output;
176
+ try {
177
+ output = execFileSync("ps", ["-o", "time=", "-g", String(this.#pgid)], {
178
+ encoding: "utf8",
179
+ // stdout only: `ps`'s own complaint about an unknown group is not a reading,
180
+ // and it must never reach the engine's stderr channel.
181
+ stdio: ["ignore", "pipe", "ignore"],
182
+ });
183
+ }
184
+ catch {
185
+ return null;
186
+ }
187
+ const lines = output
188
+ .split("\n")
189
+ .map((line) => line.trim())
190
+ .filter((line) => line.length > 0);
191
+ if (lines.length === 0)
192
+ return null;
193
+ let total = 0;
194
+ for (const line of lines) {
195
+ const ms = _a.#parseCpuTime(line);
196
+ if (ms === null)
197
+ return null;
198
+ total += ms;
199
+ }
200
+ return total;
201
+ }
202
+ /** One `time=` reading as milliseconds — `null` when the text is not that format. */
203
+ static #parseCpuTime(text) {
204
+ const match = _a.TIME_PATTERN.exec(text);
205
+ if (match === null)
206
+ return null;
207
+ const days = Number(match[1] ?? 0);
208
+ const hours = Number(match[2] ?? 0);
209
+ const minutes = Number(match[3] ?? match[5] ?? 0);
210
+ const seconds = Number(match[4] ?? match[6] ?? 0);
211
+ return (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
212
+ }
213
+ /** The newest content mtime (ms) in the scanned tree — `null` when the walk cannot
214
+ * complete (an unreadable directory anywhere makes the whole leg unreadable rather
215
+ * than under-reporting). */
216
+ #newestMtimeMs() {
217
+ try {
218
+ return this.#newestIn(this.#scanRoot, 0);
219
+ }
220
+ catch {
221
+ return null;
222
+ }
223
+ }
224
+ /** The recursive descent — symlinks and the engine's own paths skipped, `MAX_DEPTH`
225
+ * as the floor of the walk. */
226
+ #newestIn(dir, depth) {
227
+ if (depth > _a.MAX_DEPTH)
228
+ return null;
229
+ let newest = null;
230
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
231
+ const child = path.join(dir, entry.name);
232
+ // A symlink is never followed (it can leave the tree outright); an excluded path
233
+ // is the engine's own write.
234
+ if (entry.isSymbolicLink() || this.#exclude.has(child))
235
+ continue;
236
+ if (entry.isDirectory()) {
237
+ const nested = this.#newestIn(child, depth + 1);
238
+ if (nested !== null && (newest === null || nested > newest))
239
+ newest = nested;
240
+ continue;
241
+ }
242
+ // Content mtimes only: a directory's own mtime moves on entry churn, which the
243
+ // CPU leg already reflects as work — and the heartbeat's first creation would
244
+ // otherwise bump its directory and self-certify a progress tick.
245
+ const mtimeMs = statSync(child).mtimeMs;
246
+ if (newest === null || mtimeMs > newest)
247
+ newest = mtimeMs;
248
+ }
249
+ return newest;
250
+ }
251
+ }
252
+ _a = Sampler;
253
+ // ---------------------------------------------------------------------------
254
+ // the sampling loop — the dispatch's heartbeat trail (§3.4)
255
+ // ---------------------------------------------------------------------------
256
+ /** The sampling loop of one dispatch — the cadence that wraps the running child: one
257
+ * sample the moment the child is spawned, then one per `intervalMs`. Each tick reads
258
+ * the two legs through the `Sampler`, has the `StallJudge` rule on them, and
259
+ * overwrites the dispatch's heartbeat file with the resulting `SampleRecord` — the
260
+ * trail a human reads after a round was cut short. A `stalled` verdict fires the
261
+ * loop's `onStall` callback once — the Terminator's kill trigger (the engine's own
262
+ * group kill; the SIGTERM → SIGKILL escalation is execa's).
263
+ *
264
+ * The interval is unref'd: the engine's own sampling must never be the reason the
265
+ * parent process stays alive (the dispatch awaits the child, not the cadence). The
266
+ * heartbeat write is a plain overwrite, deliberately NOT a write-then-rename: a
267
+ * temporary file would sit inside the scanned tree and its own creation would certify
268
+ * "progress" — the very self-report the exclusion exists to prevent. Both the write
269
+ * and the removal are fail-open: the trail is a diagnostic, never a dispatch's fate.
270
+ *
271
+ * The last observation is held in memory (`lastSample`): a terminated round's crash
272
+ * record takes it from there, never by re-reading the file the engine itself wrote. */
273
+ class SamplingLoop {
274
+ #sampler;
275
+ #judge;
276
+ #heartbeatPath;
277
+ #intervalMs;
278
+ /** The stall trigger — called once on the first `stalled` verdict (the kill). */
279
+ #onStall;
280
+ /** Whether the stall verdict has already fired — one kill per dispatch. */
281
+ #stallFired = false;
282
+ /** The most recent observation — the postmortem sample of a terminated round. */
283
+ #last = null;
284
+ #timer = null;
285
+ constructor(options) {
286
+ this.#sampler = options.sampler;
287
+ this.#judge = options.judge;
288
+ this.#heartbeatPath = options.heartbeatPath;
289
+ this.#intervalMs = options.intervalMs;
290
+ this.#onStall = options.onStall;
291
+ }
292
+ /** Sample at once (the spawn instant has just passed — a round is never observed
293
+ * only from the first interval on) and start the cadence. */
294
+ start() {
295
+ this.#tick(Date.now());
296
+ this.#timer = setInterval(() => this.#tick(Date.now()), this.#intervalMs);
297
+ // Never hold the parent process open for the engine's own sampling.
298
+ this.#timer.unref();
299
+ }
300
+ /** The loop's last observation (null when no tick was ever taken) — the sample a
301
+ * terminated round's crash record carries, from memory. */
302
+ lastSample() {
303
+ return this.#last;
304
+ }
305
+ /** The judge's idle reading (ms) at this instant — the termination fact's idle time. */
306
+ idleMs() {
307
+ return this.#judge.idleMs(Date.now());
308
+ }
309
+ /** End the loop at the dispatch's terminal state: the cadence stops, and the
310
+ * heartbeat is removed iff the round ended by itself — a terminated round's file
311
+ * stays for a human's postmortem. */
312
+ stop(endedByItself) {
313
+ if (this.#timer !== null) {
314
+ clearInterval(this.#timer);
315
+ this.#timer = null;
316
+ }
317
+ if (!endedByItself)
318
+ return;
319
+ try {
320
+ rmSync(this.#heartbeatPath, { force: true });
321
+ }
322
+ catch {
323
+ // Fail-open (see the class doc).
324
+ }
325
+ }
326
+ /** One tick: read both legs, judge them, and overwrite the heartbeat record. A
327
+ * `stalled` verdict fires the kill trigger once (the first stall owns the kill;
328
+ * later ticks of a dying child never re-fire). */
329
+ #tick(now) {
330
+ const sample = this.#sampler.probe();
331
+ const verdict = this.#judge.observe(sample, now);
332
+ const record = {
333
+ sampledAt: now,
334
+ groupCpuMs: sample.groupCpuMs,
335
+ newestMtimeMs: sample.newestMtimeMs,
336
+ verdict,
337
+ };
338
+ this.#last = record;
339
+ try {
340
+ writeFileSync(this.#heartbeatPath, `${JSON.stringify(record, null, 2)}\n`, "utf8");
341
+ }
342
+ catch {
343
+ // Fail-open (see the class doc): an unwritable heartbeat slows nothing down.
344
+ }
345
+ if (verdict === "stalled" && !this.#stallFired) {
346
+ this.#stallFired = true;
347
+ this.#onStall?.();
348
+ }
349
+ }
350
+ }
351
+ // ---------------------------------------------------------------------------
352
+ // the production runner — execa's asynchronous face
353
+ // ---------------------------------------------------------------------------
354
+ /** Terminator — the production `ChildRunner`: one child, its whole process
355
+ * lifecycle. Every process capability the seam needs is execa's, never the
356
+ * engine's:
357
+ * · `killDescendants: true` — the child is spawned as its own process group and
358
+ * the group is killed as a unit (execa forces the spawn-layer detachment
359
+ * internally; the user-facing `detached` option is never set, because it would
360
+ * short-circuit execa's parent-exit `cleanup`);
361
+ * · `forceKillAfterDelay` — SIGTERM, then SIGKILL after the grace (execa's own
362
+ * default written out, so the escalation is pinned at the call site);
363
+ * · `timeout` — the phase's wall-clock ceiling on the same kill path;
364
+ * · `reject: false` + `stripFinalNewline: false` — the fail-open result face, the
365
+ * child's stdout kept byte-verbatim;
366
+ * · `maxBuffer` is never set or lowered — execa's own 100 MB default is the
367
+ * unbounded-face successor of the retired fixed 1 MiB cap;
368
+ * · the sampling loop — the child is sampled from the spawn instant and every
369
+ * `policy.sampleIntervalMs` after (the heartbeat file is that loop's trail, and
370
+ * the judge's verdict rides every record).
371
+ * The class holds zero session state: everything a dispatch needs rides the
372
+ * `ChildRun` argument, so the composition root wires it without a scene. */
373
+ export class Terminator {
374
+ /** The force-kill grace (ms) — SIGTERM, then SIGKILL after this delay (execa's
375
+ * default, pinned explicitly). */
376
+ static FORCE_KILL_AFTER_DELAY_MS = 5000;
377
+ async run(run) {
378
+ // The spawn instant seeds the judge's idle clock (§3.3).
379
+ const spawnedAt = Date.now();
380
+ // The engine's own stall kill — set by the sampling loop's trigger when the
381
+ // judge rules `stalled` AND the kill is delivered; the derivation reads it to
382
+ // attribute the kill (the signal execa reports for OUR kill would otherwise
383
+ // read as an external one).
384
+ let killedByStall = false;
385
+ const subprocess = execa(run.command, [...run.args], {
386
+ cwd: run.cwd,
387
+ reject: false,
388
+ stripFinalNewline: false,
389
+ // fd 0 on /dev/null: a child that reads stdin sees EOF at once, never a pipe nobody closes.
390
+ stdin: "ignore",
391
+ killDescendants: true,
392
+ forceKillAfterDelay: Terminator.FORCE_KILL_AFTER_DELAY_MS,
393
+ timeout: run.policy.budgetMs,
394
+ });
395
+ // Reclaim the group the instant the direct child exits: a grandchild holding the stdout
396
+ // / stderr pipes would otherwise keep the `await` open. No execa option does this (its
397
+ // group kill is on-demand only), so execa's own group-aware `kill()` is called once, at
398
+ // the `exit` event, and only on the group the engine created (`killDescendants`). With
399
+ // live members the pgid is still reserved; with none (no grandchild) the kill is a no-op
400
+ // unless the pgid was reused inside a vanishingly small window. Every ordinary child exit in
401
+ // termination.test.ts (no grandchild) passes through this kill.
402
+ subprocess.nodeChildProcess.once("exit", () => {
403
+ subprocess.kill();
404
+ });
405
+ const sampling = this.#startSampling(run, subprocess.pid, spawnedAt, () => {
406
+ // The engine's own group kill — execa kills the process group and escalates
407
+ // SIGTERM → SIGKILL after the grace. No signal logic of the engine's own.
408
+ // The flag records DELIVERY, not intent: `kill()` returns false when the signal
409
+ // could not be sent (the child already exited), so a round that ended by itself
410
+ // in the same tick is not misattributed as `stalled`.
411
+ if (subprocess.kill())
412
+ killedByStall = true;
413
+ });
414
+ // The round's heartbeat fate — terminated by default, so an unexpected throw keeps
415
+ // the trail as well; a round that ends by itself leaves no file behind.
416
+ let endedByItself = false;
417
+ try {
418
+ const result = await subprocess;
419
+ const termination = Terminator.terminationOf({
420
+ timedOut: result.timedOut,
421
+ killedByStall,
422
+ signal: result.signal,
423
+ isTerminated: result.isTerminated,
424
+ idleMs: sampling?.idleMs() ?? 0,
425
+ lastSample: sampling?.lastSample() ?? null,
426
+ });
427
+ endedByItself = termination === null;
428
+ return {
429
+ // The child's OWN exit code, unfolded: null means "never spawned / signalled",
430
+ // never a fabricated 1 (which would misreport both as an ordinary failed run).
431
+ code: result.exitCode ?? null,
432
+ stdout: result.stdout,
433
+ // The child's own stderr when it wrote one, else execa's diagnostic (a spawn
434
+ // failure like ENOENT writes nothing, so its reason rides the `shortMessage` —
435
+ // the fail-open face keeps a reason text, never an empty block).
436
+ stderr: result.stderr || (result.failed ? (result.shortMessage ?? "") : ""),
437
+ termination,
438
+ };
439
+ }
440
+ finally {
441
+ // The cadence never outlives the dispatch.
442
+ sampling?.stop(endedByItself);
443
+ }
444
+ }
445
+ /** Start the dispatch's sampling loop, or null when the child never spawned (a
446
+ * broken command has no pid: nothing to sample and nothing to postmortem). The
447
+ * group id is the child's OWN pid, never recomputed — `killDescendants` forces the
448
+ * spawn-layer detachment, so the child IS its process group leader (the same fact
449
+ * execa's own group kill rides); the scan root is the same `cwd` the child was
450
+ * spawned in. The stall trigger rides through: the loop's first `stalled` verdict
451
+ * is the kill's authorization. */
452
+ #startSampling(run, pid, spawnedAt, onStall) {
453
+ if (pid === undefined)
454
+ return null;
455
+ const sampling = new SamplingLoop({
456
+ sampler: new Sampler({
457
+ pgid: pid,
458
+ scanRoot: run.cwd,
459
+ exclude: Sampler.excludesFor(run.cwd, run.heartbeatPath),
460
+ }),
461
+ judge: new StallJudge(run.policy.idleWindowMs, spawnedAt),
462
+ heartbeatPath: run.heartbeatPath,
463
+ intervalMs: run.policy.sampleIntervalMs,
464
+ onStall,
465
+ });
466
+ sampling.start();
467
+ return sampling;
468
+ }
469
+ /** Derive the termination fact from the child's own result face — the four-way
470
+ * derivation (§4.1), in the order the causes claim a kill (package-visible, so the
471
+ * table-driven pin can rule on every branch without a real child):
472
+ * · the wall-clock ceiling (execa's `timedOut`) → `over-budget`;
473
+ * · the engine's own stall kill → `stalled` (ahead of the signal leg: OUR kill
474
+ * also arrives as a signal, and misreading it as external would falsify the
475
+ * postmortem);
476
+ * · any other signal → `signal` (the external-kill semantic, never the SIGTERM
477
+ * literal — SIGTERM / SIGKILL / SIGINT / SIGHUP read the same);
478
+ * · none of the three but the child was terminated anyway → `unknown` (the
479
+ * unattributable fallback);
480
+ * · nothing of the above → the round ended by itself (successfully or not), no
481
+ * termination.
482
+ * The last sample rides whichever cause won: it is the sampling loop's own last
483
+ * observation, held in memory — never a re-read of the heartbeat file the engine
484
+ * itself wrote.
485
+ *
486
+ * `killedByStall` records that OUR kill was delivered (execa's `kill()` returns
487
+ * false when the signal could not be sent — a child that already exited is not
488
+ * attributed here). Residual boundary: a child that exits within the same tick
489
+ * while its process group still exists (a zombie not yet reaped) can still be
490
+ * signalled and read `stalled` — the idle verdict, not the kill landing, is the
491
+ * criterion. */
492
+ static terminationOf(facts) {
493
+ const { timedOut, killedByStall, signal, isTerminated, idleMs, lastSample } = facts;
494
+ if (timedOut)
495
+ return { cause: "over-budget", idleMs, lastSample };
496
+ if (killedByStall)
497
+ return { cause: "stalled", idleMs, lastSample };
498
+ if (signal !== undefined)
499
+ return { cause: "signal", idleMs, lastSample };
500
+ if (isTerminated)
501
+ return { cause: "unknown", idleMs, lastSample };
502
+ return null;
503
+ }
504
+ }