@oscaner-skills/cdd-engine 4.2.0 → 4.4.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 (58) hide show
  1. package/README.md +38 -9
  2. package/README.zh-CN.md +44 -10
  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 +382 -172
  25. package/dist/face/capsule.js +73 -88
  26. package/dist/face/cli.js +152 -38
  27. package/dist/face/declare.js +42 -19
  28. package/dist/face/gate.js +119 -40
  29. package/dist/face/init.js +84 -25
  30. package/dist/face/lifecycle.js +540 -123
  31. package/dist/face/plugins.js +70 -2
  32. package/dist/face/preview.js +69 -18
  33. package/dist/face/route-render.js +60 -21
  34. package/dist/face/termination.js +135 -261
  35. package/dist/face/words.js +139 -13
  36. package/dist/infra/atomic.js +15 -0
  37. package/dist/infra/git.js +25 -0
  38. package/dist/infra/proc.js +150 -0
  39. package/dist/infra/round-log.js +104 -0
  40. package/dist/infra/runtime.js +16 -4
  41. package/dist/infra/workspace.js +7 -2
  42. package/dist/render/brief.js +15 -17
  43. package/dist/render/skeleton.js +41 -28
  44. package/dist/render/templates.js +128 -84
  45. package/dist/session/faces.js +47 -20
  46. package/dist/session/graph.js +13 -37
  47. package/dist/session/handoff-schema.js +16 -8
  48. package/dist/session/inflight.js +282 -0
  49. package/dist/session/ledger.js +603 -145
  50. package/dist/session/line-identity.js +33 -0
  51. package/dist/session/next.js +140 -80
  52. package/dist/session/pipeline.js +247 -0
  53. package/dist/session/preflight.js +276 -68
  54. package/dist/session/reviewed-identity.js +54 -0
  55. package/dist/session/round-naming.js +56 -8
  56. package/dist/session/run.js +364 -80
  57. package/dist/session/wave.js +94 -14
  58. package/package.json +13 -3
@@ -4,10 +4,11 @@
4
4
  // → schema shape → word-table accessor → guard-lexicon) converges into ONE word
5
5
  // table with three families served by one class:
6
6
  //
7
- // capsule — the capsule-station words: the capsule keys (status · blocker ·
8
- // handoff, the pinned emit order), the `next:` route station + the stderr
9
- // stations, the status vocabulary and the route classifier words. Every
10
- // byte the capsule emits rides this family — a reorder is a red test.
7
+ // capsule — the capsule-station words: the capsule keys (status · handoff, the
8
+ // pinned emit order), the two route stations (`next:` + `reason:`) and
9
+ // the stderr stations, the status vocabulary and the route classifier
10
+ // words. Every byte the capsule emits rides this family — a reorder is a
11
+ // red test.
11
12
  // guard — the guard-ban words: the retired-vocabulary ban rows (STALE / GATE /
12
13
  // shape) the guards assert absent from the live faces. This is the ban
13
14
  // table's data-source face — the guard scan releases these rows as its
@@ -22,23 +23,28 @@
22
23
  // translation data (a new word is a new data row, never a code branch).
23
24
  //
24
25
  // The vocabulary is English-primary and death-stable: v1 keeps the same word face
25
- // the consumers already read (status · blocker · handoff · next:) — a steady state,
26
- // never a compatibility shim. The capsule class reads ALL its words through this
27
- // instance (constructor injection) — the guaranteed "one table, zero second table".
26
+ // the consumers already read (status · handoff · next:) — a steady state, never a
27
+ // compatibility shim. The capsule class reads ALL its words through this instance
28
+ // (constructor injection) — the guaranteed "one table, zero second table".
28
29
  // The capsule machine face (status · next: · CDD_BLOCKED:) is never a locale row —
29
30
  // the machine surface stays English-constant, never localizeable.
30
31
  //
31
32
  // Module-level exports are types / the declared word data / the class — zero
32
33
  // behavior-carrying bare functions (the plan's zero-bare-function discipline).
33
34
  import { DOC_TYPE_VALUES } from "../contract/declare.js";
35
+ /** The fix round's disposition summary line — the ONE template of the deliberate
36
+ * stdout byte addition (design spec §3.4). The template lives here, on the
37
+ * presentation plane; the contract criterion (`FixDispositions#summaryOf`) supplies
38
+ * the two counts it fills, so the contract plane never imports this table. */
39
+ export const FIX_DISPOSITIONS_SUMMARY = "fixed {fixed} · rejected {rejected}";
34
40
  /** The capsule word rows — every word the capsule face emits, one table. */
