@oscaner-skills/cdd-engine 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +2 -2
  2. package/README.zh-CN.md +2 -2
  3. package/package.json +4 -3
  4. package/src-next/__tests__/dead-decl.guard.test.ts +39 -0
  5. package/src-next/__tests__/floor.guard.test.ts +69 -0
  6. package/src-next/__tests__/issue-body.guard.test.ts +66 -0
  7. package/src-next/__tests__/phase-suffix.guard.test.ts +72 -0
  8. package/src-next/__tests__/smoke.integration.test.ts +60 -77
  9. package/src-next/__tests__/support/strip-comments.ts +99 -0
  10. package/src-next/__tests__/zero-dep.test.ts +6 -46
  11. package/src-next/contract/__tests__/__snapshots__/project.schema.overall-spec.snap +39 -21
  12. package/src-next/contract/__tests__/__snapshots__/project.schema.phase-spec.snap +40 -28
  13. package/src-next/contract/__tests__/__snapshots__/project.schema.plan.snap +40 -23
  14. package/src-next/contract/__tests__/__snapshots__/project.schema.single-spec.snap +38 -21
  15. package/src-next/contract/__tests__/__snapshots__/project.shape.overall-spec.snap +21 -6
  16. package/src-next/contract/__tests__/__snapshots__/project.shape.phase-spec.snap +22 -12
  17. package/src-next/contract/__tests__/__snapshots__/project.shape.plan.snap +23 -8
  18. package/src-next/contract/__tests__/__snapshots__/project.shape.single-spec.snap +21 -6
  19. package/src-next/contract/__tests__/declare.test.ts +251 -12
  20. package/src-next/contract/__tests__/doc.test.ts +214 -45
  21. package/src-next/contract/__tests__/dockey.guard.test.ts +58 -0
  22. package/src-next/contract/__tests__/edge-conditions.guard.test.ts +81 -0
  23. package/src-next/contract/__tests__/frontmatter.test.ts +164 -0
  24. package/src-next/contract/__tests__/judge.test.ts +410 -172
  25. package/src-next/contract/__tests__/lint.test.ts +49 -39
  26. package/src-next/contract/__tests__/project.test.ts +60 -19
  27. package/src-next/contract/__tests__/structure-pin.test.ts +186 -0
  28. package/src-next/contract/declare.ts +179 -91
  29. package/src-next/contract/doc.ts +227 -164
  30. package/src-next/contract/frontmatter.ts +233 -0
  31. package/src-next/contract/home-extractors.ts +397 -0
  32. package/src-next/contract/invariants.ts +214 -69
  33. package/src-next/contract/judge.ts +28 -19
  34. package/src-next/contract/lint.ts +5 -41
  35. package/src-next/contract/project.ts +103 -43
  36. package/src-next/contract/skill-anatomy.ts +39 -11
  37. package/src-next/face/__tests__/board-view.test.ts +318 -115
  38. package/src-next/face/__tests__/capsule.test.ts +49 -25
  39. package/src-next/face/__tests__/channel-closure.guard.test.ts +28 -1
  40. package/src-next/face/__tests__/cli.test.ts +1091 -837
  41. package/src-next/face/__tests__/face.test.ts +5 -5
  42. package/src-next/face/__tests__/install-rows.guard.test.ts +58 -0
  43. package/src-next/face/__tests__/preview.test.ts +374 -0
  44. package/src-next/face/__tests__/projection.test.ts +5 -3
  45. package/src-next/face/__tests__/repo-root.guard.test.ts +120 -0
  46. package/src-next/face/__tests__/termination.test.ts +650 -0
  47. package/src-next/face/artifacts.ts +90 -37
  48. package/src-next/face/board-view.ts +128 -138
  49. package/src-next/face/capsule.ts +30 -16
  50. package/src-next/face/cli.ts +306 -97
  51. package/src-next/face/declare.ts +15 -18
  52. package/src-next/face/gate.ts +19 -18
  53. package/src-next/face/host.ts +6 -30
  54. package/src-next/face/lifecycle.ts +213 -188
  55. package/src-next/face/preview.ts +151 -0
  56. package/src-next/face/projection.ts +4 -1
  57. package/src-next/face/route-render.ts +39 -14
  58. package/src-next/face/termination.ts +573 -0
  59. package/src-next/face/words.ts +20 -2
  60. package/src-next/infra/__tests__/infra.test.ts +49 -3
  61. package/src-next/infra/__tests__/root.test.ts +56 -0
  62. package/src-next/infra/doc-roots.ts +29 -0
  63. package/src-next/infra/root.ts +73 -0
  64. package/src-next/infra/runtime.ts +12 -65
  65. package/src-next/infra/workspace.ts +95 -5
  66. package/src-next/render/__tests__/render.test.ts +92 -41
  67. package/src-next/render/__tests__/skeleton.test.ts +282 -64
  68. package/src-next/render/issue-body.ts +5 -2
  69. package/src-next/render/skeleton.ts +155 -90
  70. package/src-next/render/templates.ts +51 -56
  71. package/src-next/session/__tests__/graph.test.ts +11 -4
  72. package/src-next/session/__tests__/ledger.test.ts +3 -2
  73. package/src-next/session/__tests__/next.test.ts +100 -8
  74. package/src-next/session/__tests__/preflight.test.ts +79 -25
  75. package/src-next/session/__tests__/round-naming.test.ts +142 -0
  76. package/src-next/session/__tests__/run.test.ts +140 -128
  77. package/src-next/session/__tests__/wave.test.ts +11 -4
  78. package/src-next/session/ledger.ts +96 -24
  79. package/src-next/session/next.ts +116 -15
  80. package/src-next/session/preflight.ts +41 -10
  81. package/src-next/session/round-naming.ts +84 -0
  82. package/src-next/session/run.ts +24 -20
  83. package/templates/report/issue-body.json +0 -46
  84. package/src-next/face/__tests__/sync-runner.test.ts +0 -70
