@zhuxixi/pi-agent-board 0.12.1 → 0.13.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 (44) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +7 -7
  3. package/docs/superpowers/plans/2026-10-21-issue-221-ask-user-question.md +198 -0
  4. package/docs/superpowers/plans/2026-10-23-issue-225-monotonic-foreground-state.md +450 -0
  5. package/docs/superpowers/plans/2026-10-23-issue-229-vim-jkl.md +449 -0
  6. package/docs/superpowers/plans/2026-10-23-issue-232-attach-bg-only-cells.md +153 -0
  7. package/docs/superpowers/plans/2026-10-23-lease-heartbeat-staleness.md +537 -0
  8. package/docs/superpowers/plans/2026-10-23-selected-row-highlight.md +405 -0
  9. package/docs/superpowers/plans/2026-10-24-issue-217-windows-pid-reuse-stopping.md +367 -0
  10. package/docs/superpowers/plans/2026-10-24-issue-230-warm-host-background-runs.md +806 -0
  11. package/docs/superpowers/plans/2026-10-24-issue-238-windows-process-identity-token.md +490 -0
  12. package/docs/superpowers/plans/2026-10-24-issue-241-coordinator-root-exit.md +461 -0
  13. package/docs/superpowers/plans/2026-10-25-issue-239-coordinator-replacement-identity.md +504 -0
  14. package/docs/superpowers/specs/2026-10-20-issue-221-ask-user-question-design.md +270 -0
  15. package/docs/superpowers/specs/2026-10-22-issue-225-monotonic-foreground-state-design.md +225 -0
  16. package/docs/superpowers/specs/2026-10-23-issue-229-vim-jkl-design.md +90 -0
  17. package/docs/superpowers/specs/2026-10-23-issue-232-attach-bg-only-cells-design.md +146 -0
  18. package/docs/superpowers/specs/2026-10-23-lease-heartbeat-staleness-design.md +271 -0
  19. package/docs/superpowers/specs/2026-10-23-selected-row-highlight-design.md +191 -0
  20. package/docs/superpowers/specs/2026-10-24-issue-217-windows-pid-reuse-stopping-design.md +334 -0
  21. package/docs/superpowers/specs/2026-10-24-issue-230-warm-host-background-runs-design.md +283 -0
  22. package/docs/superpowers/specs/2026-10-24-issue-238-windows-process-identity-token-design.md +286 -0
  23. package/docs/superpowers/specs/2026-10-24-issue-241-coordinator-root-exit-design.md +381 -0
  24. package/docs/superpowers/specs/2026-10-25-issue-239-coordinator-replacement-identity-design.md +331 -0
  25. package/package.json +3 -3
  26. package/runner/pty-runner.mjs +18 -22
  27. package/runner/state-coordinator.mjs +213 -26
  28. package/scripts/run-tests.mjs +375 -0
  29. package/src/core/background-runs.mjs +273 -0
  30. package/src/core/coordinator-client.mjs +346 -26
  31. package/src/core/diagnostics.mjs +24 -0
  32. package/src/core/events.mjs +16 -3
  33. package/src/core/foreground-projection-cache.mjs +99 -0
  34. package/src/core/host-coordination.mjs +69 -1
  35. package/src/core/launch.mjs +21 -1
  36. package/src/core/locks.mjs +176 -31
  37. package/src/core/pid.mjs +4 -2
  38. package/src/core/process-identity-probe.mjs +228 -0
  39. package/src/core/state-commands.mjs +5 -1
  40. package/src/core/types.mjs +1 -0
  41. package/src/core/warm-host-sweeper.mjs +7 -2
  42. package/src/runtime/service.mjs +385 -73
  43. package/src/ui/dashboard.ts +48 -25
  44. package/src/ui/pty-attach.ts +14 -6
@@ -33,10 +33,15 @@
33
33
  * replay is deterministic — no re-decision, no re-binding.
34
34
  * - Legacy adoption: a view without materializedRevision is stamped as part of
35
35
  * its first applied command's single materialization write (no extra write).
