@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
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Cross-platform process identity probe (issue #217) and start-token reader
3
+ * (issue #238).
4
+ *
5
+ * The probe produces the two corroborating signals — process creation time and
6
+ * command line — that `classifyUnverifiableProcess` judges when a recorded
7
+ * start token is missing. `readProcessStartToken` produces the comparable token
8
+ * itself: linux reads `/proc` and win32 converts the probe's creation time into
9
+ * a `ct:<ms>` token. Pure parsers are exported for exhaustive unit tests;
10
+ * `readProcessIdentityProbe` is the only I/O layer (one async `execFile` per
11
+ * pid, never throwing).
12
+ *
13
+ * `readProcessStartToken` has no darwin path on purpose: `ps` reports elapsed
14
+ * time at second resolution, so two reads of one process drift by up to ~1 s
15
+ * and a token comparison would misclassify a live process as `foreign`.
16
+ * Returning `null` keeps callers on the "unverifiable" path instead of
17
+ * guessing. The probe itself stays off linux: the `/proc` token already
18
+ * identifies processes there, so probing would only add latency.
19
+ */
20
+ import { execFile } from "node:child_process";
21
+ import { captureStartToken } from "./pid.mjs";
22
+
23
+ /** Hard cap on one probe: a hung PowerShell/ps must not stall recovery. */
24
+ export const PROBE_TIMEOUT_MS = 3_000;
25
+
26
+ /** Cap on captured stdout — a command line is small; anything larger is junk. */
27
+ const PROBE_MAX_BUFFER = 64 * 1024;
28
+
29
+ /**
30
+ * Format an absolute creation time as the comparable `ct:` identity token
31
+ * (issue #238): two reads of the same process yield the same token regardless
32
+ * of when they happen. Only positive safe integers format — anything else
33
+ * (missing creation time, a fractional or out-of-range value, a coerced
34
+ * string) would produce a token that can never match a recorded one.
35
+ * @param {number} creationTimeMs
36
+ * @returns {string|null}
37
+ */
38
+ export function creationTimeToken(creationTimeMs) {
39
+ if (!Number.isSafeInteger(creationTimeMs) || creationTimeMs <= 0) return null;
40
+ return `ct:${creationTimeMs}`;
41
+ }
42
+
43
+ /**
44
+ * Read the comparable start token for a process (issue #238): the token is
45
+ * recorded next to a lease and compared later to tell "same process" from
46
+ * "reused pid".
47
+ *
48
+ * - linux: `captureStartToken(pid)` — `/proc/<pid>/stat` starttime.
49
+ * - win32: probe → `creationTimeToken(creationTimeMs)` — CIM creation time is
50
+ * millisecond-resolution, so two reads of one process are strictly equal.
51
+ * - anything else, including darwin: `null`, and the probe is never called.
52
+ *
53
+ * A pid that is not a positive safe integer yields `null` before any I/O; a
54
+ * probe rejection or unusable result also yields `null` (unverifiable, never
55
+ * "foreign").
56
+ *
57
+ * @param {number} pid
58
+ * @param {{ platform?: string, probe?: typeof readProcessIdentityProbe }} [opts]
59
+ * @returns {Promise<string|null>}
60
+ */
61
+ export async function readProcessStartToken(pid, {
62
+ platform = process.platform,
63
+ probe = readProcessIdentityProbe,
64
+ } = {}) {
65
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null;
66
+ if (platform === "linux") return captureStartToken(pid);
67
+ if (platform !== "win32") return null;
68
+ try {
69
+ const observed = await probe(pid);
70
+ return observed ? creationTimeToken(observed.creationTimeMs) : null;
71
+ } catch {
72
+ return null;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Parse an epoch-milliseconds value from CIM JSON output. Accepts decimal
78
+ * digits only: PowerShell can hand back an empty string or a negative number
79
+ * for protected processes, neither of which is a usable creation time.
80
+ * @param {string} text
81
+ * @returns {number|null}
82
+ */
83
+ export function parseUnixMillis(text) {
84
+ const trimmed = String(text ?? "").trim();
85
+ if (!/^\d+$/.test(trimmed)) return null;
86
+ const millis = Number(trimmed);
87
+ return Number.isSafeInteger(millis) && millis > 0 ? millis : null;
88
+ }
89
+
90
+ /**
91
+ * Parse the compressed CIM object emitted for a Windows process:
92
+ * `{"creation":<unix ms>|null,"cmd":"<command line>"|null}`. Malformed JSON or
93
+ * a non-object payload yields `null` (the judgment layer reads that as
94
+ * `unknown`, which is always safe).
95
+ * @param {string} text
96
+ * @returns {{creationTimeMs:number|null, commandLine:string|null}|null}
97
+ */
98
+ export function parseProbeJson(text) {
99
+ if (typeof text !== "string") return null;
100
+ const trimmed = text.trim();
101
+ if (!trimmed) return null;
102
+ /** @type {any} */ let parsed;
103
+ try {
104
+ parsed = JSON.parse(trimmed);
105
+ } catch {
106
+ return null;
107
+ }
108
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
109
+ return {
110
+ creationTimeMs: parseUnixMillis(parsed.creation),
111
+ commandLine: typeof parsed.cmd === "string" && parsed.cmd.trim() ? parsed.cmd : null,
112
+ };
113
+ }
114
+
115
+ /** `[DD-]HH:MM:SS` (ps drops leading units it does not need). */
116
+ const PS_ELAPSED_PATTERN = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/;
117
+
118
+ /**
119
+ * Parse a POSIX `ps` elapsed-time field into milliseconds. Handles the three
120
+ * shapes `ps -o etime=` emits: `MM:SS`, `HH:MM:SS`, and `D-HH:MM:SS`.
121
+ * @param {string} text
122
+ * @returns {number|null}
123
+ */
124
+ export function parsePsElapsedMs(text) {
125
+ const match = PS_ELAPSED_PATTERN.exec(String(text ?? "").trim());
126
+ if (!match) return null;
127
+ const days = match[1] == null ? 0 : Number(match[1]);
128
+ const hours = match[2] == null ? 0 : Number(match[2]);
129
+ const minutes = Number(match[3]);
130
+ const seconds = Number(match[4]);
131
+ if (minutes > 59 || seconds > 59) return null;
132
+ return ((days * 24 + hours) * 3600 + minutes * 60 + seconds) * 1000;
133
+ }
134
+
135
+ /**
136
+ * Parse one `ps -p <pid> -o etime=,command=` line: the first whitespace-
137
+ * separated token is the elapsed time, everything after it is the command.
138
+ * `ps` reports age, not creation time, so callers pass the clock reading.
139
+ * @param {string} text
140
+ * @param {number} nowMs Epoch ms at which the probe output was read.
141
+ * @returns {{creationTimeMs:number|null, commandLine:string|null}|null}
142
+ */
143
+ export function parsePsProbeLine(text, nowMs) {
144
+ if (typeof text !== "string") return null;
145
+ const trimmed = text.trim();
146
+ if (!trimmed) return null;
147
+ const split = trimmed.search(/\s/);
148
+ const elapsedText = split === -1 ? trimmed : trimmed.slice(0, split);
149
+ const commandLine = split === -1 ? "" : trimmed.slice(split).trim();
150
+ const elapsedMs = parsePsElapsedMs(elapsedText);
151
+ if (elapsedMs == null) return null;
152
+ return {
153
+ creationTimeMs: nowMs - elapsedMs,
154
+ commandLine: commandLine || null,
155
+ };
156
+ }
157
+
158
+ /**
159
+ * Windows CIM query: one round trip returns creation time (converted to Unix
160
+ * milliseconds in PowerShell so the parent needs no date parsing) and the
161
+ * command line. `-ErrorAction SilentlyContinue` keeps a vanished pid from
162
+ * turning into a non-zero exit; the empty result is handled as "unavailable".
163
+ * @param {number} pid
164
+ * @returns {string}
165
+ */
166
+ function windowsProbeScript(pid) {
167
+ return "$p = Get-CimInstance Win32_Process -Filter \"ProcessId=" + pid + "\" -ErrorAction SilentlyContinue; "
168
+ + "if ($p) { [pscustomobject]@{creation=[long]([datetimeoffset]$p.CreationDate).ToUnixTimeMilliseconds(); cmd=$p.CommandLine} | ConvertTo-Json -Compress }";
169
+ }
170
+
171
+ /**
172
+ * Resolve the platform-specific probe command. Platforms without a probe
173
+ * (`linux` and everything else) and invalid pids return `null`, so callers
174
+ * never spawn anything for them.
175
+ * @param {string} platform
176
+ * @param {number} pid
177
+ * @returns {{command:string, args:string[]}|null}
178
+ */
179
+ export function resolveProbeCommand(platform, pid) {
180
+ if (!Number.isSafeInteger(pid) || pid <= 0) return null;
181
+ if (platform === "win32") {
182
+ return {
183
+ command: "powershell.exe",
184
+ args: ["-NoProfile", "-NonInteractive", "-Command", windowsProbeScript(pid)],
185
+ };
186
+ }
187
+ if (platform === "darwin") {
188
+ return { command: "ps", args: ["-p", String(pid), "-o", "etime=,command="] };
189
+ }
190
+ return null;
191
+ }
192
+
193
+ /**
194
+ * Read `{ creationTimeMs, commandLine }` for `pid`, or `null` when the process
195
+ * cannot be observed (unsupported platform, invalid pid, non-zero exit,
196
+ * timeout, or empty output). `null` means "unverifiable", never "foreign".
197
+ *
198
+ * `execFileFn` is injectable for tests; the default is Node's async
199
+ * `execFile`. `windowsHide` mirrors `launchRun`'s detached spawn (issue #49):
200
+ * without it a console window flashes on Windows 11 25H2.
201
+ *
202
+ * @param {number} pid
203
+ * @param {{ platform?: string, execFileFn?: typeof execFile, timeoutMs?: number, nowMs?: () => number }} [opts]
204
+ * @returns {Promise<{creationTimeMs:number|null, commandLine:string|null}|null>}
205
+ */
206
+ export async function readProcessIdentityProbe(pid, {
207
+ platform = process.platform,
208
+ execFileFn = execFile,
209
+ timeoutMs = PROBE_TIMEOUT_MS,
210
+ nowMs = Date.now,
211
+ } = {}) {
212
+ const resolved = resolveProbeCommand(platform, pid);
213
+ if (!resolved) return null;
214
+ return new Promise((resolve) => {
215
+ execFileFn(resolved.command, resolved.args, { timeout: timeoutMs, windowsHide: true, maxBuffer: PROBE_MAX_BUFFER }, (error, stdout) => {
216
+ if (error) {
217
+ resolve(null);
218
+ return;
219
+ }
220
+ const text = String(stdout ?? "").trim();
221
+ if (!text) {
222
+ resolve(null);
223
+ return;
224
+ }
225
+ resolve(platform === "win32" ? parseProbeJson(text) : parsePsProbeLine(text, nowMs()));
226
+ });
227
+ });
228
+ }
@@ -115,7 +115,11 @@ export const PATCHABLE_FIELDS = Object.freeze({
115
115
  // through patch_fields (controller ruling R1 — plan oversight, Task 3).
116
116
  "job-runner": Object.freeze({ state: Object.freeze(["review", "evidenceSummary", "summary", "latestAssistantPreview"]), status: Object.freeze(["evidenceSummary", "summary", "latestAssistantPreview"]) }),
117
117
  "state-runner": Object.freeze({ state: Object.freeze(["review", "evidenceSummary"]), status: Object.freeze(["evidenceSummary"]) }),
118
- "service": Object.freeze({ state: Object.freeze(["lastVisitedAt"]), status: Object.freeze([]) }),
118
+ // summary (issue #230): a warm host that died with a paused background
119
+ // workflow run leaves the row silent — reconcile announces the interruption
120
+ // by patching summary. lastVisitedAt (markVisited) is the visit-recency
121
+ // stamp. Both are metadata mirrors; semantic fields keep their own kinds.
122
+ "service": Object.freeze({ state: Object.freeze(["lastVisitedAt", "summary"]), status: Object.freeze([]) }),
119
123
  // lastVisitedAt (markVisited): visiting is a user action, so it routes as
120
124
  // dashboard-user — the manual fence only fences non-human sources, and
121
125
  // legacy stamped lastVisitedAt unconditionally (visit-recency tracking
@@ -189,6 +189,7 @@ export const GROUP_LABELS = {
189
189
  * @property {number} toolCount
190
190
  * @property {number} [eventCount]
191
191
  * @property {number|null} [lastEventAt]
192
+ * @property {number} [updatedAt] In-memory foreground rebuild freshness (issue #225); not persisted on run status files.
192
193
  * @property {EvidenceUsage|null} [usage]
193
194
  * @property {string|null} [stallReason]
194
195
  * @property {ReviewSummary|null} [evidenceSummary]
@@ -45,16 +45,18 @@ export function canAutoDrain(row) {
45
45
  * idle = host alive && !busy && no attached clients && not keepViewId.
46
46
  * graceMs exempts freshly started hosts (attach handoff race: ensureHost has
47
47
  * started a host but the client has not connected yet).
48
+ * isProtected is injected by the caller (this pure function never reads disk):
49
+ * a host running a background workflow is exempt from both eviction branches.
48
50
  * TTL eviction runs first; survivors over maxWarm are evicted oldest-first by
49
51
  * idleSince = max(state.lastActivityAt, host.startedAt) || meta.updatedAt (host-level
50
52
  * idle counts from host start, so a stale lastActivityAt from a previous host
51
53
  * incarnation never makes a fresh host look idle longer than it has been up).
52
54
  *
53
55
  * @param {Array<import("./store.mjs").Row>} rows
54
- * @param {{ now: number, maxWarm: number, ttlMs: number, graceMs?: number, keepViewId?: string|null }} o
56
+ * @param {{ now: number, maxWarm: number, ttlMs: number, graceMs?: number, keepViewId?: string|null, isProtected?: ((row: import("./store.mjs").Row) => boolean)|null }} o
55
57
  * @returns {{ ttlEvicted: string[], excessEvicted: string[] }} viewIds, ttl group first
56
58
  */
57
- export function selectIdleHostsToEvict(rows, { now, maxWarm, ttlMs, graceMs = 0, keepViewId = null }) {
59
+ export function selectIdleHostsToEvict(rows, { now, maxWarm, ttlMs, graceMs = 0, keepViewId = null, isProtected = null }) {
58
60
  // Both-zero = eviction disabled entirely. Callers (service.pruneWarmHosts)
59
61
  // may additionally early-return for the same reason.
60
62
  if (maxWarm === 0 && ttlMs === 0) return { ttlEvicted: [], excessEvicted: [] };
@@ -63,6 +65,9 @@ export function selectIdleHostsToEvict(rows, { now, maxWarm, ttlMs, graceMs = 0,
63
65
  if (keepViewId != null && row.meta.id === keepViewId) continue;
64
66
  if (!row.hostAlive) continue;
65
67
  if (isAgentBusy(row)) continue;
68
+ // Background-run protection (issue #230): a host executing a background
69
+ // workflow still counts as busy even though the assistant turn ended.
70
+ if (isProtected && isProtected(row)) continue;
66
71
  if ((row.host?.attachedClients ?? 0) !== 0) continue;
67
72
  const startedAt = row.host?.startedAt;
68
73
  if (graceMs > 0 && startedAt != null && now - startedAt < graceMs) continue;