@oscaner-skills/cdd-engine 4.2.0 → 4.3.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 (55) hide show
  1. package/README.md +38 -9
  2. package/README.zh-CN.md +43 -9
  3. package/dist/contract/completion-criterion.js +351 -0
  4. package/dist/contract/declare.js +181 -43
  5. package/dist/contract/doc.js +84 -271
  6. package/dist/contract/frontmatter.js +2 -1
  7. package/dist/contract/home-extractors.js +49 -316
  8. package/dist/contract/invariants.js +400 -296
  9. package/dist/contract/judge.js +74 -49
  10. package/dist/contract/lint.js +3 -2
  11. package/dist/contract/liveness-signal.js +103 -0
  12. package/dist/contract/markdown-document.js +410 -0
  13. package/dist/contract/markdown-tree-types.js +6 -0
  14. package/dist/contract/markdown-tree.js +137 -0
  15. package/dist/contract/project.js +1 -1
  16. package/dist/contract/rules.js +106 -0
  17. package/dist/contract/selector-engine.js +332 -0
  18. package/dist/contract/selector-spec.js +74 -0
  19. package/dist/contract/skill-anatomy.js +29 -1
  20. package/dist/contract/task-block-grammar.js +285 -0
  21. package/dist/contract/task-blocks.js +65 -0
  22. package/dist/contract/translate.js +21 -0
  23. package/dist/contract/wave-width.js +15 -0
  24. package/dist/face/board-view.js +401 -131
  25. package/dist/face/capsule.js +66 -89
  26. package/dist/face/cli.js +116 -35
  27. package/dist/face/declare.js +36 -18
  28. package/dist/face/gate.js +117 -40
  29. package/dist/face/init.js +1 -1
  30. package/dist/face/lifecycle.js +540 -123
  31. package/dist/face/preview.js +43 -10
  32. package/dist/face/route-render.js +51 -21
  33. package/dist/face/termination.js +135 -261
  34. package/dist/face/words.js +134 -12
  35. package/dist/infra/atomic.js +15 -0
  36. package/dist/infra/git.js +25 -0
  37. package/dist/infra/proc.js +150 -0
  38. package/dist/infra/round-log.js +104 -0
  39. package/dist/infra/runtime.js +16 -4
  40. package/dist/infra/workspace.js +7 -2
  41. package/dist/render/brief.js +15 -17
  42. package/dist/render/skeleton.js +41 -28
  43. package/dist/render/templates.js +128 -84
  44. package/dist/session/faces.js +47 -20
  45. package/dist/session/graph.js +13 -37
  46. package/dist/session/handoff-schema.js +16 -8
  47. package/dist/session/inflight.js +282 -0
  48. package/dist/session/ledger.js +581 -136
  49. package/dist/session/line-identity.js +33 -0
  50. package/dist/session/next.js +138 -80
  51. package/dist/session/preflight.js +276 -68
  52. package/dist/session/round-naming.js +56 -8
  53. package/dist/session/run.js +317 -78
  54. package/dist/session/wave.js +94 -14
  55. package/package.json +13 -3
@@ -7,9 +7,9 @@
7
7
  //
8
8
  // The seam's two ends are value objects, so the whole child lifecycle speaks one
9
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 + the per-host
12
- // dispatch env);
10
+ // · `ChildRun` — one dispatch's full context (command/args/cwd + the in-flight
11
+ // record handle the sampler overwrites + the termination policy of the phase +
12
+ // the per-host dispatch env);
13
13
  // · `ChildOutcome` — the child's result (its own exit code, verbatim streams)
14
14
  // plus the `termination` fact: non-null ⟺ the round was cut short. The
15
15
  // terminated round's downstream judgments all read that one fact, never the
@@ -17,11 +17,8 @@
17
17
  //
18
18
  // Module-level exports are types / the value object / the class — zero
19
19
  // behavior-carrying bare functions.
20
- var _a;
21
- import { execFileSync } from "node:child_process";
22
- import { readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
23
- import path from "node:path";
24
20
  import { execa } from "execa";
21
+ import { LIVENESS_SIGNALS, LivenessJudge, } from "../contract/liveness-signal.js";
25
22
  // ---------------------------------------------------------------------------
26
23
  // the constant single source — budget and timing, per dispatch phase
27
24
  // ---------------------------------------------------------------------------
@@ -67,240 +64,116 @@ export class TerminationPolicy {
67
64
  return new TerminationPolicy(TerminationPolicy.BUDGET_MS[phase]);
68
65
  }
69
66
  }