35
41
  export const CAPSULE_WORDS = {
36
42
  /** The capsule emit key rows — one declaration per status class (the summary
37
43
  * face's key-set single source; a reorder is a red test — the pinned face).
38
- * A success status renders `status · blocker · handoff`; a failure status renders
44
+ * A success status renders `status · handoff`; a failure status renders
39
45
  * `status` alone, plus `handoff` only when the round wrote a crash record. */
40
46
  keys: {
41
- success: ["status", "blocker", "handoff"],
47
+ success: ["status", "handoff"],
42
48
  failure: ["status"],
43
49
  handoff: "handoff",
44
50
  },
@@ -48,9 +54,12 @@ export const CAPSULE_WORDS = {
48
54
  separator: " · ",
49
55
  /** The status vocabulary — the five handoff-conclusion values. */
50
56
  status: ["APPROVED", "BLOCKED", "CHANGES_REQUESTED", "REVIEW_FIX", "TIMEOUT"],
51
- /** The route stations — the `: `-suffixed channel anchors. */
57
+ /** The route stations — the `: `-suffixed channel anchors. The two route anchors
58
+ * (`next:` and the `reason:` row that follows it) open the capsule's output;
59
+ * the three stderr anchors open the diagnostics channels. */
52
60
  stations: {
53
61
  next: "next:",
62
+ reason: "reason:",
54
63
  blocked: "CDD_BLOCKED:",
55
64
  warn: "CDD_WARN:",
56
65
  cliMissing: "CDD_CLI_MISSING:",
@@ -61,6 +70,10 @@ export const CAPSULE_WORDS = {
61
70
  review: "review",
62
71
  fix: "fix",
63
72
  implement: "implement",
73
+ /** The pipeline skill-ref template — an INSTRUCTION phrase (route to a skill),
74
+ * never a pseudo-command: `{ref}` is filled with the per-host `REFS[ref][host]`
75
+ * form at the render. */
76
+ handoffRef: "route to {ref} skill",
64
77
  docType: "the doc declares no `doc-type:` key — add `doc-type: <overall|phase-spec|single-spec|plan>` to the doc's front-matter (spec §12 · D34) and re-run",
65
78
  docTypeValue: "the doc declares `doc-type: {value}`, which is outside the declared domain — use one of {domain} and re-run",
66
79
  slugMissing: "the doc declares no `slug:` key — add `slug: <workspace-key>` to the doc's front-matter (the identity key the board and every work command share) and re-run",
@@ -74,6 +87,8 @@ export const CAPSULE_WORDS = {
74
87
  split: "the requested wave ({requested}) splits/mismatches the derived wave ({open}) — dispatch the full derived wave",
75
88
  wrongPhase: "the open wave is at {phase} — run cdd {phase} first",
76
89
  mixedBatch: "the derived batch ({batch}) mixes closed and open tasks ({closed} closed, {open} open) — a wave closes as a unit; re-declare the **DependsOn** edges so no task joins an already-executed batch",
90
+ waveTooWide: "the open wave ({tasks}) carries more than {max} tasks — narrow the wave by adjusting the plan's **DependsOn** edges (chain the extra tasks) and re-run",
91
+ tooManyTasks: "the requested task set ({tasks}) carries {count} tasks, above the {max}-task wave limit — dispatch at most {max} tasks per wave by adjusting the plan's **DependsOn** edges and re-run",
77
92
  },
78
93
  /** The pre-flight BLOCK wording rows (P4.1 T1) — the seam's refusal vocabulary,
79
94
  * single-sourced (the seam fills the {count} slot, never a re-type). */
@@ -81,6 +96,27 @@ export const CAPSULE_WORDS = {
81
96
  dirtyTree: "the working tree is dirty — commit or discard your changes (recovery is the orchestrator's job; the engine only refuses — it never stashes, makes a temporary commit, or resumes a dirty tree), then re-run the same command",
82
97
  graph: "the plan graph has {count} edge violation(s) — fix the **DependsOn** edges first",
83
98
  docContract: "the target document fails the doc-contract — fix its structural findings first",
99
+ planLedger: "the plan and the ledger disagree structurally — fix the plan's task set or the recorded waves first",
100
+ },
101
+ /** The checked-list rows (P21 §3.4) — the per-rule outcome vocabulary the
102
+ * pre-flight `checked` face renders (one row per state, never a CLI literal). */
103
+ checked: {
104
+ heading: "checked:",
105
+ passed: "passed",
106
+ failed: "failed",
107
+ skippedNoDocTarget: "skipped (no doc target)",
108
+ skippedNoLedgerFacts: "skipped (no ledger facts)",
109
+ skippedNotJudged: "skipped (not judged)",
110
+ skippedUnreadableDoc: "skipped (unreadable doc)",
111
+ planAhead: "plan-ledger: info (plan leads ledger by {count} tasks)",
112
+ planLayersUnavailable: "info (plan layers: unavailable)",
113
+ inFlight: {
114
+ free: "free — no dispatch holds this tree",
115
+ held: "held — pid {pid}",
116
+ stale: "stale holder — pid {pid} (re-run with --steal-stale to take over)",
117
+ corruptLocked: "unreadable record — lock on disk",
118
+ corruptUnlocked: "unreadable record — no lock behind",
119
+ },
84
120
  },
85
121
  /** The terminated-review promotion warning — the one CDD_WARN wording row the
86
122
  * lifecycle emits when a terminated review round's valid findings draft is
@@ -89,6 +125,29 @@ export const CAPSULE_WORDS = {
89
125
  /** The terminated-round diagnostic suffix — appended to the one CDD_BLOCKED reason
90
126
  * line of a non-promoted terminated round. Fill slots: {idleMs} / {verdict}. */
91
127
  terminationDetail: " — idleMs: {idleMs}, last sample verdict: {verdict}",
128
+ /** The round's soft-violation warning — a soft entry is bookkeeping only (design
129
+ * spec §3.3): the round still concludes, and this line names what was booked.
130
+ * Fill slot: {message}. */
131
+ softViolation: "round soft violation: {message}",
132
+ /** The in-flight rows (P21 §2.2) — the held report, the takeover hint, the two
133
+ * corrupt shapes and the three canonical recovery sentences. */
134
+ inFlight: {
135
+ held: "a dispatch is already in flight — pid {pid} · command: {command} · started: {startedAt} · running for {uptime} · wave: {wave} · slug: {slug}",
136
+ stealable: "the holding process is gone — re-run the same command with --steal-stale to take the in-flight record over",
137
+ corruptLocked: "the in-flight record is unreadable and its lock is still on disk — re-run with --steal-stale to take it over",
138
+ corruptUnlocked: "the in-flight record is unreadable and no lock is left behind — re-run with --steal-stale to take it over",
139
+ lockHeld: "held by pid {pid} · command: {command} · started: {startedAt} · wave: {wave} · slug: {slug}",
140
+ lockOnly: "held by an unreadable in-flight record — the lock is still on disk",
141
+ free: "free — no dispatch holds this tree",
142
+ recovery: [
143
+ "look at the working tree first",
144
+ "commit the changes that work",
145
+ "discard the ones that are broken",
146
+ ],
147
+ },
148
+ /** The cut-short round's late-landing hint — every kill / timeout / crash message
149
+ * carries it: the child may have written more after the engine stopped watching. */
150
+ lateLanding: "a late write may land after the round was cut short — check the working tree before starting the review",
92
151
  };
93
152
  /** The guard-ban vocabulary — the STALE / GATE / shape ban rows the guards assert
94
153
  * absent from the live faces (the single-source ban table; the guard scan releases
@@ -176,9 +235,9 @@ export class Words {
176
235
  // capsule — the station-word family
177
236
  // -------------------------------------------------------------------------
178
237
  /** The capsule emit keys of one status class, in the pinned byte order — the key
179
- * set's single source. A success status renders `status · blocker · handoff`; a
180
- * failure status (TIMEOUT / BLOCKED) renders `status`, plus `handoff` only when
181
- * the round wrote a crash record (`withHandoff`). */
238
+ * set's single source. A success status renders `status · handoff`; a failure
239
+ * status (TIMEOUT / BLOCKED) renders `status`, plus `handoff` only when the round
240
+ * wrote a crash record (`withHandoff`). */
182
241
  capsuleKeys(status, withHandoff) {
183
242
  const rows = CAPSULE_WORDS.keys;
184
243
  const failure = CAPSULE_WORDS.failureStatuses.includes(status);
@@ -210,6 +269,12 @@ export class Words {
210
269
  .replace("{value}", value)
211
270
  .replace("{domain}", DOC_TYPE_VALUES.join(", "));
212
271
  }
272
+ /** The pipeline skill-ref instruction phrase — the `handoffRef` row filled with the
273
+ * per-host `REFS[ref][host]` form (the row and its `{ref}` fill are owned here,
274
+ * never re-typed at the render). */
275
+ handoffRefWord(ref) {
276
+ return this.routeWord("handoffRef").replace("{ref}", ref);
277
+ }
213
278
  /** The identity-gate refusal wording for one refused slug verdict — the ONE
214
279
  * spelling the pre-flight gate and the dispatch carrier print (the row and its
215
280
  * `{slug}` fill are owned here, never re-typed at a carrier). */
@@ -233,6 +298,11 @@ export class Words {
233
298
  preflightWords() {
234
299
  return CAPSULE_WORDS.preflight;
235
300
  }
301
+ /** The checked-list wording rows — the per-rule outcome vocabulary (single source:
302
+ * the seam renders these rows, never a CLI literal). */
303
+ checkedWords() {
304
+ return CAPSULE_WORDS.checked;
305
+ }
236
306
  /** The terminated-review promotion warning, rendered from the termination facts —
237
307
  * the single source of both the wording row and its slot names. */
238
308
  promotionWarning(facts) {
@@ -249,6 +319,62 @@ export class Words {
249
319
  .replace("{idleMs}", String(facts.idleMs))
250
320
  .replace("{verdict}", facts.verdict);
251
321
  }
322
+ /** The soft-violation warning, rendered from the entry's message — the single
323
+ * filler of its slot. */
324
+ softViolation(message) {
325
+ return CAPSULE_WORDS.softViolation.replace("{message}", message);
326
+ }
327
+ /** The in-flight wording rows — the held report, the takeover hint, the two corrupt
328
+ * shapes and the canonical recovery sentences (one source; the CLI fills the held
329
+ * slots, never re-types a row). */
330
+ inFlightWords() {
331
+ return CAPSULE_WORDS.inFlight;
332
+ }
333
+ /** The held report of one in-flight record, rendered from its identity facts — the
334
+ * single filler of the held row's slots ({pid} / {command} / {startedAt} /
335
+ * {uptime} / {wave} / {slug}). The record's instant is the holder pid's own start
336
+ * time, so `uptime` is that process's age in whole minutes. */
337
+ inFlightHeld(facts) {
338
+ const uptimeMinutes = Math.max(0, Math.floor((Date.now() - facts.startedAt) / 60_000));
339
+ return this.inFlightWords()
340
+ .held.replace("{pid}", String(facts.pid))
341
+ .replace("{command}", facts.command)
342
+ .replace("{startedAt}", new Date(facts.startedAt).toISOString())
343
+ .replace("{uptime}", `${uptimeMinutes}m`)
344
+ .replace("{wave}", facts.wave ?? "none")
345
+ .replace("{slug}", facts.slug);
346
+ }
347
+ /** The held BLOCK message of an in-flight judgment — the pre-flight gate's refusal
348
+ * and the CLI's acquire-race render fill the SAME rows (identical bytes by
349
+ * construction: one message, two call sites). A null record is the lock-with-no-
350
+ * readable-record shape. */
351
+ inFlightBlocked(record, alive) {
352
+ if (record === null)
353
+ return this.inFlightWords().corruptLocked;
354
+ const held = this.inFlightHeld({
355
+ pid: record.pid,
356
+ command: record.command,
357
+ startedAt: record.startedAt,
358
+ wave: record.wave,
359
+ slug: record.slug,
360
+ });
361
+ return alive ? held : `${held} — ${this.inFlightWords().stealable}`;
362
+ }
363
+ /** The preview / board lock row value of one holder record — the same identity
364
+ * facts the held BLOCK names, in the `lock:` row's own shape. */
365
+ inFlightLock(record) {
366
+ return this.inFlightWords()
367
+ .lockHeld.replace("{pid}", String(record.pid))
368
+ .replace("{command}", record.command)
369
+ .replace("{startedAt}", new Date(record.startedAt).toISOString())
370
+ .replace("{wave}", record.wave ?? "none")
371
+ .replace("{slug}", record.slug);
372
+ }
373
+ /** The cut-short round's late-landing hint — appended to every kill / timeout /
374
+ * crash message (the child may still be writing after the engine stopped). */
375
+ lateLandingHint() {
376
+ return CAPSULE_WORDS.lateLanding;
377
+ }
252
378
  // -------------------------------------------------------------------------
253
379
  // locale — the word-table locale face (the langs projection + the label rows)
254
380
  // -------------------------------------------------------------------------
@@ -0,0 +1,15 @@
1
+ // packages/cdd-engine/src-next/infra/atomic.ts
2
+ // The ONE atomic write implementation of the engine (P21 §6.1): every JSON artifact
3
+ // the engine persists — progress / crash / handoff / in-flight — rides
4
+ // `Workspace.writeJson`, which delegates here. `write-file-atomic` writes a temporary
5
+ // sibling and renames it into place (aligning the mode of an existing target), so a
6
+ // process killed mid-write leaves the previous whole document, never half a JSON
7
+ // body. The seam is one instance method: zero behavior-carrying bare functions.
8
+ import writeFileAtomic from "write-file-atomic";
9
+ /** The atomic file writer — temp file + rename, through `write-file-atomic`'s synchronous face. */
10
+ export class AtomicWriter {
11
+ /** Write `text` to `file` atomically (UTF-8). */
12
+ write(file, text) {
13
+ writeFileAtomic.sync(file, text, { encoding: "utf8" });
14
+ }
15
+ }
package/dist/infra/git.js CHANGED
@@ -34,4 +34,29 @@ export class GitClient {
34
34
  return false;
35
35
  }
36
36
  }
37
+ /** The current HEAD sha — the dispatch's baseline for the crash record's
38
+ * `dispatchBase`. null outside a repo or on a branch with no commit yet (a
39
+ * present fact only, never a fabricated ref). */
40
+ async head(cwd) {
41
+ try {
42
+ return (await this.#git(cwd).revparse(["HEAD"])).trim() || null;
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ }
48
+ /** The commits added after `base`, oldest first, each as `{sha} {subject}` — the
49
+ * work a crashed child left behind. An absent base or an unreadable repo yields
50
+ * the empty list (fail-open: the diagnostic fact never breaks a crash record). */
51
+ async commitsSince(cwd, base) {
52
+ if (base === null)
53
+ return [];
54
+ try {
55
+ const log = await this.#git(cwd).log({ from: base, to: "HEAD" });
56
+ return log.all.map((entry) => `${entry.hash} ${entry.message}`);
57
+ }
58
+ catch {
59
+ return [];
60
+ }
61
+ }
37
62
  }
@@ -0,0 +1,150 @@
1
+ // packages/cdd-engine/src-next/infra/proc.ts
2
+ // The ONE OS process read face of the engine (P21 §2.3/§6.1). Two capabilities,
3
+ // deliberately two sources:
4
+ // · `ps-list` answers the non-CPU facts — the process table, the PPID chain and
5
+ // the start time that guards pid reuse;
6
+ // · `ps -o time= -g <pgid>` keeps today's process-GROUP cumulative CPU reading.
7
+ // This is the declared exception to "prefer a mature third-party package": no
8
+ // cross-platform package reports group CPU (`pidusage` is per-pid; `ps-list`
9
+ // carries no pgid). Replacing the group read with a PPID walk plus `pidusage`
10
+ // would miss members — a leader that exits reparents its members, and a
11
+ // `setsid` grandchild is not in that tree at all — and the direction of the
12
+ // error would be a false stall, i.e. killing a working child.
13
+ //
14
+ // The group's definition is pinned here: the members are `ps -g <pgid>`'s members
15
+ // (the real process group, same source as before); the PPID descent only serves
16
+ // the distinct-dispatch face ("is one dispatch running, not two"), never the CPU leg.
17
+ //
18
+ // Module-level exports are types / the class — zero behavior-carrying bare functions.
19
+ import { execFileSync } from "node:child_process";
20
+ import psList from "ps-list";
21
+ /** The process-fact reader — the single OS read face. */
22
+ export class ProcessFacts {
23
+ /** A `ps -o time=` reading: `[DD-][HH:]MM:SS[.ff]` (BSD gives centiseconds, Linux
24
+ * whole seconds — both ride the same pattern). Migrated verbatim from `Sampler`;
25
+ * this is its only copy. */
26
+ static TIME_PATTERN = /^(?:(\d+)-)?(?:(\d+):(\d+):(\d+(?:\.\d+)?)|(\d+):(\d+(?:\.\d+)?))$/;
27
+ /** The start-time tolerance of the liveness judgment (ms): a recorded start time
28
+ * within this window of the live one is the same process (a pid reused by a later
29
+ * process lands far outside it). */
30
+ static START_TIME_TOLERANCE_MS = 60_000;
31
+ /** The whole process table (`ps-list`, one read), sorted by pid for stable dedup. */
32
+ static async snapshot() {
33
+ const descriptors = await psList();
34
+ return descriptors
35
+ .map((descriptor) => ({
36
+ pid: descriptor.pid,
37
+ ppid: descriptor.ppid,
38
+ cmd: descriptor.cmd ?? descriptor.name,
39
+ startTime: descriptor.startTime?.getTime() ?? null,
40
+ }))
41
+ .sort((left, right) => left.pid - right.pid);
42
+ }
43
+ /** One process's own start instant (epoch ms) — the RECORDED side of the liveness
44
+ * judgment, so the record and the guard describe the same instant (the process's
45
+ * start, never the dispatch's). Null when the pid is absent from the table or its
46
+ * start time is unreadable — the same conservative fact `live` answers with. */
47
+ static async startOf(pid, rows) {
48
+ let table;
49
+ try {
50
+ table = rows ?? (await ProcessFacts.snapshot());
51
+ }
52
+ catch {
53
+ return null;
54
+ }
55
+ return table.find((entry) => entry.pid === pid)?.startTime ?? null;
56
+ }
57
+ /** The group's cumulative CPU (ms), summed over `ps -o time= -g <pgid>`'s members.
58
+ * Keep today's reading exactly: a non-zero `ps` exit (no such group, or no `ps`
59
+ * at all), an empty reading or any unparseable line makes the leg unreadable —
60
+ * `null`, fail-open. */
61
+ static groupCpuMs(pgid) {
62
+ let output;
63
+ try {
64
+ output = execFileSync("ps", ["-o", "time=", "-g", String(pgid)], {
65
+ encoding: "utf8",
66
+ // stdout only: `ps`'s own complaint about an unknown group is not a reading,
67
+ // and it must never reach the engine's stderr channel.
68
+ stdio: ["ignore", "pipe", "ignore"],
69
+ });
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ const lines = output
75
+ .split("\n")
76
+ .map((line) => line.trim())
77
+ .filter((line) => line.length > 0);
78
+ // A group with no observable member is not evidence of zero CPU.
79
+ if (lines.length === 0)
80
+ return null;
81
+ let total = 0;
82
+ for (const line of lines) {
83
+ const ms = ProcessFacts.#parseCpuTime(line);
84
+ if (ms === null)
85
+ return null;
86
+ total += ms;
87
+ }
88
+ return total;
89
+ }
90
+ /** The group's process ids: the PPID descent rooted at `pgid` (a wrapper process
91
+ * and the children it spawned are ONE dispatch, so `npm exec` never counts as a
92
+ * second task). The root itself is a member when the table carries it. */
93
+ static groupMembers(pgid, rows) {
94
+ const children = new Map();
95
+ for (const row of rows) {
96
+ const siblings = children.get(row.ppid);
97
+ if (siblings === undefined)
98
+ children.set(row.ppid, [row.pid]);
99
+ else
100
+ siblings.push(row.pid);
101
+ }
102
+ const members = [];
103
+ const seen = new Set();
104
+ const queue = [pgid];
105
+ while (queue.length > 0) {
106
+ const pid = queue.pop();
107
+ if (pid === undefined || seen.has(pid))
108
+ continue;
109
+ seen.add(pid);
110
+ members.push(pid);
111
+ for (const child of children.get(pid) ?? [])
112
+ queue.push(child);
113
+ }
114
+ return members.sort((left, right) => left - right);
115
+ }
116
+ /** Whether `pid` is live under the recorded start time:
117
+ * · absent from the table → false;
118
+ * · present but the start time is incompatible (|startTime − startedAt| >
119
+ * tolerance) → false (the pid was reused);
120
+ * · present with an unreadable start time → null (never "dead": an unreadable
121
+ * fact must not authorize a takeover);
122
+ * · the table itself unreadable → null (same conservative reading).
123
+ * `rows` is the test seam (the same shape `snapshot()` returns). */
124
+ static async live(pid, startedAt, rows) {
125
+ let table;
126
+ try {
127
+ table = rows ?? (await ProcessFacts.snapshot());
128
+ }
129
+ catch {
130
+ return null;
131
+ }
132
+ const row = table.find((entry) => entry.pid === pid);
133
+ if (row === undefined)
134
+ return false;
135
+ if (row.startTime === null)
136
+ return null;
137
+ return Math.abs(row.startTime - startedAt) <= ProcessFacts.START_TIME_TOLERANCE_MS;
138
+ }
139
+ /** One `time=` reading as milliseconds — `null` when the text is not that format. */
140
+ static #parseCpuTime(text) {
141
+ const match = ProcessFacts.TIME_PATTERN.exec(text);
142
+ if (match === null)
143
+ return null;
144
+ const days = Number(match[1] ?? 0);
145
+ const hours = Number(match[2] ?? 0);
146
+ const minutes = Number(match[3] ?? match[5] ?? 0);
147
+ const seconds = Number(match[4] ?? match[6] ?? 0);
148
+ return (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000;
149
+ }
150
+ }
@@ -0,0 +1,104 @@
1
+ // packages/cdd-engine/src-next/infra/round-log.ts
2
+ // P22 T2 — the per-round log file: one append stream per dispatched round, opened
3
+ // BEFORE the child spawn and closed after the child exits. The file is the round's
4
+ // silent, append-only channel — nothing is echoed to the engine's own stdio face.
5
+ //
6
+ // Module-level exports are the class — zero behavior-carrying bare functions.
7
+ import { once } from "node:events";
8
+ import { createWriteStream, statSync } from "node:fs";
9
+ import { mkdir } from "node:fs/promises";
10
+ import path from "node:path";
11
+ /**
12
+ * RoundLog — one round's append-only log file. `create` opens the stream (and creates
13
+ * the `logs/` directory the workspace does not own), `write` appends a chunk,
14
+ * `close` drains the stream and resolves once the file handle is closed. The static
15
+ * observers read the file's size/mtime for the liveness legs; an unreadable path is
16
+ * `null` (an absent observation, never a throw).
17
+ *
18
+ * The channel is an OBSERVATION face: a fault on it (ENOSPC, EIO, a late chunk after
19
+ * close) kills the log leg alone. A standing `error` listener marks the log dead —
20
+ * every later `write` is a silent no-op and the fault is reported ONCE, naming the
21
+ * path — and `close` never rejects, so a round's conclusion is never rewritten by a
22
+ * log that could not be written.
23
+ */
24
+ export class RoundLog {
25
+ #path;
26
+ #stream;
27
+ #report;
28
+ #opened = false;
29
+ #dead = false;
30
+ #closed = null;
31
+ constructor(target, stream, report) {
32
+ this.#path = target;
33
+ this.#stream = stream;
34
+ this.#report = report ?? (() => { });
35
+ stream.on("error", () => this.#fault());
36
+ }
37
+ /** Open a round log at `target`, creating its parent directory (the `logs/` dir
38
+ * lives here, never in the workspace's own root/slug creation). The resolved
39
+ * promise means the file exists and is open — zero bytes at spawn time. An open
40
+ * failure rejects (the caller's creating leg); the `onFault` notice covers the
41
+ * faults that arrive AFTER the channel is live. */
42
+ static async create(target, onFault) {
43
+ await mkdir(path.dirname(target), { recursive: true });
44
+ const stream = createWriteStream(target, { flags: "a" });
45
+ const log = new RoundLog(target, stream, onFault);
46
+ await once(stream, "open");
47
+ log.#opened = true;
48
+ return log;
49
+ }
50
+ /** The log file's absolute path. */
51
+ get path() {
52
+ return this.#path;
53
+ }
54
+ /** Append one chunk — the child's stdout/stderr bytes, never prefixed and never
55
+ * re-decoded (a chunk boundary must not tear a multi-byte character). A dead log
56
+ * swallows the chunk: the round it observes keeps running. */
57
+ write(chunk) {
58
+ if (this.#dead)
59
+ return;
60
+ this.#stream.write(chunk);
61
+ }
62
+ /** The file's size in bytes, or null when it cannot be read. */
63
+ static sizeOf(target) {
64
+ return RoundLog.#statOf(target)?.size ?? null;
65
+ }
66
+ /** The file's mtime in milliseconds, or null when it cannot be read. */
67
+ static mtimeOf(target) {
68
+ return RoundLog.#statOf(target)?.mtimeMs ?? null;
69
+ }
70
+ /** Drain and close the stream — resolves only once the handle is closed, so a read
71
+ * after this point sees the complete file. Idempotent and NEVER rejecting: a dead
72
+ * channel must not change the conclusion of the round it was observing. */
73
+ close() {
74
+ if (this.#closed !== null)
75
+ return this.#closed;
76
+ this.#closed = this.#stream.destroyed
77
+ ? Promise.resolve()
78
+ : new Promise((resolve) => {
79
+ this.#stream.once("close", () => resolve());
80
+ this.#stream.once("error", () => resolve());
81
+ this.#stream.end();
82
+ });
83
+ return this.#closed;
84
+ }
85
+ /** Mark the channel dead and report it once, naming the path. A fault during the
86
+ * open itself is the creating leg's failure (the reject), never a second notice. */
87
+ #fault() {
88
+ if (this.#dead)
89
+ return;
90
+ this.#dead = true;
91
+ if (this.#opened)
92
+ this.#report(this.#path);
93
+ }
94
+ /** The file's stat, or null on any read failure (fail-open observation). */
95
+ static #statOf(target) {
96
+ try {
97
+ const statOf = statSync(target);
98
+ return { size: statOf.size, mtimeMs: statOf.mtimeMs };
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ }
104
+ }
@@ -40,11 +40,17 @@ export const HANDOFF_FAMILIES = {
40
40
  "fix.wave": {
41
41
  name: "tasks-{tasks}-fix-{round}.json",
42
42
  },
43
- "review.spec": {
44
- name: "spec-review-{round}.json",
43
+ "review.phase-spec": {
44
+ name: "phase-spec-review-{round}.json",
45
45
  },
46
- "fix.spec": {
47
- name: "spec-fix-{round}.json",
46
+ "fix.phase-spec": {
47
+ name: "phase-spec-fix-{round}.json",
48
+ },
49
+ "review.overall": {
50
+ name: "overall-review-{round}.json",
51
+ },
52
+ "fix.overall": {
53
+ name: "overall-fix-{round}.json",
48
54
  },
49
55
  "review.plan": {
50
56
  name: "plan-review-{round}.json",
@@ -52,6 +58,12 @@ export const HANDOFF_FAMILIES = {
52
58
  "fix.plan": {
53
59
  name: "plan-fix-{round}.json",
54
60
  },
61
+ "review.single-spec": {
62
+ name: "single-spec-review-{round}.json",
63
+ },
64
+ "fix.single-spec": {
65
+ name: "single-spec-fix-{round}.json",
66
+ },
55
67
  "review.branch": {
56
68
  // find #9 (spec §6.5): the range token leaves the file name — the workspace
57
69
  // slug is the plan-slug (the fix face carries --plan) · round accumulates
@@ -16,6 +16,7 @@
16
16
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
17
17
  import path from "node:path";
18
18
  import { parse } from "jsonc-parser";
19
+ import { AtomicWriter } from "./atomic.js";
19
20
  import { RepoRoot } from "./root.js";
20
21
  /** The persisted path-field keys — the JSON fields whose value is a PATH (the
21
22
  * progress.json `reviewedRevision.doc` / `.plan` layers · the base.json `plan`
@@ -67,6 +68,8 @@ export class Workspace {
67
68
  root;
68
69
  slug;
69
70
  path;
71
+ /** The JSON write seam — every engine-persisted artifact rides it. */
72
+ #atomic = new AtomicWriter();
70
73
  constructor(root, slug) {
71
74
  this.root = root;
72
75
  this.slug = slug;
@@ -145,7 +148,9 @@ export class Workspace {
145
148
  }
146
149
  return { kind: "ok", value: text };
147
150
  }
148
- /** Write a JSON child — mkdir before write. The declared path fields (`doc` /
151
+ /** Write a JSON child — mkdir before write, and the bytes land through the ONE
152
+ * atomic write seam (`AtomicWriter`): a killed process leaves the previous whole
153
+ * document, never half a JSON body. The declared path fields (`doc` /
149
154
  * `plan`) are normalized to the canonical repoRoot-relative shape on write (P9
150
155
  * T4 §2.7), so every engine-persisted path field lands relative — the read-time
151
156
  * backstop then only covers legacy bytes (migration handles history, the read
@@ -155,7 +160,7 @@ export class Workspace {
155
160
  writeJson(name, value) {
156
161
  this.ensure();
157
162
  const normalized = this.#normalizePaths(value);
158
- writeFileSync(this.resolve(name), `${JSON.stringify(normalized, null, 2)}\n`, "utf8");
163
+ this.#atomic.write(this.resolve(name), `${JSON.stringify(normalized, null, 2)}\n`);
159
164
  }
160
165
  /** Write a text child — mkdir before write (the text twin of `writeJson`; the
161
166
  * engine-rendered brief is the one text artifact the engine authors itself).