@zhuxixi/pi-agent-board 0.12.1 → 0.13.1

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 (53) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +29 -11
  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/plans/2026-10-26-issue-245-key-hints-doc-sync.md +244 -0
  15. package/docs/superpowers/plans/2026-10-27-issue-172-fullscreen-selection-clear.md +344 -0
  16. package/docs/superpowers/plans/2026-10-27-issue-252-select-key-hints.md +209 -0
  17. package/docs/superpowers/plans/2026-10-28-issue-255-coordinator-endpoint-zombie.md +442 -0
  18. package/docs/superpowers/specs/2026-10-20-issue-221-ask-user-question-design.md +270 -0
  19. package/docs/superpowers/specs/2026-10-22-issue-225-monotonic-foreground-state-design.md +225 -0
  20. package/docs/superpowers/specs/2026-10-23-issue-229-vim-jkl-design.md +90 -0
  21. package/docs/superpowers/specs/2026-10-23-issue-232-attach-bg-only-cells-design.md +146 -0
  22. package/docs/superpowers/specs/2026-10-23-lease-heartbeat-staleness-design.md +271 -0
  23. package/docs/superpowers/specs/2026-10-23-selected-row-highlight-design.md +191 -0
  24. package/docs/superpowers/specs/2026-10-24-issue-217-windows-pid-reuse-stopping-design.md +334 -0
  25. package/docs/superpowers/specs/2026-10-24-issue-230-warm-host-background-runs-design.md +283 -0
  26. package/docs/superpowers/specs/2026-10-24-issue-238-windows-process-identity-token-design.md +286 -0
  27. package/docs/superpowers/specs/2026-10-24-issue-241-coordinator-root-exit-design.md +381 -0
  28. package/docs/superpowers/specs/2026-10-25-issue-239-coordinator-replacement-identity-design.md +331 -0
  29. package/docs/superpowers/specs/2026-10-26-issue-245-key-hints-doc-sync-design.md +72 -0
  30. package/docs/superpowers/specs/2026-10-27-issue-172-fullscreen-selection-clear-design.md +248 -0
  31. package/docs/superpowers/specs/2026-10-27-issue-252-select-key-hints-design.md +95 -0
  32. package/docs/superpowers/specs/2026-10-28-issue-255-coordinator-endpoint-zombie-design.md +380 -0
  33. package/package.json +3 -3
  34. package/runner/pty-runner.mjs +18 -22
  35. package/runner/state-coordinator.mjs +275 -31
  36. package/scripts/run-tests.mjs +375 -0
  37. package/src/core/background-runs.mjs +273 -0
  38. package/src/core/coordinator-client.mjs +346 -26
  39. package/src/core/diagnostics.mjs +24 -0
  40. package/src/core/events.mjs +16 -3
  41. package/src/core/foreground-projection-cache.mjs +99 -0
  42. package/src/core/host-coordination.mjs +117 -1
  43. package/src/core/launch.mjs +21 -1
  44. package/src/core/locks.mjs +176 -31
  45. package/src/core/pid.mjs +4 -2
  46. package/src/core/process-identity-probe.mjs +228 -0
  47. package/src/core/pty-scroll.mjs +8 -8
  48. package/src/core/state-commands.mjs +5 -1
  49. package/src/core/types.mjs +1 -0
  50. package/src/core/warm-host-sweeper.mjs +7 -2
  51. package/src/runtime/service.mjs +385 -73
  52. package/src/ui/dashboard.ts +55 -29
  53. package/src/ui/pty-attach.ts +57 -21