36
+ * - Root guard (issue #241): a board root that disappears — or is REPLACED by a
37
+ * write that recreates it in the delete window — makes the supervised
38
+ * heartbeat step down with exit 0 and one stderr line. Neither path writes a
39
+ * diagnostic or state: every append helper ensureDirs its parent and would
40
+ * recreate the deleted root skeleton.
36
41
  * - AGENT_BOARD_COORDINATOR=off makes the process exit 0 immediately (tests and
37
42
  * the client's degradation path).
38
43
  */
39
- import { existsSync, readdirSync, readFileSync, statSync, unlinkSync } from "node:fs";
44
+ import { existsSync, readdirSync, statSync, unlinkSync } from "node:fs";
40
45
  import { randomBytes } from "node:crypto";
41
46
  import { createServer } from "node:net";
42
47
  import { readJson } from "../src/core/atomic.mjs";
@@ -50,7 +55,10 @@ import {
50
55
  writeCheckpoint,
51
56
  } from "../src/core/coordinator-journal.mjs";
52
57
  import { ownsEndpoint } from "../src/core/host-coordination.mjs";
53
- import { acquireOwnedViewLock, withViewLockSync } from "../src/core/locks.mjs";
58
+ import { appendDiagnostic } from "../src/core/diagnostics.mjs";
59
+ import { acquireOwnedViewLock, describeLeaseConflict, heartbeatFailureAction, withViewLockSync } from "../src/core/locks.mjs";
60
+ import { captureStartToken } from "../src/core/pid.mjs";
61
+ import { resolveTestMs } from "../src/core/test-knobs.mjs";
54
62
  import * as P from "../src/core/paths.mjs";
55
63
  import { readState, readStatus, writeState, writeStatus } from "../src/core/store.mjs";
56
64
  import { TRANSIENT_KINDS, decideStateTransition, validateCommand } from "../src/core/state-commands.mjs";
@@ -97,28 +105,150 @@ main().catch((err) => {
97
105
  process.exit(1);
98
106
  });
99
107
 
108
+ /**
109
+ * Append a coordinator-scoped diagnostic. `appendDiagnostic` throws when the
110
+ * disk is failing, so callers fence the write where a crash would be worse
111
+ * than a lost diagnostic (issue #224 D4). The AGENT_BOARD_TEST_FAIL_DIAGNOSTIC
112
+ * knob forces that throw so A14b can prove the step-down survives it.
113
+ * @param {string} code
114
+ * @param {Record<string, any>} details
115
+ * @param {"info"|"warn"|"error"} [level]
116
+ * @param {string} [source]
117
+ */
118
+ function appendCoordinatorDiagnostic(code, details, level = "info", source = "coordinator") {
119
+ if (process.env.AGENT_BOARD_TEST_FAIL_DIAGNOSTIC === "1") {
120
+ throw new Error(`forced coordinator diagnostic failure (${code})`);
121
+ }
122
+ appendDiagnostic(root, "_coordinator", { source, level, code, details });
123
+ }
124
+
125
+ /**
126
+ * Whether the board root is provably gone. Only `ENOENT` counts (issue #241):
127
+ * a transient access failure (EACCES/EBUSY, e.g. a scanner holding the
128
+ * directory) must never kill a healthy coordinator, so it reads as "present".
129
+ * @returns {boolean}
130
+ */
131
+ function rootVanished() {
132
+ try {
133
+ statSync(root);
134
+ return false;
135
+ } catch (err) {
136
+ return /** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT";
137
+ }
138
+ }
139
+
140
+ /**
141
+ * Snapshot the board root directory's filesystem identity (issue #241).
142
+ * `{dev, ino}` identifies one exact directory: a delete-and-recreate at the same
143
+ * path gets a new inode, which is the only way to tell "the root came back" from
144
+ * "the root never left" once a write's ensureDir has recreated it. Returns null
145
+ * when the root is missing or the filesystem reports no usable identity (ino 0,
146
+ * or no dev/ino at all), which degrades the check to existence-only.
147
+ * @returns {{dev: number, ino: number}|null}
148
+ */
149
+ function captureRootIdentity() {
150
+ try {
151
+ const st = statSync(root);
152
+ if (!Number.isFinite(st.dev) || !Number.isFinite(st.ino) || st.ino === 0) return null;
153
+ return { dev: st.dev, ino: st.ino };
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Whether the board root is gone or was replaced since boot (issue #241).
161
+ * Existence alone is not enough: `appendCommand`/`writeState`/lease acquisition
162
+ * ensureDir their parent, so a write landing after the delete RECREATES the path
163
+ * and a plain stat then reads "present" (final-review I1). Comparing against the
164
+ * identity captured at boot detects the replacement on the next supervised tick,
165
+ * including the boot-window race where lease acquisition recreates the root.
166
+ * Only `ENOENT` counts as missing; any other stat error (EACCES/EBUSY) reads as
167
+ * present so a transient access failure never kills a healthy coordinator. With
168
+ * no captured identity the check degrades to existence-only (never a false
169
+ * step-down).
170
+ * @param {{dev: number, ino: number}|null} identity
171
+ * @returns {"missing"|"replaced"|null}
172
+ */
173
+ function rootVanishedOrReplaced(identity) {
174
+ try {
175
+ const st = statSync(root);
176
+ if (!identity) return null;
177
+ return st.dev !== identity.dev || st.ino !== identity.ino ? "replaced" : null;
178
+ } catch (err) {
179
+ return /** @type {NodeJS.ErrnoException} */ (err)?.code === "ENOENT" ? "missing" : null;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * The one stderr line every "root is gone" exit emits (issue #241): the boot
185
+ * guard and the supervised step-down. Neither writes a diagnostic: every
186
+ * append helper ensures its parent directory (src/core/atomic.mjs), so a write
187
+ * under <root>/views/_coordinator would recreate the deleted directory chain —
188
+ * the throwaway-root residue this issue exists to remove. Detached callers
189
+ * ignore stdio; a test pipes stderr and attributes the exit to this line.
190
+ * @param {"missing"|"replaced"} state
191
+ * @param {string} outcome
192
+ */
193
+ function writeRootGone(state, outcome) {
194
+ process.stderr.write(`state-coordinator: board root ${state} (${root}); ${outcome}\n`);
195
+ }
196
+
100
197
  async function main() {
101
198
  const instanceId = randomBytes(8).toString("hex");
102
199
  const startedAt = Date.now();
200
+ const heartbeatMs = resolveTestMs(process.env, "AGENT_BOARD_TEST_COORDINATOR_HEARTBEAT_MS", HEARTBEAT_MS);
201
+
202
+ // Capture the root's identity BEFORE the boot guard (issue #241, final-review
203
+ // I1): a delete between the guard and lease acquisition would let that
204
+ // ensureDir recreate the root WITH a valid lease, and the process would then
205
+ // serve it forever. The tick compares against this snapshot, so the recreated
206
+ // directory is detected on the first heartbeat.
207
+ const rootIdentity = captureRootIdentity();
208
+
209
+ // 0. A root that is already gone must fail closed (issue #241 A3b). Lease
210
+ // acquisition runs ensureDir, which would happily REBUILD the deleted board
211
+ // and serve that empty root forever — the exact orphan shape this issue is
212
+ // about. "Nothing to serve" is an expected outcome like a lost lease, so it
213
+ // exits 0, writes no diagnostic, and logs the shared stderr line.
214
+ if (rootVanished()) {
215
+ writeRootGone("missing", "nothing to serve; exiting");
216
+ process.exit(0);
217
+ }
103
218
 
104
219
  // 1. Lease first: a second coordinator is an expected, idempotent no-op.
105
220
  // Identity carries a POSIX startToken (pty-runner pattern) so a SIGKILLed
106
- // coordinator's lease can be reclaimed by the next instance after pid reuse.
221
+ // coordinator's lease can be reclaimed by the next instance after pid reuse,
222
+ // plus the in-process instanceId the pong reports (issue #239 A4) so a client
223
+ // can tell whether the live endpoint is still the lease's owner.
224
+ // heartbeatMs declares the staleness contract (issue #224): a holder that
225
+ // stops heartbeating becomes reclaimable on its own staleness.
107
226
  /** @type {import("../src/core/locks.mjs").Lease} */
108
227
  let lease;
109
228
  try {
110
229
  lease = acquireOwnedViewLock(root, "_coordinator", "state-coordinator", {
111
230
  waitMs: 500,
112
- identity: { pid: process.pid, startToken: captureStartToken(process.pid) },
231
+ identity: { pid: process.pid, startToken: captureStartToken(process.pid), instanceId },
232
+ heartbeatMs,
113
233
  });
114
234
  } catch (err) {
235
+ // Record the conflict instead of exiting silently (issue #224 D6). The
236
+ // diagnostic write is best-effort: it must never turn the expected
237
+ // idempotent exit into a crash.
238
+ const summary = describeLeaseConflict(root, "_coordinator", "state-coordinator");
239
+ if (summary) {
240
+ try { appendCoordinatorDiagnostic("coordinator_lease_unavailable", summary, "error"); } catch { /* best effort */ }
241
+ }
115
242
  process.stderr.write(`state-coordinator: lease unavailable (${err?.code ?? err?.message ?? "unknown"}); another instance may own it; exiting\n`);
116
243
  process.exit(0);
117
244
  }
118
- const startTouchTimer = setInterval(() => {
119
- try { lease?.touch(); } catch { /* best effort */ }
120
- }, HEARTBEAT_MS);
121
- startTouchTimer.unref?.();
245
+ // Leave a trace when this acquire reclaimed a stale lease (issue #224 D6).
246
+ if (lease.reclaimed) {
247
+ try { appendCoordinatorDiagnostic("lease_reclaimed", { ...lease.reclaimed }, "info", "lock"); } catch { /* best effort */ }
248
+ }
249
+ // Boot-edge touch (issue #224 D5): reflect acquisition progress before the
250
+ // supervised interval starts. Never counted toward the failure counter.
251
+ try { lease.touch(); } catch { /* best effort */ }
122
252
 
123
253
  // 2. Boot state: journal summary, processed-command ring, replay, counter init.
124
254
  // Repair a crash-torn tail FIRST: without it the first post-restart append
@@ -161,6 +291,10 @@ async function main() {
161
291
  }
162
292
  let lastCheckpointBytes = 0;
163
293
 
294
+ // Boot-edge touch (issue #224 D5): replay is done; the heartbeat now
295
+ // reflects live progress before the endpoint binds. Never counted.
296
+ try { lease.touch(); } catch { /* best effort */ }
297
+
164
298
  // 3. Control socket (JSONL, pty-runner's line-buffered server shape).
165
299
  const socketPath = P.coordinatorEndpointPathFor(process.platform, root);
166
300
  if (process.platform !== "win32" && existsSync(socketPath)) {
@@ -186,6 +320,16 @@ async function main() {
186
320
  shutdown(1);
187
321
  });
188
322
 
323
+ // Boot-edge touch (issue #224 D5): the endpoint bind is the last boot
324
+ // boundary; the supervised interval takes over once listen succeeds.
325
+ // Never counted toward the failure counter.
326
+ try { lease.touch(); } catch { /* best effort */ }
327
+
328
+ // Consecutive supervised heartbeat failures. Only interval touches count;
329
+ // the boot-edge touches above are deliberately ignored (issue #224 D4/D5).
330
+ let consecutiveTouchFailures = 0;
331
+ let heartbeatTimer = null;
332
+
189
333
  server.listen(socketPath, () => {
190
334
  if (process.platform !== "win32") {
191
335
  try {
@@ -193,6 +337,66 @@ async function main() {
193
337
  boundSocketIdentity = { dev: st.dev, ino: st.ino };
194
338
  } catch { /* without the identity, cleanup degrades to no-op */ }
195
339
  }
340
+ // Supervision starts only after the endpoint is bound (issue #224 D4):
341
+ // a live-but-stuck holder must step down before its lease can be
342
+ // preempted as stale, and stepping down before the socket exists would
343
+ // make the A14 endpoint cleanup a no-op.
344
+ heartbeatTimer = setInterval(() => {
345
+ // Step down when the board root is gone or was REPLACED (issue #241):
346
+ // a detached coordinator that outlives its root serves nobody, and its
347
+ // lease can never be reclaimed while the pid is alive. Detection reuses
348
+ // this tick — no second timer — so the worst case is one heartbeat.
349
+ //
350
+ // Existence alone is not enough (final-review I1): a write landing after
351
+ // the delete (appendCommand / writeState → ensureDir) recreates the
352
+ // directory, so a plain stat would read "present" and the coordinator
353
+ // would serve a dead board. The boot-time dev/ino identity distinguishes
354
+ // the recreated directory from the original one, and the same guard
355
+ // catches a root deleted between the boot guard and lease acquisition
356
+ // (that ensureDir would recreate it WITH a lease).
357
+ //
358
+ // No diagnostic is written on either path: every append helper
359
+ // ensureDirs its parent (src/core/atomic.mjs), so appending to
360
+ // <root>/views/_coordinator/diagnostics.jsonl would RECREATE the
361
+ // deleted directory chain — reintroducing exactly the throwaway-root
362
+ // residue this issue measures (U1). The shared stderr line is the
363
+ // attribution instead; detached callers ignore stdio, while a test
364
+ // spawns with a stderr pipe. Residual accepted (spec §7): a write in
365
+ // the delete window may leave a skeleton directory (data, not a
366
+ // process); this tick bounds its lifetime.
367
+ //
368
+ // A missing root also makes the touch below fail, but that path needs
369
+ // three consecutive failures; checking first attributes the step-down
370
+ // to the real cause and vacates the root immediately.
371
+ const rootState = rootVanishedOrReplaced(rootIdentity);
372
+ if (rootState) {
373
+ writeRootGone(rootState, "stepping down");
374
+ shutdown(0);
375
+ return;
376
+ }
377
+ let ok;
378
+ try {
379
+ ok = process.env.AGENT_BOARD_TEST_FORCE_TOUCH_FAILURE === "1" ? false : lease.touch();
380
+ } catch {
381
+ ok = false;
382
+ }
383
+ if (!ok) {
384
+ consecutiveTouchFailures += 1;
385
+ if (heartbeatFailureAction(consecutiveTouchFailures) === "abandon") {
386
+ // Count → diagnostic → shutdown, in that order. The
387
+ // diagnostic write throws when the disk is failing (the
388
+ // exact step-down scenario), so it is fenced and must not
389
+ // block the exit.
390
+ try {
391
+ appendCoordinatorDiagnostic("coordinator_heartbeat_lost", { consecutiveFailures: consecutiveTouchFailures }, "error");
392
+ } catch { /* a failing diagnostic must not block the step-down */ }
393
+ shutdown(0);
394
+ }
395
+ } else {
396
+ consecutiveTouchFailures = 0;
397
+ }
398
+ }, heartbeatMs);
399
+ heartbeatTimer.unref?.();
196
400
  });
197
401
 
198
402
  let shuttingDown = false;
@@ -202,7 +406,7 @@ async function main() {
202
406
  function shutdown(code) {
203
407
  if (shuttingDown) return;
204
408
  shuttingDown = true;
205
- try { clearInterval(startTouchTimer); } catch { /* best effort */ }
409
+ try { clearInterval(heartbeatTimer); } catch { /* best effort */ }
206
410
  try { server.close(); } catch { /* already closed */ }
207
411
  if (process.platform !== "win32" && boundSocketIdentity) {
208
412
  try {
@@ -410,20 +614,3 @@ async function main() {
410
614
  lastCheckpointBytes = gcJournal(root);
411
615
  }
412
616
  }
413
-
414
- /** POSIX process start token — /proc/<pid>/stat field 22 (starttime), stable
415
- * across exec(2). Same recipe as pty-runner: lets locks.mjs reclaim this
416
- * coordinator's lease after a SIGKILL even if the pid was reused. null on
417
- * failure or non-Linux platforms (reclaim degrades to "blocked" there — same
418
- * platform parity as PTY hosts). */
419
- function captureStartToken(pid) {
420
- if (process.platform !== "linux" || !pid) return null;
421
- try {
422
- const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
423
- const afterComm = stat.slice(stat.lastIndexOf(")") + 1).trimStart();
424
- const fields = afterComm.split(/\s+/);
425
- return fields[19] ?? null;
426
- } catch {
427
- return null;
428
- }
429
- }
@@ -0,0 +1,375 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Suite gate for issue #241: run every test file through `node --test` and fail
4
+ * the run when a detached state-coordinator leaked past the test process.
5
+ *
6
+ * Why this exists: every coordinator integration test creates a throwaway board
7
+ * root under the OS temp dir and spawns a detached coordinator. A coordinator
8
+ * that fails to step down stays alive forever and pins its root, so leaks
9
+ * accumulate on a developer box instead of showing up as a test failure.
10
+ *
11
+ * Design (spec §3.3):
12
+ * - Snapshot the matching coordinators BEFORE the run. Pre-existing ones are
13
+ * warn-only: they are not this run's fault and are never killed.
14
+ * - After the run, poll up to GRACE_MS for every coordinator above the snapshot
15
+ * to be gone (the 1 s self-exit window plus load slack).
16
+ * - Survivors: print pid + root, SIGTERM, wait 2 s, SIGKILL leftovers, exit 1.
17
+ * - A test run killed by a signal (`exitCode === null`) is never a success.
18
+ * - Enumeration unavailable: warn and skip the residue check (fail-open). A
19
+ * missing `pwsh`/`powershell`/`ps` must not turn into a red suite.
20
+ *
21
+ * Selection is deliberately narrow: the command line must contain THIS
22
+ * checkout's absolute `runner/state-coordinator.mjs` and its root argument must
23
+ * resolve under `os.tmpdir()`. Another checkout's test coordinator never
24
+ * matches (its script path differs), and a default production board
25
+ * (`~/.pi/agent/agent-board`) never matches either. Accepted limit (spec §7): a
26
+ * board whose `AGENT_BOARD_ROOT` points under `os.tmpdir()` and whose runner is
27
+ * this checkout is indistinguishable from a test coordinator, so the gate would
28
+ * kill that live board.
29
+ *
30
+ * Known limit (final-review m7): POSIX selection is token-based and `ps` output
31
+ * is unquoted, so a checkout path containing spaces splits and its coordinators
32
+ * are not selected (the gate silently no-ops instead of failing). win32 CIM
33
+ * output quotes paths with spaces, so the tokenizer handles it there.
34
+ *
35
+ * This module must stay import-side-effect free: `test/run-tests-wrapper.test.mjs`
36
+ * imports the pure functions and `runSuite`, and a spurious `main()` at import
37
+ * time would recursively start the whole suite. Only the entry-point guard at
38
+ * the bottom of this file may call `main()`.
39
+ */
40
+ import { execFileSync, spawn } from "node:child_process";
41
+ import { readdirSync } from "node:fs";
42
+ import { tmpdir } from "node:os";
43
+ import { join, posix, resolve } from "node:path";
44
+ import { fileURLToPath, pathToFileURL } from "node:url";
45
+
46
+ /** The only coordinator script this checkout's suite spawns. */
47
+ const COORDINATOR_RELATIVE_SCRIPT = "runner/state-coordinator.mjs";
48
+ const DEFAULT_GRACE_MS = 10_000;
49
+ const DEFAULT_POLL_MS = 100;
50
+ /** SIGTERM → SIGKILL pause. On win32 SIGTERM is TerminateProcess; POSIX needs the grace. */
51
+ const SIGKILL_DELAY_MS = 2_000;
52
+ const SIGTERM = "SIGTERM";
53
+ const SIGKILL = "SIGKILL";
54
+
55
+ /**
56
+ * Normalize a path for comparison without depending on the host platform:
57
+ * forward slashes, dot segments removed, no trailing separator (a `tmpRoot` like
58
+ * `C:\Temp\` or `/tmp/` must select exactly like its un-suffixed form), and (on
59
+ * win32) case-folded. Filesystem roots keep their separator (`/` stays `/`,
60
+ * `C:/` stays `C:/`): stripping it would turn a drive root into the
61
+ * drive-relative `C:`. The platform is explicit so the unit tests can exercise
62
+ * win32 samples on POSIX CI.
63
+ * @param {string} value
64
+ * @param {string} platform
65
+ * @returns {string}
66
+ */
67
+ function canonicalPath(value, platform) {
68
+ const text = String(value ?? "").replace(/\\/g, "/");
69
+ if (!text) return "";
70
+ let normalized = posix.normalize(text);
71
+ if (normalized.length > 1 && normalized.endsWith("/")) {
72
+ const trimmed = normalized.replace(/\/+$/, "");
73
+ normalized = trimmed.endsWith(":") ? `${trimmed}/` : trimmed;
74
+ }
75
+ return platform === "win32" ? normalized.toLowerCase() : normalized;
76
+ }
77
+
78
+ /**
79
+ * True when `candidate` is `directory` itself or one of its descendants, using
80
+ * the already-canonical spellings. The trailing-slash check keeps a sibling
81
+ * such as `/tmpfoo` from matching `/tmp`; a filesystem root already ends in the
82
+ * separator, so `${directory}/` would become `//` and match nothing there.
83
+ * @param {string} candidate
84
+ * @param {string} directory
85
+ * @returns {boolean}
86
+ */
87
+ function isUnderDirectory(candidate, directory) {
88
+ if (!candidate || !directory) return false;
89
+ if (candidate === directory) return true;
90
+ return candidate.startsWith(directory.endsWith("/") ? directory : `${directory}/`);
91
+ }
92
+
93
+ /**
94
+ * Split a process command line into argv-shaped tokens, honoring the double
95
+ * quotes CIM emits around paths with spaces. Node's own argv never needs
96
+ * backslash-escaped quotes inside a path, so this covers the coordinator shape.
97
+ * @param {string} commandLine
98
+ * @returns {string[]}
99
+ */
100
+ function tokenizeCommandLine(commandLine) {
101
+ const tokens = [];
102
+ for (const match of commandLine.matchAll(/"([^"]*)"|(\S+)/g)) tokens.push(match[1] ?? match[2]);
103
+ return tokens;
104
+ }
105
+
106
+ /**
107
+ * Parse the platform's process-enumeration output. Never throws: unparsable
108
+ * output and unparsable lines are skipped.
109
+ * @param {string} raw
110
+ * @param {string} platform
111
+ * @returns {Array<{pid: number, commandLine: string}>}
112
+ */
113
+ export function parseProcessList(raw, platform) {
114
+ const text = String(raw ?? "").trim();
115
+ if (!text) return [];
116
+ if (platform === "win32") {
117
+ let data;
118
+ try {
119
+ data = JSON.parse(text);
120
+ } catch {
121
+ return [];
122
+ }
123
+ // ConvertTo-Json emits a single object when exactly one process matches.
124
+ const rows = Array.isArray(data) ? data : [data];
125
+ return rows
126
+ .map((row) => ({ pid: Number(row?.ProcessId ?? 0), commandLine: String(row?.CommandLine ?? "") }))
127
+ .filter((row) => Number.isFinite(row.pid) && row.pid > 0 && row.commandLine);
128
+ }
129
+ const out = [];
130
+ for (const line of text.split(/\r?\n/)) {
131
+ const match = /^\s*(\d+)\s+(.+)$/.exec(line);
132
+ if (match) out.push({ pid: Number(match[1]), commandLine: match[2] });
133
+ }
134
+ return out;
135
+ }
136
+
137
+ /**
138
+ * Keep only coordinators this checkout's suite could have spawned: the command
139
+ * line runs `<repoRoot>/runner/state-coordinator.mjs` and the token after that
140
+ * script (the root argument, quotes stripped by the tokenizer) resolves under
141
+ * `tmpRoot`. Production roots and other checkouts never match.
142
+ * @param {{
143
+ * processes?: Array<{pid: number, commandLine: string}>,
144
+ * repoRoot: string,
145
+ * tmpRoot: string,
146
+ * platform: string,
147
+ * }} args
148
+ * @returns {Array<{pid: number, root: string}>} deterministic order by pid
149
+ */
150
+ export function selectOrphanCoordinators({ processes, repoRoot, tmpRoot, platform }) {
151
+ const scriptPath = canonicalPath(`${repoRoot}/${COORDINATOR_RELATIVE_SCRIPT}`, platform);
152
+ const tmpPath = canonicalPath(tmpRoot, platform);
153
+ if (!scriptPath || !tmpPath) return [];
154
+ const out = [];
155
+ for (const proc of processes ?? []) {
156
+ const pid = Number(proc?.pid ?? 0);
157
+ if (!Number.isFinite(pid) || pid <= 0) continue;
158
+ const tokens = tokenizeCommandLine(String(proc?.commandLine ?? ""));
159
+ const scriptIndex = tokens.findIndex((token) => canonicalPath(token, platform) === scriptPath);
160
+ if (scriptIndex < 0) continue;
161
+ const root = tokens[scriptIndex + 1];
162
+ if (!root) continue;
163
+ if (!isUnderDirectory(canonicalPath(root, platform), tmpPath)) continue;
164
+ out.push({ pid, root });
165
+ }
166
+ return out.sort((left, right) => left.pid - right.pid);
167
+ }
168
+
169
+ /**
170
+ * @param {unknown} error
171
+ * @returns {string}
172
+ */
173
+ function describeError(error) {
174
+ return error instanceof Error ? error.message : String(error);
175
+ }
176
+
177
+ /**
178
+ * Orchestrate one suite run and its residue check. Every side effect is
179
+ * injected so the unit tests drive every branch without spawning or killing
180
+ * anything; the real shell lives in `main()`.
181
+ * @param {{
182
+ * spawnTest: () => Promise<{exitCode: number|null, signal?: string|null}>,
183
+ * listProcesses: () => Array<{pid: number, commandLine: string}>|Promise<Array<{pid: number, commandLine: string}>>,
184
+ * kill: (pid: number, signal: string) => void,
185
+ * sleep: (ms: number) => Promise<void>,
186
+ * log: (line: string) => void,
187
+ * repoRoot: string,
188
+ * tmpRoot: string,
189
+ * platform: string,
190
+ * graceMs?: number,
191
+ * pollMs?: number,
192
+ * now?: () => number,
193
+ * }} deps
194
+ * @returns {Promise<{exitCode: number, survivors: number[]}>}
195
+ */
196
+ export async function runSuite(deps) {
197
+ const {
198
+ spawnTest,
199
+ listProcesses,
200
+ kill,
201
+ sleep,
202
+ log,
203
+ repoRoot,
204
+ tmpRoot,
205
+ platform,
206
+ graceMs = DEFAULT_GRACE_MS,
207
+ pollMs = DEFAULT_POLL_MS,
208
+ now = Date.now,
209
+ } = deps;
210
+ const select = (processes) => selectOrphanCoordinators({ processes, repoRoot, tmpRoot, platform });
211
+
212
+ // Snapshot first: pre-existing coordinators predate this run, so they are
213
+ // warned about but never killed and never fail the suite.
214
+ /** @type {Set<number>} */
215
+ const preexisting = new Set();
216
+ let canCheckResidue = true;
217
+ try {
218
+ for (const proc of select(await listProcesses())) preexisting.add(proc.pid);
219
+ } catch (error) {
220
+ canCheckResidue = false;
221
+ log(`run-tests: WARNING: cannot enumerate node processes (${describeError(error)}); skipping the coordinator residue check`);
222
+ }
223
+ if (preexisting.size > 0) {
224
+ log(`run-tests: WARNING: ${preexisting.size} pre-existing state-coordinator process(es) before the run; not killed, not a failure`);
225
+ }
226
+
227
+ const run = await spawnTest();
228
+
229
+ // Poll for post-run residue. The last successful enumeration is kept when a
230
+ // later poll fails: an already observed survivor still fails the run, while
231
+ // never having enumerated at all stays fail-open.
232
+ /** @type {Array<{pid: number, root: string}>} */
233
+ let survivors = [];
234
+ let residueChecked = false;
235
+ if (canCheckResidue) {
236
+ const deadline = now() + graceMs;
237
+ for (;;) {
238
+ let current;
239
+ try {
240
+ current = select(await listProcesses());
241
+ residueChecked = true;
242
+ } catch (error) {
243
+ canCheckResidue = false;
244
+ log(`run-tests: WARNING: cannot enumerate node processes (${describeError(error)}); skipping the coordinator residue check`);
245
+ break;
246
+ }
247
+ survivors = current.filter((proc) => !preexisting.has(proc.pid));
248
+ if (survivors.length === 0) break;
249
+ if (now() >= deadline) break;
250
+ await sleep(pollMs);
251
+ }
252
+ }
253
+
254
+ /** @type {number[]} */
255
+ const survivorPids = [];
256
+ if (survivors.length > 0) {
257
+ for (const proc of survivors) log(`run-tests: leaked state-coordinator pid=${proc.pid} root=${proc.root}`);
258
+ for (const proc of survivors) kill(proc.pid, SIGTERM);
259
+ await sleep(SIGKILL_DELAY_MS);
260
+ let leftovers = survivors;
261
+ if (canCheckResidue) {
262
+ try {
263
+ leftovers = select(await listProcesses()).filter((proc) => !preexisting.has(proc.pid));
264
+ } catch (error) {
265
+ log(`run-tests: WARNING: cannot enumerate node processes after SIGTERM (${describeError(error)}); sending SIGKILL to the known survivors`);
266
+ }
267
+ }
268
+ for (const proc of leftovers) {
269
+ log(`run-tests: survivor pid=${proc.pid} ignored SIGTERM; sending SIGKILL`);
270
+ kill(proc.pid, SIGKILL);
271
+ }
272
+ survivorPids.push(...survivors.map((proc) => proc.pid));
273
+ } else if (residueChecked) {
274
+ log("run-tests: no leaked coordinators");
275
+ }
276
+
277
+ let exitCode;
278
+ if (run.exitCode === null) {
279
+ log(`run-tests: the test run ended by signal ${run.signal ?? "unknown"}; treating it as a failure`);
280
+ exitCode = 1;
281
+ } else {
282
+ exitCode = run.exitCode;
283
+ }
284
+ if (survivors.length > 0) exitCode = 1;
285
+ return { exitCode, survivors: survivorPids };
286
+ }
287
+
288
+ /**
289
+ * Enumerate node processes with their command lines. Throws when the platform's
290
+ * enumeration tool is unavailable; `runSuite` turns that into a warning and
291
+ * skips the residue check (fail-open).
292
+ * @returns {Array<{pid: number, commandLine: string}>}
293
+ */
294
+ function listNodeProcesses() {
295
+ if (process.platform === "win32") {
296
+ // Forced UTF-8: ConvertTo-Json otherwise emits code-page text that mangles
297
+ // non-ASCII root paths, and CIM may quote paths containing spaces.
298
+ const prefix = "[Console]::OutputEncoding=[Text.Encoding]::UTF8; $OutputEncoding=[Text.Encoding]::UTF8;";
299
+ const query = "Get-CimInstance Win32_Process -Filter \"Name='node.exe'\" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress";
300
+ const args = ["-NoProfile", "-NonInteractive", "-Command", `${prefix} ${query}`];
301
+ for (const shell of ["pwsh", "powershell"]) {
302
+ try {
303
+ return parseProcessList(execFileSync(shell, args, { encoding: "utf8" }), process.platform);
304
+ } catch (error) {
305
+ // Only a missing shell falls through to the next candidate; an
306
+ // enumeration failure is not masked by retrying another binary.
307
+ if (error?.code !== "ENOENT") throw error;
308
+ }
309
+ }
310
+ throw new Error("neither pwsh nor powershell is available");
311
+ }
312
+ // -ww matters: without unlimited width, ps truncates the command line before
313
+ // the root argument and a leaked coordinator silently escapes selection.
314
+ return parseProcessList(execFileSync("ps", ["-e", "-ww", "-o", "pid=,args="], { encoding: "utf8" }), process.platform);
315
+ }
316
+
317
+ /**
318
+ * Run the suite files through `node --test` with inherited stdio.
319
+ * @param {string} repoRoot
320
+ * @param {string[]} files repoRoot-relative test paths
321
+ * @returns {Promise<{exitCode: number|null, signal: string|null}>}
322
+ */
323
+ function spawnSuite(repoRoot, files) {
324
+ return new Promise((settle) => {
325
+ let settled = false;
326
+ const finish = (value) => {
327
+ if (settled) return;
328
+ settled = true;
329
+ settle(value);
330
+ };
331
+ const child = spawn(process.execPath, ["--test", ...files], { cwd: repoRoot, stdio: "inherit", windowsHide: true });
332
+ child.on("error", (error) => {
333
+ console.error(`run-tests: failed to spawn the test runner: ${describeError(error)}`);
334
+ finish({ exitCode: 1, signal: null });
335
+ });
336
+ child.on("exit", (code, signal) => finish({ exitCode: code, signal: signal ?? null }));
337
+ });
338
+ }
339
+
340
+ /**
341
+ * Real shell: derive this checkout from the module location, enumerate the test
342
+ * files, run the suite, grade the residue, and set `process.exitCode`.
343
+ * @returns {Promise<{exitCode: number, survivors: number[]}>}
344
+ */
345
+ export async function main() {
346
+ const repoRoot = fileURLToPath(new URL("..", import.meta.url));
347
+ // Sorted so a failing run's file ordering is stable across platforms.
348
+ const files = readdirSync(join(repoRoot, "test"))
349
+ .filter((name) => name.endsWith(".test.mjs"))
350
+ .sort()
351
+ .map((name) => join("test", name));
352
+ const result = await runSuite({
353
+ repoRoot,
354
+ tmpRoot: tmpdir(),
355
+ platform: process.platform,
356
+ spawnTest: () => spawnSuite(repoRoot, files),
357
+ listProcesses: () => listNodeProcesses(),
358
+ kill: (pid, signal) => {
359
+ try {
360
+ process.kill(pid, signal);
361
+ } catch { /* already gone */ }
362
+ },
363
+ sleep: (ms) => new Promise((resolveSleep) => setTimeout(resolveSleep, ms)),
364
+ log: (line) => console.log(line),
365
+ });
366
+ process.exitCode = result.exitCode;
367
+ return result;
368
+ }
369
+
370
+ // Import safety: see the module JSDoc. `main()` must never run while a test
371
+ // imports the pure functions, or `node --test` would recurse into itself.
372
+ const invokedPath = process.argv[1];
373
+ if (invokedPath !== undefined && import.meta.url === pathToFileURL(resolve(invokedPath)).href) {
374
+ await main();
375
+ }