@@ -0,0 +1,573 @@
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
+
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
+ import type {
25
+ RoundPhase,
26
+ Sample,
27
+ SampleRecord,
28
+ StallVerdict,
29
+ TerminationCause,
30
+ } from "../session/ledger.ts";
31
+
32
+ // ---------------------------------------------------------------------------
33
+ // the seam — one dispatch's input, result and runner
34
+ // ---------------------------------------------------------------------------
35
+
36
+ /** How a round ended when it did not end by itself — the derived cause plus the
37
+ * last observed sample (the postmortem pair the crash record carries; the sample
38
+ * rides the outcome in memory, never re-read from the heartbeat file). `unknown`
39
+ * is the unattributable fallback of the derivation. */
40
+ export interface Termination {
41
+ cause: TerminationCause | "unknown";
42
+ lastSample: SampleRecord | null;
43
+ }
44
+
45
+ /** The facts the termination derivation rules on — the execa result face plus the
46
+ * engine's own stall-kill flag and the sampling loop's last observation. Named
47
+ * fields, because the three adjacent booleans/strings would swap silently as
48
+ * positional parameters. */
49
+ export interface TerminationFacts {
50
+ timedOut: boolean;
51
+ killedByStall: boolean;
52
+ signal: string | undefined;
53
+ isTerminated: boolean;
54
+ lastSample: SampleRecord | null;
55
+ }
56
+
57
+ /** One dispatch's result over the child-runner seam — the child's own exit code
58
+ * (null when it never spawned or was signalled) and its verbatim streams, plus the
59
+ * termination fact. `termination !== null` ⟺ the round was cut short (the wall-clock
60
+ * ceiling, the engine's own kill, or a signal on the child) — a spawn failure has
61
+ * neither an exit code nor a termination, so it rides the ordinary child-exit face. */
62
+ export interface ChildOutcome {
63
+ code: number | null;
64
+ stdout: string;
65
+ stderr: string;
66
+ termination: Termination | null;
67
+ }
68
+
69
+ /** One dispatch's full context — everything the runner needs, and nothing that
70
+ * reaches back into the session: the spawned command, the heartbeat path the
71
+ * sampler writes for this dispatch, and the phase's termination policy. The
72
+ * caller derives `cwd` and `heartbeatPath` from the one workspace it holds, so
73
+ * both paths share one source; the same `cwd` is the spawn directory AND the
74
+ * scanned tree root (the "scan root ≡ the child's cwd" structural guarantee). */
75
+ export interface ChildRun {
76
+ command: string;
77
+ args: readonly string[];
78
+ cwd: string;
79
+ heartbeatPath: string;
80
+ policy: TerminationPolicy;
81
+ }
82
+
83
+ /** The child-runner seam — the production terminator and the test stub implement
84
+ * this one shape; the lifecycle sees only the interface. A failed child rides the
85
+ * result, never a throw (fail-open). */
86
+ export interface ChildRunner {
87
+ run(run: ChildRun): Promise<ChildOutcome>;
88
+ }
89
+
90
+ // ---------------------------------------------------------------------------
91
+ // the constant single source — budget and timing, per dispatch phase
92
+ // ---------------------------------------------------------------------------
93
+
94
+ /** TerminationPolicy — the budget/timing constant single source (code constants
95
+ * only: zero environment variables, zero config plane). The budget key set IS the
96
+ * dispatch-phase set, so no phase falls through to another phase's ceiling. The
97
+ * timing pair is injectable (the production values are the constants below; tests
98
+ * inject tiny ones, so an end-to-end stall case need not wait out the real window). */
99
+ export class TerminationPolicy {
100
+ /** The per-phase wall-clock ceiling (ms) — the implement round is the long one. */
101
+ static readonly BUDGET_MS: Readonly<Record<RoundPhase, number>> = {
102
+ implement: 6 * 60 * 60 * 1000,
103
+ review: 3 * 60 * 60 * 1000,
104
+ fix: 3 * 60 * 60 * 1000,
105
+ "branch-review": 3 * 60 * 60 * 1000,
106
+ };
107
+ /** The stall window (ms) — how long a round may make no progress before the
108
+ * judge rules it stalled (not per phase: "no progress" means the same thing on
109
+ * every phase). */
110
+ static readonly IDLE_WINDOW_MS = 30 * 60 * 1000;
111
+ /** The sampling cadence (ms) — one sample tick per interval. */
112
+ static readonly SAMPLE_INTERVAL_MS = 60 * 1000;
113
+
114
+ /** The round's wall-clock ceiling (ms) — the execa `timeout` value. */
115
+ readonly budgetMs: number;
116
+ /** The stall window the judge rules on (ms). */
117
+ readonly idleWindowMs: number;
118
+ /** The sampler's tick interval (ms). */
119
+ readonly sampleIntervalMs: number;
120
+
121
+ constructor(
122
+ budgetMs: number,
123
+ idleWindowMs: number = TerminationPolicy.IDLE_WINDOW_MS,
124
+ sampleIntervalMs: number = TerminationPolicy.SAMPLE_INTERVAL_MS,
125
+ ) {
126
+ this.budgetMs = budgetMs;
127
+ this.idleWindowMs = idleWindowMs;
128
+ this.sampleIntervalMs = sampleIntervalMs;
129
+ }
130
+
131
+ /** The production policy of one dispatch phase — its own budget key plus the
132
+ * shared timing constants. */
133
+ static of(phase: RoundPhase): TerminationPolicy {
134
+ return new TerminationPolicy(TerminationPolicy.BUDGET_MS[phase]);
135
+ }
136
+ }
137
+
138
+ // ---------------------------------------------------------------------------
139
+ // the stall judge — the running judgment over one dispatch, pure logic
140
+ // ---------------------------------------------------------------------------
141
+
142
+ /** StallJudge — is this dispatch still moving? Not a comparison of two samples but a
143
+ * judgment over the round: the judge holds its own accumulating state and is fed one
144
+ * tick at a time through `observe`, which returns the tick's verdict. Zero I/O: it
145
+ * reads the two legs of a `Sample` and nothing else (the OS reads live in `Sampler`),
146
+ * so its truth table is testable without a process or a tree. Both the idle window
147
+ * and the spawn instant are injected — the window never comes from a module constant
148
+ * and the clock never comes from the wall (a stall case must not wait out the real
149
+ * half hour), and the spawn instant seeds the idle clock.
150
+ *
151
+ * The rules, in the order they are applied:
152
+ * · an unreadable leg (`null`) → `unknown`, and unknown never kills (fail-open: no
153
+ * reading of a leg means no evidence of a stall, and an unreadable tick carries no
154
+ * observation either way);
155
+ * · CPU above the PREVIOUS observation, or mtime above the HISTORICAL MAXIMUM →
156
+ * `progress`, and the idle clock restarts at this tick;
157
+ * · no progress and the window is still open → `idled`;
158
+ * · no progress and the window is spent → `stalled` (the kill).
159
+ * Neither leg authorizes a kill alone (`unknown` covers the unreadable case) and
160
+ * output activity is deliberately NOT a signal: a thinking child is silent, and using
161
+ * silence against it would kill a child that is working. */
162
+ export class StallJudge {
163
+ readonly #idleWindowMs: number;
164
+ /** The instant of the last progress — the spawn instant until the first one. */
165
+ #idleSince: number;
166
+ /** The previous tick's process-group CPU (ms) — `null` until the first readable one. */
167
+ #lastCpuMs: number | null = null;
168
+ /** The largest mtime (ms) the tree leg has ever reported. */
169
+ #maxMtimeMs: number | null = null;
170
+
171
+ constructor(idleWindowMs: number, spawnedAt: number) {
172
+ this.#idleWindowMs = idleWindowMs;
173
+ this.#idleSince = spawnedAt;
174
+ }
175
+
176
+ /** Judge one tick: feed the tick's sample and the instant it was taken. */
177
+ observe(sample: Sample, now: number): StallVerdict {
178
+ const cpuMs = sample.groupCpuMs;
179
+ const mtimeMs = sample.newestMtimeMs;
180
+ // Both legs must be readable to judge at all.
181
+ if (cpuMs === null || mtimeMs === null) return "unknown";
182
+ // Progress is an advance over what has already been seen — this CPU over the
183
+ // previous observation, this mtime over the historical maximum. The first readable
184
+ // tick has neither, so it can never be a progress tick: the idle clock has been
185
+ // running since the spawn instant, exactly as if that tick had been flat.
186
+ const advanced =
187
+ (this.#lastCpuMs !== null && cpuMs > this.#lastCpuMs) ||
188
+ (this.#maxMtimeMs !== null && mtimeMs > this.#maxMtimeMs);
189
+ this.#lastCpuMs = cpuMs;
190
+ if (this.#maxMtimeMs === null || mtimeMs > this.#maxMtimeMs) this.#maxMtimeMs = mtimeMs;
191
+ if (advanced) {
192
+ this.#idleSince = now;
193
+ return "progress";
194
+ }
195
+ return now - this.#idleSince < this.#idleWindowMs ? "idled" : "stalled";
196
+ }
197
+ }
198
+
199
+ // ---------------------------------------------------------------------------
200
+ // the sampler — the two legs' heavy lifting (the only OS I/O of the stall face)
201
+ // ---------------------------------------------------------------------------
202
+
203
+ /** Sampler — one dispatch's two legs, read once per tick: the process group's
204
+ * cumulative CPU and the newest content mtime of the scanned tree. The I/O lives
205
+ * here and the judgment lives in `StallJudge`, so each face is testable on its own
206
+ * (the truth table without a process, the fail-open `null` without a judge).
207
+ *
208
+ * · The group id is the child's own pid, never recomputed: `killDescendants` forces
209
+ * the spawn-layer detachment, so the child IS its process group leader — the same
210
+ * fact execa's own `process.kill(-pid)` kill rides.
211
+ * · The scan root is the child's cwd (the repo root), so the "scan root ≡ child cwd"
212
+ * correspondence is structural.
213
+ * · `exclude` is the engine's own writes — `Sampler.excludesFor` is its single
214
+ * source: the repo's `.git/` and the dispatch's heartbeat file. The rest of
215
+ * `.kairos/` is NOT excluded: a child's handoff draft there is real progress. */
216
+ export class Sampler {
217
+ /** The deepest tree level the walk descends to. */
218
+ static readonly MAX_DEPTH = 32;
219
+ /** The VCS internal every scan skips — its mtime is never a round's progress. */
220
+ static readonly VCS_DIR = ".git";
221
+ /** A `ps -o time=` reading: `[DD-][HH:]MM:SS[.ff]` (BSD gives centiseconds, Linux
222
+ * whole seconds — both ride the same pattern). */
223
+ static readonly TIME_PATTERN =
224
+ /^(?:(\d+)-)?(?:(\d+):(\d+):(\d+(?:\.\d+)?)|(\d+):(\d+(?:\.\d+)?))$/;
225
+
226
+ readonly #pgid: number;
227
+ readonly #scanRoot: string;
228
+ readonly #exclude: ReadonlySet<string>;
229
+
230
+ constructor(options: { pgid: number; scanRoot: string; exclude: readonly string[] }) {
231
+ this.#pgid = options.pgid;
232
+ // Absolute, normalized forms on both sides of the comparison below, so an
233
+ // exclusion matches the walked path it names.
234
+ this.#scanRoot = path.resolve(options.scanRoot);
235
+ this.#exclude = new Set(options.exclude.map((entry) => path.resolve(entry)));
236
+ }
237
+
238
+ /** The exclusion single source for one dispatch: the repo's VCS internal plus the
239
+ * heartbeat path the engine itself writes (a tick must never self-certify). */
240
+ static excludesFor(scanRoot: string, heartbeatPath: string): readonly string[] {
241
+ return [path.join(scanRoot, Sampler.VCS_DIR), heartbeatPath];
242
+ }
243
+
244
+ /** Read both legs of this tick — each independently fail-open: a leg the platform
245
+ * cannot read is `null`, never a fabricated reading. */
246
+ probe(): Sample {
247
+ return { groupCpuMs: this.#groupCpuMs(), newestMtimeMs: this.#newestMtimeMs() };
248
+ }
249
+
250
+ /** The process group's cumulative CPU (ms), summed over the group's processes. A
251
+ * non-zero `ps` exit (no such group, or no `ps` at all) or any unparseable line
252
+ * makes the leg unreadable — `null`. An empty reading is unreadable too: a group
253
+ * with no observable member is not evidence of zero CPU. */
254
+ #groupCpuMs(): number | null {
255
+ let output: string;
256
+ try {
257
+ output = execFileSync("ps", ["-o", "time=", "-g", String(this.#pgid)], {
258
+ encoding: "utf8",
259
+ // stdout only: `ps`'s own complaint about an unknown group is not a reading,
260
+ // and it must never reach the engine's stderr channel.
261
+ stdio: ["ignore", "pipe", "ignore"],
262
+ });
263
+ } catch {
264
+ return null;
265
+ }
266
+ const lines = output
267
+ .split("\n")
268
+ .map((line) => line.trim())
269
+ .filter((line) => line.length > 0);
270
+ if (lines.length === 0) return null;
271
+ let total = 0;
272
+ for (const line of lines) {
273
+ const ms = Sampler.#parseCpuTime(line);
274
+ if (ms === null) return null;
275
+ total += ms;
276
+ }
277
+ return total;
278
+ }
279
+
280
+ /** One `time=` reading as milliseconds — `null` when the text is not that format. */
281
+ static #parseCpuTime(text: string): number | null {
282
+ const match = Sampler.TIME_PATTERN.exec(text);
283
+ if (match === null) return null;
284
+ const days = Number(match[1] ?? 0);
285
+ const hours = Number(match[2] ?? 0);
286
+ const minutes = Number(match[3] ?? match[5] ?? 0);
287
+ const seconds = Number(match[4] ?? match[6] ?? 0);
288
+ return (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
289
+ }
290
+
291
+ /** The newest content mtime (ms) in the scanned tree — `null` when the walk cannot
292
+ * complete (an unreadable directory anywhere makes the whole leg unreadable rather
293
+ * than under-reporting). */
294
+ #newestMtimeMs(): number | null {
295
+ try {
296
+ return this.#newestIn(this.#scanRoot, 0);
297
+ } catch {
298
+ return null;
299
+ }
300
+ }
301
+
302
+ /** The recursive descent — symlinks and the engine's own paths skipped, `MAX_DEPTH`
303
+ * as the floor of the walk. */
304
+ #newestIn(dir: string, depth: number): number | null {
305
+ if (depth > Sampler.MAX_DEPTH) return null;
306
+ let newest: number | null = null;
307
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
308
+ const child = path.join(dir, entry.name);
309
+ // A symlink is never followed (it can leave the tree outright); an excluded path
310
+ // is the engine's own write.
311
+ if (entry.isSymbolicLink() || this.#exclude.has(child)) continue;
312
+ if (entry.isDirectory()) {
313
+ const nested = this.#newestIn(child, depth + 1);
314
+ if (nested !== null && (newest === null || nested > newest)) newest = nested;
315
+ continue;
316
+ }
317
+ // Content mtimes only: a directory's own mtime moves on entry churn, which the
318
+ // CPU leg already reflects as work — and the heartbeat's first creation would
319
+ // otherwise bump its directory and self-certify a progress tick.
320
+ const mtimeMs = statSync(child).mtimeMs;
321
+ if (newest === null || mtimeMs > newest) newest = mtimeMs;
322
+ }
323
+ return newest;
324
+ }
325
+ }
326
+
327
+ // ---------------------------------------------------------------------------
328
+ // the sampling loop — the dispatch's heartbeat trail (§3.4)
329
+ // ---------------------------------------------------------------------------
330
+
331
+ /** The sampling loop of one dispatch — the cadence that wraps the running child: one
332
+ * sample the moment the child is spawned, then one per `intervalMs`. Each tick reads
333
+ * the two legs through the `Sampler`, has the `StallJudge` rule on them, and
334
+ * overwrites the dispatch's heartbeat file with the resulting `SampleRecord` — the
335
+ * trail a human reads after a round was cut short. A `stalled` verdict fires the
336
+ * loop's `onStall` callback once — the Terminator's kill trigger (the engine's own
337
+ * group kill; the SIGTERM → SIGKILL escalation is execa's).
338
+ *
339
+ * The interval is unref'd: the engine's own sampling must never be the reason the
340
+ * parent process stays alive (the dispatch awaits the child, not the cadence). The
341
+ * heartbeat write is a plain overwrite, deliberately NOT a write-then-rename: a
342
+ * temporary file would sit inside the scanned tree and its own creation would certify
343
+ * "progress" — the very self-report the exclusion exists to prevent. Both the write
344
+ * and the removal are fail-open: the trail is a diagnostic, never a dispatch's fate.
345
+ *
346
+ * The last observation is held in memory (`lastSample`): a terminated round's crash
347
+ * record takes it from there, never by re-reading the file the engine itself wrote. */
348
+ class SamplingLoop {
349
+ readonly #sampler: Sampler;
350
+ readonly #judge: StallJudge;
351
+ readonly #heartbeatPath: string;
352
+ readonly #intervalMs: number;
353
+ /** The stall trigger — called once on the first `stalled` verdict (the kill). */
354
+ readonly #onStall?: () => void;
355
+ /** Whether the stall verdict has already fired — one kill per dispatch. */
356
+ #stallFired = false;
357
+ /** The most recent observation — the postmortem sample of a terminated round. */
358
+ #last: SampleRecord | null = null;
359
+ #timer: ReturnType<typeof setInterval> | null = null;
360
+
361
+ constructor(options: {
362
+ sampler: Sampler;
363
+ judge: StallJudge;
364
+ heartbeatPath: string;
365
+ intervalMs: number;
366
+ onStall?: () => void;
367
+ }) {
368
+ this.#sampler = options.sampler;
369
+ this.#judge = options.judge;
370
+ this.#heartbeatPath = options.heartbeatPath;
371
+ this.#intervalMs = options.intervalMs;
372
+ this.#onStall = options.onStall;
373
+ }
374
+
375
+ /** Sample at once (the spawn instant has just passed — a round is never observed
376
+ * only from the first interval on) and start the cadence. */
377
+ start(): void {
378
+ this.#tick(Date.now());
379
+ this.#timer = setInterval(() => this.#tick(Date.now()), this.#intervalMs);
380
+ // Never hold the parent process open for the engine's own sampling.
381
+ this.#timer.unref();
382
+ }
383
+
384
+ /** The loop's last observation (null when no tick was ever taken) — the sample a
385
+ * terminated round's crash record carries, from memory. */
386
+ lastSample(): SampleRecord | null {
387
+ return this.#last;
388
+ }
389
+
390
+ /** End the loop at the dispatch's terminal state: the cadence stops, and the
391
+ * heartbeat is removed iff the round ended by itself — a terminated round's file
392
+ * stays for a human's postmortem. */
393
+ stop(endedByItself: boolean): void {
394
+ if (this.#timer !== null) {
395
+ clearInterval(this.#timer);
396
+ this.#timer = null;
397
+ }
398
+ if (!endedByItself) return;
399
+ try {
400
+ rmSync(this.#heartbeatPath, { force: true });
401
+ } catch {
402
+ // Fail-open (see the class doc).
403
+ }
404
+ }
405
+
406
+ /** One tick: read both legs, judge them, and overwrite the heartbeat record. A
407
+ * `stalled` verdict fires the kill trigger once (the first stall owns the kill;
408
+ * later ticks of a dying child never re-fire). */
409
+ #tick(now: number): void {
410
+ const sample = this.#sampler.probe();
411
+ const verdict = this.#judge.observe(sample, now);
412
+ const record: SampleRecord = {
413
+ sampledAt: now,
414
+ groupCpuMs: sample.groupCpuMs,
415
+ newestMtimeMs: sample.newestMtimeMs,
416
+ verdict,
417
+ };
418
+ this.#last = record;
419
+ try {
420
+ writeFileSync(this.#heartbeatPath, `${JSON.stringify(record, null, 2)}\n`, "utf8");
421
+ } catch {
422
+ // Fail-open (see the class doc): an unwritable heartbeat slows nothing down.
423
+ }
424
+ if (verdict === "stalled" && !this.#stallFired) {
425
+ this.#stallFired = true;
426
+ this.#onStall?.();
427
+ }
428
+ }
429
+ }
430
+
431
+ // ---------------------------------------------------------------------------
432
+ // the production runner — execa's asynchronous face
433
+ // ---------------------------------------------------------------------------
434
+
435
+ /** Terminator — the production `ChildRunner`: one child, its whole process
436
+ * lifecycle. Every process capability the seam needs is execa's, never the
437
+ * engine's:
438
+ * · `killDescendants: true` — the child is spawned as its own process group and
439
+ * the group is killed as a unit (execa forces the spawn-layer detachment
440
+ * internally; the user-facing `detached` option is never set, because it would
441
+ * short-circuit execa's parent-exit `cleanup`);
442
+ * · `forceKillAfterDelay` — SIGTERM, then SIGKILL after the grace (execa's own
443
+ * default written out, so the escalation is pinned at the call site);
444
+ * · `timeout` — the phase's wall-clock ceiling on the same kill path;
445
+ * · `reject: false` + `stripFinalNewline: false` — the fail-open result face, the
446
+ * child's stdout kept byte-verbatim;
447
+ * · `maxBuffer` is never set or lowered — execa's own 100 MB default is the
448
+ * unbounded-face successor of the retired fixed 1 MiB cap;
449
+ * · the sampling loop — the child is sampled from the spawn instant and every
450
+ * `policy.sampleIntervalMs` after (the heartbeat file is that loop's trail, and
451
+ * the judge's verdict rides every record).
452
+ * The class holds zero session state: everything a dispatch needs rides the
453
+ * `ChildRun` argument, so the composition root wires it without a scene. */
454
+ export class Terminator implements ChildRunner {
455
+ /** The force-kill grace (ms) — SIGTERM, then SIGKILL after this delay (execa's
456
+ * default, pinned explicitly). */
457
+ static readonly FORCE_KILL_AFTER_DELAY_MS = 5000;
458
+
459
+ async run(run: ChildRun): Promise<ChildOutcome> {
460
+ // The spawn instant seeds the judge's idle clock (§3.3).
461
+ const spawnedAt = Date.now();
462
+ // The engine's own stall kill — set by the sampling loop's trigger when the
463
+ // judge rules `stalled` AND the kill is delivered; the derivation reads it to
464
+ // attribute the kill (the signal execa reports for OUR kill would otherwise
465
+ // read as an external one).
466
+ let killedByStall = false;
467
+ const subprocess = execa(run.command, [...run.args], {
468
+ cwd: run.cwd,
469
+ reject: false,
470
+ stripFinalNewline: false,
471
+ killDescendants: true,
472
+ forceKillAfterDelay: Terminator.FORCE_KILL_AFTER_DELAY_MS,
473
+ timeout: run.policy.budgetMs,
474
+ });
475
+ const sampling = this.#startSampling(run, subprocess.pid, spawnedAt, () => {
476
+ // The engine's own group kill — execa kills the process group and escalates
477
+ // SIGTERM → SIGKILL after the grace. No signal logic of the engine's own.
478
+ // The flag records DELIVERY, not intent: `kill()` returns false when the signal
479
+ // could not be sent (the child already exited), so a round that ended by itself
480
+ // in the same tick is not misattributed as `stalled`.
481
+ if (subprocess.kill()) killedByStall = true;
482
+ });
483
+ // The round's heartbeat fate — terminated by default, so an unexpected throw keeps
484
+ // the trail as well; a round that ends by itself leaves no file behind.
485
+ let endedByItself = false;
486
+ try {
487
+ const result = await subprocess;
488
+ const termination = Terminator.terminationOf({
489
+ timedOut: result.timedOut,
490
+ killedByStall,
491
+ signal: result.signal,
492
+ isTerminated: result.isTerminated,
493
+ lastSample: sampling?.lastSample() ?? null,
494
+ });
495
+ endedByItself = termination === null;
496
+ return {
497
+ // The child's OWN exit code, unfolded: null means "never spawned / signalled",
498
+ // never a fabricated 1 (which would misreport both as an ordinary failed run).
499
+ code: result.exitCode ?? null,
500
+ stdout: result.stdout,
501
+ // The child's own stderr when it wrote one, else execa's diagnostic (a spawn
502
+ // failure like ENOENT writes nothing, so its reason rides the `shortMessage` —
503
+ // the fail-open face keeps a reason text, never an empty block).
504
+ stderr: result.stderr || (result.failed ? (result.shortMessage ?? "") : ""),
505
+ termination,
506
+ };
507
+ } finally {
508
+ // The cadence never outlives the dispatch.
509
+ sampling?.stop(endedByItself);
510
+ }
511
+ }
512
+
513
+ /** Start the dispatch's sampling loop, or null when the child never spawned (a
514
+ * broken command has no pid: nothing to sample and nothing to postmortem). The
515
+ * group id is the child's OWN pid, never recomputed — `killDescendants` forces the
516
+ * spawn-layer detachment, so the child IS its process group leader (the same fact
517
+ * execa's own group kill rides); the scan root is the same `cwd` the child was
518
+ * spawned in. The stall trigger rides through: the loop's first `stalled` verdict
519
+ * is the kill's authorization. */
520
+ #startSampling(
521
+ run: ChildRun,
522
+ pid: number | undefined,
523
+ spawnedAt: number,
524
+ onStall?: () => void,
525
+ ): SamplingLoop | null {
526
+ if (pid === undefined) return null;
527
+ const sampling = new SamplingLoop({
528
+ sampler: new Sampler({
529
+ pgid: pid,
530
+ scanRoot: run.cwd,
531
+ exclude: Sampler.excludesFor(run.cwd, run.heartbeatPath),
532
+ }),
533
+ judge: new StallJudge(run.policy.idleWindowMs, spawnedAt),
534
+ heartbeatPath: run.heartbeatPath,
535
+ intervalMs: run.policy.sampleIntervalMs,
536
+ onStall,
537
+ });
538
+ sampling.start();
539
+ return sampling;
540
+ }
541
+
542
+ /** Derive the termination fact from the child's own result face — the four-way
543
+ * derivation (§4.1), in the order the causes claim a kill (package-visible, so the
544
+ * table-driven pin can rule on every branch without a real child):
545
+ * · the wall-clock ceiling (execa's `timedOut`) → `over-budget`;
546
+ * · the engine's own stall kill → `stalled` (ahead of the signal leg: OUR kill
547
+ * also arrives as a signal, and misreading it as external would falsify the
548
+ * postmortem);
549
+ * · any other signal → `signal` (the external-kill semantic, never the SIGTERM
550
+ * literal — SIGTERM / SIGKILL / SIGINT / SIGHUP read the same);
551
+ * · none of the three but the child was terminated anyway → `unknown` (the
552
+ * unattributable fallback);
553
+ * · nothing of the above → the round ended by itself (successfully or not), no
554
+ * termination.
555
+ * The last sample rides whichever cause won: it is the sampling loop's own last
556
+ * observation, held in memory — never a re-read of the heartbeat file the engine
557
+ * itself wrote.
558
+ *
559
+ * `killedByStall` records that OUR kill was delivered (execa's `kill()` returns
560
+ * false when the signal could not be sent — a child that already exited is not
561
+ * attributed here). Residual boundary: a child that exits within the same tick
562
+ * while its process group still exists (a zombie not yet reaped) can still be
563
+ * signalled and read `stalled` — the idle verdict, not the kill landing, is the
564
+ * criterion. */
565
+ static terminationOf(facts: TerminationFacts): Termination | null {
566
+ const { timedOut, killedByStall, signal, isTerminated, lastSample } = facts;
567
+ if (timedOut) return { cause: "over-budget", lastSample };
568
+ if (killedByStall) return { cause: "stalled", lastSample };
569
+ if (signal !== undefined) return { cause: "signal", lastSample };
570
+ if (isTerminated) return { cause: "unknown", lastSample };
571
+ return null;
572
+ }
573
+ }
@@ -48,7 +48,13 @@ export type StationKind = "next" | "blocked" | "warn" | "cliMissing";
48
48
  * v1.25: `implement` — the dispatch-ready `next:` literal's verb for a ready wave;
49
49
  * `docType` — the missing-declaration BLOCK wording the capsule's unified next face
50
50
  * renders over the CDD_BLOCKED station, spec §12 · D34). */