@@ -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
+ }
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Background-workflow run detection for warm-host eviction (issue #230).
3
+ *
4
+ * A warm host whose session owns a `running` pi-workflow run must not be swept:
5
+ * eviction revokes the host, the child pi gets SIGTERM, and the in-flight agent
6
+ * step turns into a `skipped/interrupted` event — the run ends `paused` while the
7
+ * user is never told. The sweeper cannot see this from row state because
8
+ * `workflow({ background: true })` returns `started` before the step finishes, so
9
+ * the row falls back to `idle` and looks evictable.
10
+ *
11
+ * This module is the decision core plus its thin IO shell: parse a run head
12
+ * record, match it to a row's session file, classify the protection outcome, and
13
+ * enumerate/probe the on-disk run store (`scanBackgroundRuns`/`probeBackgroundRun`).
14
+ * Design: docs/superpowers/specs/2026-10-24-issue-230-warm-host-background-runs-design.md
15
+ */
16
+ import { readdirSync, readFileSync, statSync } from "node:fs";
17
+ import * as os from "node:os";
18
+ import * as path from "node:path";
19
+
20
+ /** Timestamp tolerance for FS mtime granularity and cross-process clock skew
21
+ * when comparing a run's `updatedAt` against the host start time (spec D1). */
22
+ export const CLOCK_EPSILON_MS = 2000;
23
+
24
+ /**
25
+ * @typedef {Object} RunHead
26
+ * @property {string} runId
27
+ * @property {string} status
28
+ * @property {string|null} parentSessionFile legacy records carry none
29
+ * @property {number|null} startedAtMs
30
+ * @property {number|null} updatedAtMs
31
+ * @property {boolean} hasCheckpoint
32
+ */
33
+
34
+ /** @typedef {"protecting"|"paused"|"irrelevant"} RunVerdict */
35
+
36
+ /**
37
+ * Root directory of pi-dynamic-workflows: `$AGENT_BOARD_WORKFLOW_HOME` (explicit
38
+ * override) > `$PI_CODING_AGENT_DIR/workflows` > `<home>/.pi/workflows`.
39
+ * Both `env` and `home` are injectable so callers and tests never depend on the
40
+ * ambient environment or the real homedir.
41
+ * @param {{ env?: Record<string, string|undefined>, home?: string }} [o]
42
+ * @returns {string}
43
+ */
44
+ export function resolveWorkflowHome({ env = process.env, home = os.homedir() } = {}) {
45
+ const expand = (p) => (p.startsWith("~") ? home + p.slice(1) : p);
46
+ const explicit = env.AGENT_BOARD_WORKFLOW_HOME;
47
+ if (typeof explicit === "string" && explicit.length > 0) return expand(explicit);
48
+ const agentDir = env.PI_CODING_AGENT_DIR;
49
+ const base = typeof agentDir === "string" && agentDir.length > 0 ? expand(agentDir) : joinPath(home, ".pi");
50
+ return joinPath(base, "workflows");
51
+ }
52
+
53
+ /**
54
+ * Parse a run head record into the fields the protection decision needs, or
55
+ * `null` when it is not a workflow run. A v2 record nests the run fields under
56
+ * `index` but keeps `summary` (and therefore the checkpoint) as a sibling at the
57
+ * record root; legacy flat records carry `checkpoint` at the root themselves and
58
+ * can never match a row because they have no `parentSessionFile` (spec non-goal:
59
+ * no legacy session matching).
60
+ * Never throws: the input is external, unversioned JSON.
61
+ * @param {unknown} raw parsed JSON
62
+ * @returns {RunHead|null}
63
+ */
64
+ export function parseRunHead(raw) {
65
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
66
+ const record = /** @type {Record<string, any>} */ (raw);
67
+ const source = record.format === "pi-workflow-run-v2" ? record.index : record;
68
+ if (typeof source !== "object" || source === null || Array.isArray(source)) return null;
69
+ if (typeof source.runId !== "string") return null;
70
+ return {
71
+ runId: source.runId,
72
+ status: typeof source.status === "string" ? source.status : "",
73
+ parentSessionFile: typeof source.parentSessionFile === "string" ? source.parentSessionFile : null,
74
+ startedAtMs: toMs(source.startedAt),
75
+ updatedAtMs: toMs(source.updatedAt),
76
+ hasCheckpoint: Boolean(record.summary?.checkpoint ?? source.checkpoint),
77
+ };
78
+ }
79
+
80
+ /**
81
+ * Whether two spellings point at the same session file. win32 compares
82
+ * case-insensitively (the row meta and the workflow record disagree on drive
83
+ * letter and segment casing; they also mix `\` and `/`); POSIX stays
84
+ * case-sensitive. `platform` is injectable because CI only runs Linux, so the
85
+ * win32 branch would otherwise be untested (spec A5).
86
+ * @param {string} a
87
+ * @param {string} b
88
+ * @param {{ platform?: string }} [o]
89
+ * @returns {boolean}
90
+ */
91
+ export function isSameSessionFile(a, b, { platform = process.platform } = {}) {
92
+ if (typeof a !== "string" || typeof b !== "string" || a.length === 0 || b.length === 0) return false;
93
+ const impl = platform === "win32" ? path.win32 : path.posix;
94
+ const na = impl.resolve(a);
95
+ const nb = impl.resolve(b);
96
+ return platform === "win32" ? na.toLowerCase() === nb.toLowerCase() : na === nb;
97
+ }
98
+
99
+ /**
100
+ * Protection verdict for one run against one row (spec D1/D2).
101
+ *
102
+ * Order matters: a run belonging to another session is always irrelevant (a
103
+ * running or paused run of a sibling row must never keep this host alive);
104
+ * `paused` is reported separately because a paused run needs no host at all and
105
+ * only drives the "run was interrupted" notice; a running run protects only when
106
+ * it was updated after the host started, so a stale `running` record left behind
107
+ * by a previous host incarnation cannot exempt the row forever.
108
+ * @param {RunHead|null|undefined} run
109
+ * @param {{ sessionFile: string|null|undefined, hostStartedAt: number|null|undefined }} o
110
+ * @returns {RunVerdict}
111
+ */
112
+ export function classifyRunForRow(run, { sessionFile, hostStartedAt }) {
113
+ if (!run || !run.parentSessionFile) return "irrelevant";
114
+ if (!isSameSessionFile(run.parentSessionFile, sessionFile)) return "irrelevant";
115
+ if (run.status === "paused") return "paused";
116
+ if (run.status !== "running") return "irrelevant";
117
+ if (hostStartedAt == null || run.updatedAtMs == null) return "protecting";
118
+ if (run.updatedAtMs >= hostStartedAt - CLOCK_EPSILON_MS) return "protecting";
119
+ return "irrelevant";
120
+ }
121
+
122
+ /**
123
+ * Strongest verdict across a scanned head list: protecting > paused >
124
+ * irrelevant. Returns the run that produced it so callers can name its runId in
125
+ * a diagnostic or a row notice; `run` is null for "irrelevant".
126
+ * @param {Array<RunHead|null|undefined>} runs
127
+ * @param {{ sessionFile: string|null|undefined, hostStartedAt: number|null|undefined }} o
128
+ * @returns {{ state: RunVerdict, run: RunHead|null }}
129
+ */
130
+ export function classifyRunsForRow(runs, o) {
131
+ let state = /** @type {RunVerdict} */ ("irrelevant");
132
+ let match = null;
133
+ for (const run of Array.isArray(runs) ? runs : []) {
134
+ const verdict = classifyRunForRow(run, o);
135
+ if (verdict === "protecting") return { state: "protecting", run };
136
+ if (verdict === "paused" && state === "irrelevant") {
137
+ state = "paused";
138
+ match = run;
139
+ }
140
+ }
141
+ return { state, run: match };
142
+ }
143
+
144
+ /**
145
+ * @typedef {RunHead & { path: string, mtimeMs: number }} RunHeadWithPath
146
+ */
147
+
148
+ /**
149
+ * Enumerate every run head under `<workflowHome>/projects/<project>/runs/`.
150
+ * Only `*.json` regular files are candidates (upstream keeps `.bak`,
151
+ * `.events.jsonl`, `.log` and `.result-*` siblings next to the head), and
152
+ * `minMtimeMs` drops heads too old to belong to a live host — a prefilter only,
153
+ * the protection verdict still comes from `classifyRunsForRow`.
154
+ *
155
+ * Failure policy (spec D6): an absent store is normal and yields `ok:true`; any
156
+ * incomplete scan yields `ok:false` so the caller logs a `warm_prune_probe_failed`
157
+ * diagnostic instead of silently guessing. An incomplete scan is any unreadable
158
+ * directory or head file, including corrupt JSON — the eviction outcome is the
159
+ * same either way (a run that cannot be read protects nothing), but only
160
+ * `ok:false` marks the coverage as incomplete (it does not disable protection).
161
+ * Heads that were read successfully are still returned and still participate in
162
+ * the protection classification; a run that could not be read simply has no
163
+ * evidence and protects nothing. A head file that parses but is not a run head
164
+ * (`parseRunHead` → null) is not an error: it is simply not a candidate.
165
+ * The store root is stat-ed before the child paths are enumerated because on
166
+ * win32 a child path under a regular file reports `ENOENT` exactly like a
167
+ * missing directory does: a missing `workflowHome` is "no store yet", a
168
+ * `workflowHome` that is not a directory is a read failure.
169
+ * @param {{ workflowHome: string, minMtimeMs?: number }} o
170
+ * @returns {{ ok: boolean, heads: Array<RunHeadWithPath>, error: string|null }}
171
+ */
172
+ export function scanBackgroundRuns({ workflowHome, minMtimeMs = 0 }) {
173
+ const heads = [];
174
+ let error = null;
175
+ const noteError = (message) => {
176
+ error ??= message;
177
+ };
178
+
179
+ let projects;
180
+ try {
181
+ if (!statSync(workflowHome).isDirectory()) {
182
+ return { ok: false, heads: [], error: `workflow home is not a directory: ${workflowHome}` };
183
+ }
184
+ projects = readdirSync(joinPath(workflowHome, "projects"), { withFileTypes: true });
185
+ } catch (e) {
186
+ if (e?.code === "ENOENT") return { ok: true, heads: [], error: null };
187
+ return { ok: false, heads: [], error: errorMessage(e) };
188
+ }
189
+
190
+ for (const project of projects) {
191
+ if (!project.isDirectory()) continue;
192
+ const runsDir = joinPath(workflowHome, "projects", project.name, "runs");
193
+ let entries;
194
+ try {
195
+ entries = readdirSync(runsDir, { withFileTypes: true });
196
+ } catch (e) {
197
+ if (e?.code !== "ENOENT") noteError(`${runsDir}: ${errorMessage(e)}`);
198
+ continue;
199
+ }
200
+ for (const entry of entries) {
201
+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
202
+ const filePath = joinPath(runsDir, entry.name);
203
+ try {
204
+ const mtimeMs = statSync(filePath).mtimeMs;
205
+ if (mtimeMs < minMtimeMs) continue;
206
+ const head = parseRunHead(JSON.parse(readFileSync(filePath, "utf8")));
207
+ if (head) heads.push({ ...head, path: filePath, mtimeMs });
208
+ } catch (e) {
209
+ noteError(`${filePath}: ${errorMessage(e)}`);
210
+ }
211
+ }
212
+ }
213
+
214
+ return { ok: error === null, heads, error };
215
+ }
216
+
217
+ /**
218
+ * Fresh protection probe for one row: the scan prefiltered to runs that could
219
+ * have been updated by this host incarnation, classified against the row's
220
+ * session file. Each field answers one question and is filled independently
221
+ * (design §5.1: a running/paused split): `running` is the run that must keep the
222
+ * host alive (spec D1), `paused` is the run whose interruption the reconcile
223
+ * pass announces (spec D2). They coexist because one session may hold an older
224
+ * paused run while a new one is running, and each consumer reads one field.
225
+ * `ok:false` only means the store could not be read (spec D6).
226
+ * @param {{ sessionFile: string|null, hostStartedAt: number|null, workflowHome: string }} o
227
+ * @returns {{ ok: boolean, running: RunHeadWithPath|null, paused: RunHeadWithPath|null, error: string|null }}
228
+ */
229
+ export function probeBackgroundRun({ sessionFile, hostStartedAt, workflowHome }) {
230
+ const minMtimeMs = hostStartedAt == null ? 0 : hostStartedAt - CLOCK_EPSILON_MS;
231
+ const scan = scanBackgroundRuns({ workflowHome, minMtimeMs });
232
+ if (!scan.ok) return { ok: false, running: null, paused: null, error: scan.error };
233
+ const verdict = classifyRunsForRow(scan.heads, { sessionFile, hostStartedAt });
234
+ const running = verdict.state === "protecting" ? verdict.run : null;
235
+ // Newest paused run wins, because it is the one most likely to be the run the
236
+ // just-ended host left behind; `path` only breaks ties deterministically.
237
+ const paused = scan.heads
238
+ .filter((head) => classifyRunForRow(head, { sessionFile, hostStartedAt }) === "paused")
239
+ .sort((a, b) => (b.updatedAtMs ?? 0) - (a.updatedAtMs ?? 0) || a.path.localeCompare(b.path))[0] ?? null;
240
+ return { ok: true, running, paused, error: scan.error };
241
+ }
242
+
243
+ /**
244
+ * Join segments with the separator style of the base path. The ambient
245
+ * `path.join` uses the host separator, which would turn POSIX-style injected
246
+ * inputs (tests, Linux CI) into backslash paths when the suite runs on Windows,
247
+ * so the style is read from the base instead of the platform.
248
+ * @param {string} base
249
+ * @param {...string} parts
250
+ * @returns {string}
251
+ */
252
+ function joinPath(base, ...parts) {
253
+ const impl = /^[A-Za-z]:/.test(base) || base.includes("\\") ? path.win32 : path.posix;
254
+ return impl.join(base, ...parts);
255
+ }
256
+
257
+ /**
258
+ * @param {unknown} e
259
+ * @returns {string}
260
+ */
261
+ function errorMessage(e) {
262
+ return e instanceof Error ? e.message : String(e);
263
+ }
264
+
265
+ /**
266
+ * @param {unknown} value
267
+ * @returns {number|null}
268
+ */
269
+ function toMs(value) {
270
+ if (typeof value !== "string") return null;
271
+ const ms = Date.parse(value);
272
+ return Number.isFinite(ms) ? ms : null;
273
+ }