70
- // ---------------------------------------------------------------------------
71
- // the stall judge — the running judgment over one dispatch, pure logic
72
- // ---------------------------------------------------------------------------
73
- /** StallJudge — is this dispatch still moving? Not a comparison of two samples but a
74
- * judgment over the round: the judge holds its own accumulating state and is fed one
75
- * tick at a time through `observe`, which returns the tick's verdict. Zero I/O: it
76
- * reads the two legs of a `Sample` and nothing else (the OS reads live in `Sampler`),
77
- * so its truth table is testable without a process or a tree. Both the idle window
78
- * and the spawn instant are injected — the window never comes from a module constant
79
- * and the clock never comes from the wall (a stall case must not wait out the real
80
- * half hour), and the spawn instant seeds the idle clock.
81
- *
82
- * The rules, in the order they are applied:
83
- * · an unreadable leg (`null`) → `unknown`, and unknown never kills (fail-open: no
84
- * reading of a leg means no evidence of a stall, and an unreadable tick carries no
85
- * observation either way);
86
- * · CPU above the PREVIOUS observation, or mtime above the HISTORICAL MAXIMUM →
87
- * `progress`, and the idle clock restarts at this tick;
88
- * · no progress and the window is still open → `idled`;
89
- * · no progress and the window is spent → `stalled` (the kill).
90
- * Neither leg authorizes a kill alone (`unknown` covers the unreadable case) and
91
- * output activity is deliberately NOT a signal: a thinking child is silent, and using
92
- * silence against it would kill a child that is working. */
93
- export class StallJudge {
94
- #idleWindowMs;
95
- /** The instant of the last progress — the spawn instant until the first one. */
96
- #idleSince;
97
- /** The previous tick's process-group CPU (ms) — `null` until the first readable one. */
98
- #lastCpuMs = null;
99
- /** The largest mtime (ms) the tree leg has ever reported. */
100
- #maxMtimeMs = null;
101
- constructor(idleWindowMs, spawnedAt) {
102
- this.#idleWindowMs = idleWindowMs;
103
- this.#idleSince = spawnedAt;
104
- }
105
- /** The idle time (ms) at `now` — how long since the last progress (the spawn instant
106
- * until the first one). */
107
- idleMs(now) {
108
- return Math.max(0, now - this.#idleSince);
109
- }
110
- /** Judge one tick: feed the tick's sample and the instant it was taken. */
111
- observe(sample, now) {
112
- const cpuMs = sample.groupCpuMs;
113
- const mtimeMs = sample.newestMtimeMs;
114
- // Both legs must be readable to judge at all.
115
- if (cpuMs === null || mtimeMs === null)
116
- return "unknown";
117
- // Progress is an advance over what has already been seen — this CPU over the
118
- // previous observation, this mtime over the historical maximum. The first readable
119
- // tick has neither, so it can never be a progress tick: the idle clock has been
120
- // running since the spawn instant, exactly as if that tick had been flat.
121
- const advanced = (this.#lastCpuMs !== null && cpuMs > this.#lastCpuMs) ||
122
- (this.#maxMtimeMs !== null && mtimeMs > this.#maxMtimeMs);
123
- this.#lastCpuMs = cpuMs;
124
- if (this.#maxMtimeMs === null || mtimeMs > this.#maxMtimeMs)
125
- this.#maxMtimeMs = mtimeMs;
126
- if (advanced) {
127
- this.#idleSince = now;
128
- return "progress";
129
- }
130
- return now - this.#idleSince < this.#idleWindowMs ? "idled" : "stalled";
131
- }
132
- }
133
- // ---------------------------------------------------------------------------
134
- // the sampler — the two legs' heavy lifting (the only OS I/O of the stall face)
135
- // ---------------------------------------------------------------------------
136
- /** Sampler — one dispatch's two legs, read once per tick: the process group's
137
- * cumulative CPU and the newest content mtime of the scanned tree. The I/O lives
138
- * here and the judgment lives in `StallJudge`, so each face is testable on its own
139
- * (the truth table without a process, the fail-open `null` without a judge).
67
+ /**
68
+ * Sampler — one dispatch's legs, read once per tick. The sampler BUILDS this round's
69
+ * signals from this round's `LivenessContext` (`LIVENESS_SIGNALS` is a per-round
70
+ * factory, never a module-level instance array), so each round's self-held state
71
+ * (`readableAt`) belongs to that round alone, and it holds the previous tick's values —
72
+ * the progress comparison basis lives with the cadence, exactly one tick wide.
140
73
  *
141
- * · The group id is the child's own pid, never recomputed: `killDescendants` forces
142
- * the spawn-layer detachment, so the child IS its process group leader — the same
143
- * fact execa's own `process.kill(-pid)` kill rides.
144
- * · The scan root is the child's cwd (the repo root), so the "scan root ≡ child cwd"
145
- * correspondence is structural.
146
- * · `exclude` is the engine's own writes — `Sampler.excludesFor` is its single
147
- * source: the repo's `.git/` and the dispatch's heartbeat file. The rest of
148
- * `.kairos/` is NOT excluded: a child's handoff draft there is real progress. */
74
+ * The legs are the CHILD's own evidence (design spec §4.3): its round log file and its
75
+ * process group's CPU. Nothing in the workspace tree is scanned any more, so a third
76
+ * party's write into the repo can never certify progress — that claim is structural
77
+ * now, not an exclusion list.
78
+ */
149
79
  export class Sampler {
150
- /** The deepest tree level the walk descends to. */
151
- static MAX_DEPTH = 32;
152
- /** The VCS internal every scan skips — its mtime is never a round's progress. */
153
- static VCS_DIR = ".git";
154
- /** A `ps -o time=` reading: `[DD-][HH:]MM:SS[.ff]` (BSD gives centiseconds, Linux
155
- * whole seconds — both ride the same pattern). */
156
- static TIME_PATTERN = /^(?:(\d+)-)?(?:(\d+):(\d+):(\d+(?:\.\d+)?)|(\d+):(\d+(?:\.\d+)?))$/;
157
- #pgid;
158
- #scanRoot;
159
- #exclude;
160
- constructor(options) {
161
- this.#pgid = options.pgid;
162
- // Absolute, normalized forms on both sides of the comparison below, so an
163
- // exclusion matches the walked path it names.
164
- this.#scanRoot = path.resolve(options.scanRoot);
165
- this.#exclude = new Set(options.exclude.map((entry) => path.resolve(entry)));
80
+ #signals;
81
+ #previous;
82
+ /** `signals` is the per-round registry; the production default is the declared
83
+ * `LIVENESS_SIGNALS`, and a caller may inject its own leg set (the deterministic
84
+ * sampling pin drives scripted readings through the same judge, so the four-state
85
+ * attribution never depends on real CPU resolution or a machine's timing). */
86
+ constructor(context, signals = LIVENESS_SIGNALS) {
87
+ this.#signals = signals.map(({ leg, create }) => ({ leg, signal: create(context) }));
88
+ this.#previous = this.#signals.map(() => null);
166
89
  }
167
- /** The exclusion single source for one dispatch: the repo's VCS internal plus the
168
- * heartbeat path the engine itself writes (a tick must never self-certify). */
169
- static excludesFor(scanRoot, heartbeatPath) {
170
- return [path.join(scanRoot, _a.VCS_DIR), heartbeatPath];
171
- }
172
- /** Read both legs of this tick — each independently fail-open: a leg the platform
173
- * cannot read is `null`, never a fabricated reading. */
90
+ /** Read every leg of this tick — each independently fail-open (`null`, never a
91
+ * fabricated reading) — and advance the previous-reading basis. */
174
92
  probe() {
175
- return { groupCpuMs: this.#groupCpuMs(), newestMtimeMs: this.#newestMtimeMs() };
176
- }
177
- /** The process group's cumulative CPU (ms), summed over the group's processes. A
178
- * non-zero `ps` exit (no such group, or no `ps` at all) or any unparseable line
179
- * makes the leg unreadable — `null`. An empty reading is unreadable too: a group
180
- * with no observable member is not evidence of zero CPU. */
181
- #groupCpuMs() {
182
- let output;
183
- try {
184
- output = execFileSync("ps", ["-o", "time=", "-g", String(this.#pgid)], {
185
- encoding: "utf8",
186
- // stdout only: `ps`'s own complaint about an unknown group is not a reading,
187
- // and it must never reach the engine's stderr channel.
188
- stdio: ["ignore", "pipe", "ignore"],
189
- });
190
- }
191
- catch {
192
- return null;
193
- }
194
- const lines = output
195
- .split("\n")
196
- .map((line) => line.trim())
197
- .filter((line) => line.length > 0);
198
- if (lines.length === 0)
199
- return null;
200
- let total = 0;
201
- for (const line of lines) {
202
- const ms = _a.#parseCpuTime(line);
203
- if (ms === null)
204
- return null;
205
- total += ms;
206
- }
207
- return total;
208
- }
209
- /** One `time=` reading as milliseconds — `null` when the text is not that format. */
210
- static #parseCpuTime(text) {
211
- const match = _a.TIME_PATTERN.exec(text);
212
- if (match === null)
213
- return null;
214
- const days = Number(match[1] ?? 0);
215
- const hours = Number(match[2] ?? 0);
216
- const minutes = Number(match[3] ?? match[5] ?? 0);
217
- const seconds = Number(match[4] ?? match[6] ?? 0);
218
- return (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
93
+ const readings = this.#signals.map((entry) => entry.signal.sample());
94
+ const previous = [...this.#previous];
95
+ readings.forEach((reading, index) => {
96
+ this.#previous[index] = reading.value;
97
+ });
98
+ return {
99
+ readings,
100
+ previous,
101
+ logSize: this.#valueOf(readings, "log"),
102
+ cpuMs: this.#valueOf(readings, "cpu"),
103
+ };
219
104
  }
220
- /** The newest content mtime (ms) in the scanned tree — `null` when the walk cannot
221
- * complete (an unreadable directory anywhere makes the whole leg unreadable rather
222
- * than under-reporting). */
223
- #newestMtimeMs() {
224
- try {
225
- return this.#newestIn(this.#scanRoot, 0);
226
- }
227
- catch {
228
- return null;
229
- }
230
- }
231
- /** The recursive descent — symlinks and the engine's own paths skipped, `MAX_DEPTH`
232
- * as the floor of the walk. */
233
- #newestIn(dir, depth) {
234
- if (depth > _a.MAX_DEPTH)
235
- return null;
236
- let newest = null;
237
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
238
- const child = path.join(dir, entry.name);
239
- // A symlink is never followed (it can leave the tree outright); an excluded path
240
- // is the engine's own write.
241
- if (entry.isSymbolicLink() || this.#exclude.has(child))
242
- continue;
243
- if (entry.isDirectory()) {
244
- const nested = this.#newestIn(child, depth + 1);
245
- if (nested !== null && (newest === null || nested > newest))
246
- newest = nested;
247
- continue;
248
- }
249
- // Content mtimes only: a directory's own mtime moves on entry churn, which the
250
- // CPU leg already reflects as work — and the heartbeat's first creation would
251
- // otherwise bump its directory and self-certify a progress tick.
252
- const mtimeMs = statSync(child).mtimeMs;
253
- if (newest === null || mtimeMs > newest)
254
- newest = mtimeMs;
255
- }
256
- return newest;
105
+ /** One tick's reading of a NAMED leg — the postmortem cells address legs by name, so
106
+ * inserting or reordering a leg cannot silently swap `logSize` and `cpuMs`. A leg
107
+ * the registry does not declare reads `null` (the fail-open face). */
108
+ #valueOf(readings, leg) {
109
+ const index = this.#signals.findIndex((entry) => entry.leg === leg);
110
+ return index < 0 ? null : (readings[index]?.value ?? null);
257
111
  }
258
112
  }
259
- _a = Sampler;
260
113
  // ---------------------------------------------------------------------------
261
- // the sampling loop — the dispatch's heartbeat trail (§3.4)
114
+ // the sampling loop — the dispatch's in-flight sampling trail (§3.4)
262
115
  // ---------------------------------------------------------------------------
263
- /** The sampling loop of one dispatch — the cadence that wraps the running child: one
264
- * sample the moment the child is spawned, then one per `intervalMs`. Each tick reads
265
- * the two legs through the `Sampler`, has the `StallJudge` rule on them, and
266
- * overwrites the dispatch's heartbeat file with the resulting `SampleRecord` — the
267
- * trail a human reads after a round was cut short. A `stalled` verdict fires the
268
- * loop's `onStall` callback once — the Terminator's kill trigger (the engine's own
269
- * group kill; the SIGTERM → SIGKILL escalation is execa's).
116
+ /**
117
+ * SamplingLoop — the sampling loop of one dispatch: the cadence that wraps the running
118
+ * child — one sample the moment the child is spawned, then one per `intervalMs`. Each
119
+ * tick reads the legs through the `Sampler`, has the `LivenessJudge` rule on them (the
120
+ * idle clock lives here, seeded by the spawn instant and restarted on every
121
+ * `progress`), and overwrites the dispatch's in-flight record sampling cells through
122
+ * `InFlight` — the ONE record, never a second file beside it. A `stalled` verdict
123
+ * fires the loop's `onStall` callback once — the Terminator's kill trigger (the
124
+ * engine's own group kill; the SIGTERM → SIGKILL escalation is execa's) — and ENDS the
125
+ * cadence: after the engine's own kill, further ticks observe only a dying process,
126
+ * so the postmortem sample must stay the stall that authorized the kill (a later
127
+ * `ps` miss would otherwise overwrite it with `unknown`).
270
128
  *
271
129
  * The interval is unref'd: the engine's own sampling must never be the reason the
272
130
  * parent process stays alive (the dispatch awaits the child, not the cadence). The
273
- * heartbeat write is a plain overwrite, deliberately NOT a write-then-rename: a
274
- * temporary file would sit inside the scanned tree and its own creation would certify
275
- * "progress" — the very self-report the exclusion exists to prevent. Both the write
276
- * and the removal are fail-open: the trail is a diagnostic, never a dispatch's fate.
131
+ * trail WRITE is fail-open (`InFlight.heartbeat` swallows a failed write): a
132
+ * diagnostic never decides a dispatch's fate. The clock is injectable (wall clock by
133
+ * default), so a pin drives ticks at explicit instants instead of waiting out the
134
+ * real cadence. The loop NEVER removes the record — removal belongs to
135
+ * `InFlight.release()` (the normal end) and `InFlight.steal()` (the explicit
136
+ * takeover) alone, so a self-ending round that still has to hand its conclusion back
137
+ * cannot erase the very fact the gate reads.
277
138
  *
278
139
  * The last observation is held in memory (`lastSample`): a terminated round's crash
279
140
  * record takes it from there, never by re-reading the file the engine itself wrote. */
280
- class SamplingLoop {
141
+ export class SamplingLoop {
281
142
  #sampler;
282
143
  #judge;
283
- #heartbeatPath;
144
+ #inflight;
284
145
  #intervalMs;
146
+ #idleWindowMs;
285
147
  /** The stall trigger — called once on the first `stalled` verdict (the kill). */
286
148
  #onStall;
287
- /** Whether the stall verdict has already fired — one kill per dispatch. */
149
+ /** Whether the stall verdict has already fired — one kill per dispatch, and no
150
+ * further sample after it (the trail's last cell is the stall). */
288
151
  #stallFired = false;
289
152
  /** The most recent observation — the postmortem sample of a terminated round. */
290
153
  #last = null;
291
154
  #timer = null;
155
+ /** The instant of the last progress — the spawn instant until the first one. */
156
+ #idleSince;
157
+ /** The tick clock (wall clock by default) — the pin injects a fake one. */
158
+ #clock;
292
159
  constructor(options) {
293
160
  this.#sampler = options.sampler;
294
161
  this.#judge = options.judge;
295
- this.#heartbeatPath = options.heartbeatPath;
162
+ this.#inflight = options.inflight;
296
163
  this.#intervalMs = options.intervalMs;
164
+ this.#idleWindowMs = options.idleWindowMs;
165
+ this.#idleSince = options.spawnedAt;
297
166
  this.#onStall = options.onStall;
167
+ this.#clock = options.clock ?? Date.now;
298
168
  }
299
169
  /** Sample at once (the spawn instant has just passed — a round is never observed
300
- * only from the first interval on) and start the cadence. */
170
+ * only from the first interval on) and start the cadence. A first tick that
171
+ * already rules `stalled` starts no cadence: the trail is final. */
301
172
  start() {
302
- this.#tick(Date.now());
303
- this.#timer = setInterval(() => this.#tick(Date.now()), this.#intervalMs);
173
+ this.tick();
174
+ if (this.#stallFired)
175
+ return;
176
+ this.#timer = setInterval(() => this.tick(), this.#intervalMs);
304
177
  // Never hold the parent process open for the engine's own sampling.
305
178
  this.#timer.unref();
306
179
  }
@@ -309,49 +182,43 @@ class SamplingLoop {
309
182
  lastSample() {
310
183
  return this.#last;
311
184
  }
312
- /** The judge's idle reading (ms) at this instant — the termination fact's idle time. */
185
+ /** The idle time (ms) at this instant — how long since the last progress. */
313
186
  idleMs() {
314
- return this.#judge.idleMs(Date.now());
187
+ return Math.max(0, this.#clock() - this.#idleSince);
315
188
  }
316
- /** End the loop at the dispatch's terminal state: the cadence stops, and the
317
- * heartbeat is removed iff the round ended by itself — a terminated round's file
318
- * stays for a human's postmortem. */
319
- stop(endedByItself) {
189
+ /** End the loop at the dispatch's terminal state — the cadence stops and NOTHING
190
+ * else: the in-flight record is not this loop's to remove, whatever way the round
191
+ * ended (removal belongs to `InFlight.release()` / `InFlight.steal()` alone). */
192
+ stop() {
320
193
  if (this.#timer !== null) {
321
194
  clearInterval(this.#timer);
322
195
  this.#timer = null;
323
196
  }
324
- if (!endedByItself)
325
- return;
326
- try {
327
- rmSync(this.#heartbeatPath, { force: true });
328
- }
329
- catch {
330
- // Fail-open (see the class doc).
331
- }
332
197
  }
333
- /** One tick: read both legs, judge them, and overwrite the heartbeat record. A
334
- * `stalled` verdict fires the kill trigger once (the first stall owns the kill;
335
- * later ticks of a dying child never re-fire). */
336
- #tick(now) {
337
- const sample = this.#sampler.probe();
338
- const verdict = this.#judge.observe(sample, now);
339
- const record = {
340
- sampledAt: now,
341
- groupCpuMs: sample.groupCpuMs,
342
- newestMtimeMs: sample.newestMtimeMs,
343
- verdict,
344
- };
345
- this.#last = record;
346
- try {
347
- writeFileSync(this.#heartbeatPath, `${JSON.stringify(record, null, 2)}\n`, "utf8");
348
- }
349
- catch {
350
- // Fail-open (see the class doc): an unwritable heartbeat slows nothing down.
351
- }
352
- if (verdict === "stalled" && !this.#stallFired) {
198
+ /** One tick at `now` (default: the loop's clock): read the legs, judge them, and
199
+ * overwrite the in-flight record's sampling cells. A `stalled` verdict fires the
200
+ * kill trigger once and ends the cadence (the first stall owns the kill, and the
201
+ * trail's last cell stays the stall — the dying child's later unreadable ticks can
202
+ * never rewrite the postmortem). */
203
+ tick(now = this.#clock()) {
204
+ if (this.#stallFired)
205
+ return;
206
+ const { readings, previous, logSize, cpuMs } = this.#sampler.probe();
207
+ const verdict = this.#judge.verdict({
208
+ readings,
209
+ previous,
210
+ idleMs: Math.max(0, now - this.#idleSince),
211
+ windowMs: this.#idleWindowMs,
212
+ now,
213
+ });
214
+ if (verdict === "progress")
215
+ this.#idleSince = now;
216
+ this.#last = { at: now, logSize, cpuMs, verdict };
217
+ this.#inflight.heartbeat({ sampledAt: now, verdict });
218
+ if (verdict === "stalled") {
353
219
  this.#stallFired = true;
354
220
  this.#onStall?.();
221
+ this.stop();
355
222
  }
356
223
  }
357
224
  }
@@ -373,7 +240,7 @@ class SamplingLoop {
373
240
  * · `maxBuffer` is never set or lowered — execa's own 100 MB default is the
374
241
  * unbounded-face successor of the retired fixed 1 MiB cap;
375
242
  * · the sampling loop — the child is sampled from the spawn instant and every
376
- * `policy.sampleIntervalMs` after (the heartbeat file is that loop's trail, and
243
+ * `policy.sampleIntervalMs` after (the in-flight record is that loop's trail, and
377
244
  * the judge's verdict rides every record).
378
245
  * The class holds zero session state: everything a dispatch needs rides the
379
246
  * `ChildRun` argument, so the composition root wires it without a scene. */
@@ -403,6 +270,15 @@ export class Terminator {
403
270
  forceKillAfterDelay: Terminator.FORCE_KILL_AFTER_DELAY_MS,
404
271
  timeout: run.policy.budgetMs,
405
272
  });
273
+ // The round's log channel — the child's stdout/stderr bytes are appended to the
274
+ // per-round file as they arrive (zero prefix, zero engine-stdout echo, raw chunks:
275
+ // the log never re-decodes, so a chunk boundary cannot tear a character). The
276
+ // buffered result face below is unchanged; the log is an additional observation.
277
+ if (run.log !== undefined) {
278
+ const log = run.log;
279
+ subprocess.stdout?.on("data", (chunk) => log.write(chunk));
280
+ subprocess.stderr?.on("data", (chunk) => log.write(chunk));
281
+ }
406
282
  // Reclaim the group the instant the direct child exits: a grandchild holding the stdout
407
283
  // / stderr pipes would otherwise keep the `await` open. No execa option does this (its
408
284
  // group kill is on-demand only), so execa's own group-aware `kill()` is called once, at
@@ -422,9 +298,6 @@ export class Terminator {
422
298
  if (subprocess.kill())
423
299
  killedByStall = true;
424
300
  });
425
- // The round's heartbeat fate — terminated by default, so an unexpected throw keeps
426
- // the trail as well; a round that ends by itself leaves no file behind.
427
- let endedByItself = false;
428
301
  try {
429
302
  const result = await subprocess;
430
303
  const termination = Terminator.terminationOf({
@@ -435,7 +308,6 @@ export class Terminator {
435
308
  idleMs: sampling?.idleMs() ?? 0,
436
309
  lastSample: sampling?.lastSample() ?? null,
437
310
  });
438
- endedByItself = termination === null;
439
311
  return {
440
312
  // The child's OWN exit code, unfolded: null means "never spawned / signalled",
441
313
  // never a fabricated 1 (which would misreport both as an ordinary failed run).
@@ -449,29 +321,31 @@ export class Terminator {
449
321
  };
450
322
  }
451
323
  finally {
452
- // The cadence never outlives the dispatch.
453
- sampling?.stop(endedByItself);
324
+ // The cadence never outlives the dispatch (the record itself is the caller's).
325
+ sampling?.stop();
454
326
  }
455
327
  }
456
328
  /** Start the dispatch's sampling loop, or null when the child never spawned (a
457
329
  * broken command has no pid: nothing to sample and nothing to postmortem). The
458
330
  * group id is the child's OWN pid, never recomputed — `killDescendants` forces the
459
331
  * spawn-layer detachment, so the child IS its process group leader (the same fact
460
- * execa's own group kill rides); the scan root is the same `cwd` the child was
461
- * spawned in. The stall trigger rides through: the loop's first `stalled` verdict
462
- * is the kill's authorization. */
332
+ * execa's own group kill rides). The round's two context cells are taken here for
333
+ * THIS round: its own log path (a re-dispatch carries its own `-a{attempt}` file)
334
+ * and its own pgid. The stall trigger rides through: the loop's first `stalled`
335
+ * verdict is the kill's authorization. */
463
336
  #startSampling(run, pid, spawnedAt, onStall) {
464
337
  if (pid === undefined)
465
338
  return null;
339
+ // No log channel → an empty path the log leg can never read (`null`), so the CPU
340
+ // leg judges alone; the round is never lost to an unopenable observation channel.
341
+ const context = { logPath: run.log?.path ?? "", pgid: pid };
466
342
  const sampling = new SamplingLoop({
467
- sampler: new Sampler({
468
- pgid: pid,
469
- scanRoot: run.cwd,
470
- exclude: Sampler.excludesFor(run.cwd, run.heartbeatPath),
471
- }),
472
- judge: new StallJudge(run.policy.idleWindowMs, spawnedAt),
473
- heartbeatPath: run.heartbeatPath,
343
+ sampler: new Sampler(context),
344
+ judge: new LivenessJudge(),
345
+ inflight: run.inflight,
474
346
  intervalMs: run.policy.sampleIntervalMs,
347
+ idleWindowMs: run.policy.idleWindowMs,
348
+ spawnedAt,
475
349
  onStall,
476
350
  });
477
351
  sampling.start();
@@ -491,7 +365,7 @@ export class Terminator {
491
365
  * · nothing of the above → the round ended by itself (successfully or not), no
492
366
  * termination.
493
367
  * The last sample rides whichever cause won: it is the sampling loop's own last
494
- * observation, held in memory — never a re-read of the heartbeat file the engine
368
+ * observation, held in memory — never a re-read of the record file the engine
495
369
  * itself wrote.
496
370
  *
497
371
  * `killedByStall` records that OUR kill was delivered (execa's `kill()` returns