51
- export type RouteWordKind = "done" | "review" | "fix" | "implement" | "docType";
51
+ export type RouteWordKind =
52
+ | "done"
53
+ | "review"
54
+ | "fix"
55
+ | "implement"
56
+ | "docType"
57
+ | "frontmatterParse";
52
58
 
53
59
  /** The wave-gate BLOCK wording rows — the vocabulary the WaveGate verdicts render
54
60
  * (the v1.21 word-table pin: the gate's prompt wording rides the word table, never a CLI literal).
@@ -98,7 +104,9 @@ export const CAPSULE_WORDS = {
98
104
  fix: "fix",
99
105
  implement: "implement",
100
106
  docType:
101
- "the doc declares no `- **Doc type**:` line — add `- **Doc type**: <overall-spec|phase-spec|single-spec|plan>` to the doc's header (spec §12) and re-run",
107
+ "the doc declares no `doc-type:` key — add `doc-type: <overall-spec|phase-spec|single-spec|plan>` to the doc's front-matter (spec §12 · D34) and re-run",
108
+ frontmatterParse:
109
+ "the doc's front-matter is not valid YAML: {reason} on line {line}, column {column} (`{source}`) — quote values that start with `[` or `{` (a YAML flow-sequence start) and re-run",
102
110
  } as const,
103
111
  /** The wave-gate BLOCK wording rows (v1.21) — the highest-arity pre-flight refusal
104
112
  * vocabulary, single-sourced (the gate fills the placeholders, never a re-type). */
@@ -193,6 +201,16 @@ export const ISSUE_LABEL_WORDS = {
193
201
  "chore.suggestedFix": { en: "## Suggested direction", zh: "## 建议方向" },
194
202
  } as const satisfies Readonly<Record<LocaleWordId, LocalizedWord>>;
195
203
 
204
+ /** The finding-type vocabulary — the canonical issue-report type set, DERIVED from the
205
+ * issue-label rows' `${type}.${segment}` key prefixes (deduped in row order). This is
206
+ * the ONE source of the accepted finding types: the issue renderer's validation set
207
+ * reads it, and the consumer `cdd-report` SKILL.md's declared `type ∈ {…}` domain is
208
+ * pinned to it by the kairos-suite consistency gate (spec §3.3 ⑥ — never a second
209
+ * hand-written list). */
210
+ export const ISSUE_TYPES: readonly string[] = [
211
+ ...new Set(Object.keys(ISSUE_LABEL_WORDS).map((id) => id.split(".")[0]!)),
212
+ ];
213
+
196
214
  /** The charter anchor rows — the P7 canonicalize data plane: one row per legacy
197
215
  * Chinese charter marker the structure judge matches through the canonicalize view
198
216
  * (the doc-arch overall 决策组叶 / 上游先例背书). The family prefix `charter.` sits