@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
@@ -26,8 +26,11 @@
26
26
  import { createConnection } from "node:net";
27
27
  import { existsSync, readFileSync } from "node:fs";
28
28
  import { fileURLToPath } from "node:url";
29
+ import { appendDiagnosticOnce } from "./diagnostics.mjs";
29
30
  import { newRunId } from "./ids.mjs";
30
31
  import { launchCoordinator } from "./launch.mjs";
32
+ import { isAlive } from "./pid.mjs";
33
+ import { readProcessStartToken } from "./process-identity-probe.mjs";
31
34
  import * as P from "./paths.mjs";
32
35
  import { COORDINATOR_PROTOCOL_VERSION } from "./coordinator-protocol.mjs";
33
36
 
@@ -42,6 +45,7 @@ const COMMAND_TIMEOUT_MS = 5_000;
42
45
 
43
46
  /** @typedef {{ status: "applied"|"rejected", reason: string|null, materializedRevision: number }} StateCommandResult */
44
47
  /** @typedef {{ ok: boolean, instanceId?: string, pid?: number|null, error?: "coordinator_disabled"|"coordinator_unavailable"|"coordinator_stale_protocol" }} EnsureResult */
48
+ /** @typedef {{ token: string|null, pid: number|null, instanceId: string|null, startToken: string|null }} LeaseRecord */
45
49
 
46
50
  /**
47
51
  * Whether the coordinator is switched off for this process (tests/legacy
@@ -117,48 +121,323 @@ function probeOnce(socketPath, connect, timeoutMs) {
117
121
  }
118
122
 
119
123
  /**
120
- * Read the coordinator lease's owner.json and return the owning pid. The
124
+ * First argument that is a non-empty string, else null. Only a non-empty
125
+ * string identifies a process instance — "" and non-strings are treated as
126
+ * "field missing" so a malformed record can never read as a verified identity.
127
+ * @param {...unknown} values
128
+ * @returns {string|null}
129
+ */
130
+ function firstNonEmptyString(...values) {
131
+ for (const value of values) {
132
+ if (typeof value === "string" && value.length > 0) return value;
133
+ }
134
+ return null;
135
+ }
136
+
137
+ /**
138
+ * Read the coordinator lease's owner.json in a decision-friendly shape. The
121
139
  * lease is written by whichever process owns the "_coordinator" lock, so it
122
- * identifies the live coordinator even when its pong predates the pid field.
140
+ * identifies the live coordinator — but its pid alone is NOT proof that the
141
+ * lease owner is the endpoint that answered our ping (issue #239): the pid may
142
+ * have been reused by an unrelated process. `instanceId` (written since issue
143
+ * #239, same value as the coordinator's pong) is what
144
+ * `judgeReplacementTarget` compares to close that gap.
145
+ *
146
+ * Tolerates every historical record shape: the lock layer passes `identity`
147
+ * through verbatim, so records written before #239 have no `instanceId` and
148
+ * non-Linux records carry `startToken: null`. `instanceId` is read from
149
+ * `identity` first, then from the top level (compatibility path for a future
150
+ * shape).
123
151
  * @param {string} root
124
- * @returns {number|null}
152
+ * @returns {LeaseRecord|null} null when the lease is missing, unparsable, or
153
+ * not a JSON object
125
154
  */
126
- function readCoordinatorLeasePid(root) {
155
+ export function readCoordinatorLeaseRecord(root) {
127
156
  try {
128
157
  const lockPath = P.viewLockPath(root, "_coordinator", "state-coordinator");
129
158
  const owner = JSON.parse(readFileSync(`${lockPath}/owner.json`, "utf8"));
130
- const pid = Number(owner?.identity?.pid ?? owner?.pid ?? 0);
131
- return Number.isFinite(pid) && pid > 0 ? pid : null;
159
+ if (!owner || typeof owner !== "object" || Array.isArray(owner)) return null;
160
+ const identity = owner.identity;
161
+ const pid = Number(identity?.pid ?? owner.pid);
162
+ return {
163
+ token: typeof owner.token === "string" ? owner.token : null,
164
+ pid: Number.isFinite(pid) && pid > 0 ? pid : null,
165
+ instanceId: firstNonEmptyString(identity?.instanceId, owner.instanceId),
166
+ startToken: firstNonEmptyString(identity?.startToken),
167
+ };
132
168
  } catch {
133
169
  return null;
134
170
  }
135
171
  }
136
172
 
137
- /** Grace window for a SIGTERMed stale coordinator to unlink its socket. */
173
+ /**
174
+ * Decide whether the lease owner may be signalled, given the lease record and
175
+ * the instanceId from the pong we just received (issue #239). Pure: no fs, no
176
+ * process, no platform checks — the caller injects the legacy live-token read.
177
+ *
178
+ * Decision order (first match wins):
179
+ * 1. unreadable record / invalid pid → skip("lease_unreadable")
180
+ * 2. recorded instanceId present → equal: signal, else skip("lease_owner_mismatch")
181
+ * 3. legacy record without startToken → skip("identity_unverified")
182
+ * 4. currentStartToken not a usable
183
+ * string (unreadable, or a missed
184
+ * await handing us a Promise) → skip("identity_unverified")
185
+ * 5. startToken differs → skip("pid_reused")
186
+ * 6. otherwise → signal
187
+ *
188
+ * Empty-string instanceId/startToken count as missing, so a malformed record
189
+ * stays on the skip side instead of matching an empty probe value.
190
+ * @param {{ recorded: LeaseRecord|null, probedInstanceId: string, currentStartToken?: string|null }} args
191
+ * @returns {{ action: "signal" } | { action: "skip", reason: "lease_unreadable"|"lease_owner_mismatch"|"pid_reused"|"identity_unverified" }}
192
+ */
193
+ export function judgeReplacementTarget({ recorded, probedInstanceId, currentStartToken = null }) {
194
+ if (!recorded || typeof recorded.pid !== "number" || !Number.isFinite(recorded.pid) || recorded.pid <= 0) {
195
+ return { action: "skip", reason: "lease_unreadable" };
196
+ }
197
+ const recordedInstanceId = firstNonEmptyString(recorded.instanceId);
198
+ if (recordedInstanceId !== null) {
199
+ return recordedInstanceId === probedInstanceId
200
+ ? { action: "signal" }
201
+ : { action: "skip", reason: "lease_owner_mismatch" };
202
+ }
203
+ const recordedStartToken = firstNonEmptyString(recorded.startToken);
204
+ if (recordedStartToken === null) return { action: "skip", reason: "identity_unverified" };
205
+ if (typeof currentStartToken !== "string" || currentStartToken.length === 0) {
206
+ return { action: "skip", reason: "identity_unverified" };
207
+ }
208
+ if (currentStartToken !== recordedStartToken) return { action: "skip", reason: "pid_reused" };
209
+ return { action: "signal" };
210
+ }
211
+
212
+ /**
213
+ * Process-local dedup keys for the replacement-skip diagnostic (issue #239 D5).
214
+ * A stale coordinator that cannot be replaced keeps failing on every
215
+ * `sendStateCommand` ensure, and `appendDiagnosticOnce` tails the whole JSONL
216
+ * file (`readJsonlTail` → `readJsonl`), so a repeat must return before any disk
217
+ * access. One entry per root × reason × identity pair for the process lifetime;
218
+ * the key space is small and bounded by the board roots in use.
219
+ * @type {Set<string>}
220
+ */
221
+ const reportedReplacementSkips = new Set();
222
+
223
+ /**
224
+ * Record that the coordinator replacement was deliberately skipped (issue #239
225
+ * D5). `reason` is one of the spec's `SkipReason` values. Best-effort by
226
+ * contract: the skip paths run inside `ensureCoordinator`, which
227
+ * `sendStateCommand` does not wrap, so every error here (malformed args,
228
+ * unreadable/unwritable JSONL) is swallowed instead of thrown.
229
+ *
230
+ * Two-layer dedup: this process-local Set filters the hot path without touching
231
+ * disk, then `appendDiagnosticOnce` dedupes across processes/restarts. The root
232
+ * existence check comes before the append because appending creates parent
233
+ * directories — a diagnostic must never resurrect a deleted root (issue #241
234
+ * class of leftovers). The key is recorded even when the write is skipped, so a
235
+ * state that was already handled never probes the disk again.
236
+ * @param {string} root
237
+ * @param {{ reason: string, recordedInstanceId?: string|null, probedInstanceId: string }} details
238
+ * @returns {void}
239
+ */
240
+ function reportReplacementSkip(root, details) {
241
+ try {
242
+ const { reason, recordedInstanceId = null, probedInstanceId } = details;
243
+ const key = `${root}|${reason}|${recordedInstanceId ?? "null"}|${probedInstanceId}`;
244
+ if (reportedReplacementSkips.has(key)) return;
245
+ reportedReplacementSkips.add(key);
246
+ if (!existsSync(root)) return;
247
+ appendDiagnosticOnce(root, "_coordinator", {
248
+ source: "coordinator-client",
249
+ level: "warn",
250
+ code: "coordinator_replacement_skipped",
251
+ message: `coordinator replacement skipped: ${reason}`,
252
+ details: { reason, recordedInstanceId: recordedInstanceId ?? null, probedInstanceId },
253
+ }, { match: ["reason", "recordedInstanceId", "probedInstanceId"] });
254
+ } catch {
255
+ // Diagnostics are best-effort: a failed write must never break the caller.
256
+ }
257
+ }
258
+
259
+ /** Grace window for a SIGTERMed stale coordinator to exit (issue #239 D4). */
138
260
  const REPLACE_TIMEOUT_MS = 3_000;
261
+ /** Liveness poll interval while waiting for a SIGTERMed coordinator to exit. */
139
262
  const REPLACE_POLL_MS = 50;
140
263
 
264
+ /** @typedef {{ replaced: true } | { replaced: false, reason: SkipReason }} ReplaceOutcome */
265
+ /** @typedef {"lease_unreadable"|"lease_owner_mismatch"|"pid_reused"|"identity_unverified"|"lease_changed"|"instance_unresponsive"|"replacement_raced"|"replace_timeout"} SkipReason */
266
+
267
+ /**
268
+ * Await `ms` with a ref'd timer, deliberately NOT unref'd (issue #239 D4).
269
+ * `ensureCoordinator` is awaited by detached one-shot callers whose send point
270
+ * holds no other ref'd handle; an unref'd sleep lets such a process exit with
271
+ * code 0 mid-wait, so `ensureCoordinator` never returns, the replacement is
272
+ * never spawned and the queued state command is silently dropped. The wait is
273
+ * bounded by `replaceTimeoutMs` (≤3s), so a ref'd timer cannot keep a caller
274
+ * alive beyond the replacement budget.
275
+ * @param {number} ms
276
+ * @returns {Promise<void>}
277
+ */
278
+ function replaceSleep(ms) {
279
+ return new Promise((resolve) => {
280
+ setTimeout(resolve, ms);
281
+ });
282
+ }
283
+
284
+ /**
285
+ * Whether a lease record names a pid that may be signalled. Mirrors the
286
+ * `lease_unreadable` boundary of `judgeReplacementTarget` for the records read
287
+ * outside the decision itself.
288
+ * @param {LeaseRecord|null} record
289
+ * @returns {boolean}
290
+ */
291
+ function hasUsableLeasePid(record) {
292
+ return Boolean(record)
293
+ && typeof record.pid === "number"
294
+ && Number.isFinite(record.pid)
295
+ && record.pid > 0;
296
+ }
297
+
141
298
  /**
142
- * Terminate a stale-protocol coordinator (issue #108) and wait for its socket
143
- * to disappear so a fresh instance can bind. SIGTERM triggers the
144
- * coordinator's graceful shutdown (socket unlink + lease release); its crash
145
- * safety (fsync-before-materialize journal + boot replay) makes the kill safe
146
- * even mid-command — an in-flight reply is the documented ambiguous outcome.
299
+ * Terminate a stale-protocol coordinator and wait for it to exit (issue #108),
300
+ * with the signal gated on a proven lease identity (issue #239). SIGTERM
301
+ * triggers the coordinator's graceful shutdown; its crash safety
302
+ * (fsync-before-materialize journal + boot replay) makes the kill safe even
303
+ * mid-command — an in-flight reply is the documented ambiguous outcome.
304
+ *
305
+ * Identity contract: the pong that proved the endpoint stale came from one
306
+ * process, while `owner.json` names the lease owner. They are the same process
307
+ * only when the recorded `identity.instanceId` matches `expectedInstanceId`
308
+ * (D2) — a mismatch or an unverifiable legacy record never signals. Before
309
+ * signalling, the endpoint is re-probed and the lease re-read (D3), so a
310
+ * takeover or lease handover that happened between judging and signalling wins
311
+ * over the kill. After the signal the caller waits, bounded by
312
+ * `replaceTimeoutMs`, for the pid to exit (D4): a successor must not be spawned
313
+ * while the old owner can still hold the lease.
314
+ *
315
+ * Every skip return reports through `reportSkip` (D5) and resolves a
316
+ * `ReplaceOutcome`. The function never throws: the diagnostic writer and the
317
+ * `kill` call are both wrapped (the latter routes ESRCH to "already replaced"
318
+ * and other errors into wait-for-exit).
147
319
  * @param {string} root
148
320
  * @param {string} socketPath
149
- * @returns {Promise<boolean>} whether the socket is gone (replacement can proceed)
321
+ * @param {string} expectedInstanceId `instanceId` from the pong that was judged
322
+ * stale — the only identity whose process may be signalled
323
+ * @param {{
324
+ * probe?: (socketPath: string, connect: (path: string) => import("node:net").Socket, timeoutMs: number) => Promise<{instanceId: string, protocolVersion: number}|null>,
325
+ * connect?: (path: string) => import("node:net").Socket,
326
+ * probeTimeoutMs?: number,
327
+ * readLease?: (root: string) => LeaseRecord|null,
328
+ * kill?: (pid: number, signal: string) => void,
329
+ * isAlive?: (pid: number) => boolean,
330
+ * readStartToken?: (pid: number) => Promise<string|null>,
331
+ * clock?: () => number,
332
+ * sleep?: (ms: number) => Promise<void>,
333
+ * replaceTimeoutMs?: number,
334
+ * reportSkip?: (details: { reason: SkipReason, recordedInstanceId: string|null, probedInstanceId: string }) => void,
335
+ * }} [opts]
336
+ * @returns {Promise<ReplaceOutcome>}
150
337
  */
151
- async function replaceStaleCoordinator(root, socketPath) {
152
- const pid = readCoordinatorLeasePid(root);
153
- if (pid != null) {
154
- try { process.kill(pid, "SIGTERM"); } catch { /* already gone */ }
338
+ export async function replaceStaleCoordinator(root, socketPath, expectedInstanceId, opts = {}) {
339
+ const connect = opts.connect ?? createConnection;
340
+ const probeTimeoutMs = opts.probeTimeoutMs ?? PROBE_TIMEOUT_MS;
341
+ const probe = opts.probe ?? probeOnce;
342
+ const readLease = opts.readLease ?? readCoordinatorLeaseRecord;
343
+ const kill = opts.kill ?? process.kill;
344
+ const isAliveFn = opts.isAlive ?? isAlive;
345
+ const readStartToken = opts.readStartToken ?? readProcessStartToken;
346
+ const clock = opts.clock ?? Date.now;
347
+ const sleep = opts.sleep ?? replaceSleep;
348
+ const replaceTimeoutMs = opts.replaceTimeoutMs ?? REPLACE_TIMEOUT_MS;
349
+ const reportSkip = opts.reportSkip ?? ((details) => reportReplacementSkip(root, details));
350
+
351
+ const recorded = readLease(root);
352
+ const recordedInstanceId = firstNonEmptyString(recorded?.instanceId);
353
+ /**
354
+ * Report a deliberate skip and resolve the matching outcome. Best-effort by
355
+ * contract: a throwing writer must never escape into `ensureCoordinator`,
356
+ * which does not wrap this call.
357
+ * @param {SkipReason} reason
358
+ * @param {string|null} [instanceId] lease-owner instance at decision time
359
+ * @returns {ReplaceOutcome}
360
+ */
361
+ const skip = (reason, instanceId = recordedInstanceId) => {
362
+ try {
363
+ reportSkip({
364
+ reason,
365
+ recordedInstanceId: instanceId,
366
+ probedInstanceId: expectedInstanceId,
367
+ });
368
+ } catch {
369
+ // Diagnostics are best-effort: a failed write never changes the outcome.
370
+ }
371
+ return { replaced: false, reason };
372
+ };
373
+
374
+ // Legacy records (pre-#239) carry no instanceId; on Linux the live /proc
375
+ // start token is then the only proof that the lease pid is still the process
376
+ // the endpoint served (D6 / J3). The read is async by contract: an injected
377
+ // implementation returning a Promise that is not awaited would compare as
378
+ // unequal, so the judge normalizes a non-string token to
379
+ // `identity_unverified` rather than `pid_reused`.
380
+ const currentStartToken = recordedInstanceId === null && firstNonEmptyString(recorded?.startToken) !== null
381
+ ? await readStartToken(/** @type {LeaseRecord} */ (recorded).pid)
382
+ : null;
383
+
384
+ const verdict = judgeReplacementTarget({ recorded, probedInstanceId: expectedInstanceId, currentStartToken });
385
+ if (verdict.action === "skip") return skip(verdict.reason);
386
+ const target = /** @type {LeaseRecord} */ (recorded);
387
+ const pid = /** @type {number} */ (target.pid);
388
+
389
+ // D3 step 1: re-probe the endpoint. A pong proves the instance that was
390
+ // judged stale is still serving, so its pid cannot have been reused yet.
391
+ // A DIFFERENT instance means the replacement raced with another client: a
392
+ // current-protocol instance already took over (nothing left to replace — the
393
+ // caller may continue), an old-protocol one must not be killed by us.
394
+ const reprobed = await probe(socketPath, connect, probeTimeoutMs);
395
+ if (reprobed && reprobed.instanceId !== expectedInstanceId) {
396
+ if (reprobed.protocolVersion >= COORDINATOR_PROTOCOL_VERSION) return { replaced: true };
397
+ return skip("replacement_raced");
155
398
  }
156
- const deadline = Date.now() + REPLACE_TIMEOUT_MS;
157
- while (Date.now() < deadline) {
158
- if (!existsSync(socketPath)) return true;
159
- await new Promise((r) => setTimeout(r, REPLACE_POLL_MS));
399
+ if (!reprobed) {
400
+ // No valid pong within the timeout is NOT proof the process is gone.
401
+ // Re-read the lease: no usable record means no evidence to signal, a
402
+ // live owner is a slow instance we must not race, and a dead owner lets
403
+ // the next launch take the lease through the normal reclaim path.
404
+ const fresh = readLease(root);
405
+ if (!hasUsableLeasePid(fresh)) return skip("lease_unreadable", null);
406
+ const freshRecord = /** @type {LeaseRecord} */ (fresh);
407
+ if (isAliveFn(/** @type {number} */ (freshRecord.pid))) {
408
+ return skip("instance_unresponsive", firstNonEmptyString(freshRecord.instanceId));
409
+ }
410
+ return { replaced: true };
411
+ }
412
+
413
+ // D3 step 2: the lease must still describe the owner we judged. A changed
414
+ // token or instanceId means another coordinator (or a recovery) owns the
415
+ // lease now — signalling the old pid could hit an unrelated process.
416
+ const confirmed = readLease(root);
417
+ if (!confirmed || confirmed.token !== target.token || firstNonEmptyString(confirmed.instanceId) !== recordedInstanceId) {
418
+ return skip("lease_changed");
419
+ }
420
+
421
+ // D4: the last fallible system call. ESRCH means the target exited between
422
+ // the checks — already replaced. EPERM and anything else leave the target
423
+ // possibly alive, so fail closed into wait-for-exit below.
424
+ try {
425
+ kill(pid, "SIGTERM");
426
+ } catch (err) {
427
+ if (/** @type {NodeJS.ErrnoException} */ (err)?.code === "ESRCH") return { replaced: true };
428
+ }
429
+
430
+ // D4: wait for the old process to actually exit before the caller spawns a
431
+ // successor. The tick budget keeps the wait finite even when an injected
432
+ // clock never advances; `clock` ends it early when wall time runs out first.
433
+ const deadline = clock() + replaceTimeoutMs;
434
+ const maxTicks = Math.max(1, Math.ceil(replaceTimeoutMs / REPLACE_POLL_MS));
435
+ for (let tick = 0; tick < maxTicks; tick++) {
436
+ if (!isAliveFn(pid)) return { replaced: true };
437
+ if (clock() >= deadline) break;
438
+ await sleep(REPLACE_POLL_MS);
160
439
  }
161
- return false;
440
+ return skip("replace_timeout");
162
441
  }
163
442
 
164
443
  /**
@@ -174,8 +453,36 @@ async function replaceStaleCoordinator(root, socketPath) {
174
453
  * If the stale instance cannot be replaced (unkillable, socket stuck), report
175
454
  * `coordinator_stale_protocol` instead of pretending it is healthy.
176
455
  *
456
+ * Replacement seams (issue #239): the identity-gated replacement accepts every
457
+ * injectable dependency of `replaceStaleCoordinator` (`probe`, `kill`,
458
+ * `isAlive`, `readStartToken`, `clock`, `sleep`, `replaceTimeoutMs`,
459
+ * `reportSkip`) plus the re-probe plumbing (`connect`, `probeTimeoutMs`); this
460
+ * function forwards them verbatim. Defaults live in `replaceStaleCoordinator`,
461
+ * so an omitted option keeps the production behaviour.
462
+ *
463
+ * Root-lifetime note (issue #241): a root that does not exist yet is no longer
464
+ * lazily created — the boot guard makes the spawned coordinator exit 0, so a
465
+ * `ensureCoordinator` call on a missing root waits the full `ENSURE_WINDOW_MS`
466
+ * (~10 s) and returns `coordinator_unavailable`. No in-repo caller does that;
467
+ * external one-shot callers that relied on a lazily-created board are affected.
468
+ *
177
469
  * @param {string} root
178
- * @param {{ runnerScript?: string, node?: string, probeTimeoutMs?: number, ensureWindowMs?: number, pollMs?: number, connect?: (path: string) => import("node:net").Socket }} [opts]
470
+ * @param {{
471
+ * runnerScript?: string,
472
+ * node?: string,
473
+ * probeTimeoutMs?: number,
474
+ * ensureWindowMs?: number,
475
+ * pollMs?: number,
476
+ * connect?: (path: string) => import("node:net").Socket,
477
+ * probe?: (socketPath: string, connect: (path: string) => import("node:net").Socket, timeoutMs: number) => Promise<{instanceId: string, protocolVersion: number}|null>,
478
+ * kill?: (pid: number, signal: string) => void,
479
+ * isAlive?: (pid: number) => boolean,
480
+ * readStartToken?: (pid: number) => Promise<string|null>,
481
+ * clock?: () => number,
482
+ * sleep?: (ms: number) => Promise<void>,
483
+ * replaceTimeoutMs?: number,
484
+ * reportSkip?: (details: { reason: SkipReason, recordedInstanceId: string|null, probedInstanceId: string }) => void,
485
+ * }} [opts]
179
486
  * @returns {Promise<EnsureResult>}
180
487
  */
181
488
  export async function ensureCoordinator(root, opts = {}) {
@@ -189,9 +496,22 @@ export async function ensureCoordinator(root, opts = {}) {
189
496
  const first = await probeOnce(socketPath, connect, probeTimeoutMs);
190
497
  if (first) {
191
498
  if (first.protocolVersion >= COORDINATOR_PROTOCOL_VERSION) return { ok: true, instanceId: first.instanceId };
192
- if (!await replaceStaleCoordinator(root, socketPath)) {
193
- return { ok: false, error: "coordinator_stale_protocol" };
194
- }
499
+ // Issue #239: only the instance that answered our ping may be replaced —
500
+ // its instanceId is the identity the lease must prove. A skip is already
501
+ // reported with its reason by the replacement orchestration itself.
502
+ const outcome = await replaceStaleCoordinator(root, socketPath, first.instanceId, {
503
+ connect,
504
+ probeTimeoutMs,
505
+ probe: opts.probe,
506
+ kill: opts.kill,
507
+ isAlive: opts.isAlive,
508
+ readStartToken: opts.readStartToken,
509
+ clock: opts.clock,
510
+ sleep: opts.sleep,
511
+ replaceTimeoutMs: opts.replaceTimeoutMs,
512
+ reportSkip: opts.reportSkip,
513
+ });
514
+ if (!outcome.replaced) return { ok: false, error: "coordinator_stale_protocol" };
195
515
  }
196
516
 
197
517
  const launched = launchCoordinator(root, { runnerScript: opts.runnerScript ?? COORDINATOR_SCRIPT, node: opts.node });
@@ -16,6 +16,30 @@ export function appendDiagnostic(root, viewId, patch = {}) {
16
16
  return event;
17
17
  }
18
18
 
19
+ /**
20
+ * Append a diagnostic unless a recent event already carries the same code and the
21
+ * same `opts.match` detail values (issue #217 D4): repeated attach clicks on one
22
+ * unverifiable host must leave one trail, not a flood.
23
+ * @param {string} root
24
+ * @param {string} viewId
25
+ * @param {Partial<import("./types.mjs").DiagnosticEvent>} patch
26
+ * @param {{ match?: string[], limit?: number }} [opts] `match: []` never dedupes.
27
+ * @returns {import("./types.mjs").DiagnosticEvent|null} the appended event, or null when skipped
28
+ */
29
+ export function appendDiagnosticOnce(root, viewId, patch = {}, opts = {}) {
30
+ const event = normalizeDiagnostic(viewId, patch);
31
+ const match = Array.isArray(opts.match) ? opts.match : [];
32
+ if (match.length > 0) {
33
+ const limit = opts.limit ?? 20;
34
+ const duplicate = readJsonlTail(P.diagnosticsPath(root, viewId), limit)
35
+ .map((e) => normalizeDiagnostic(viewId, e))
36
+ .some((e) => e.code === event.code && match.every((key) => e.details?.[key] === event.details?.[key]));
37
+ if (duplicate) return null;
38
+ }
39
+ appendJsonl(P.diagnosticsPath(root, viewId), event);
40
+ return event;
41
+ }
42
+
19
43
  /** @param {string} root @param {string} viewId @returns {import("./types.mjs").DiagnosticEvent[]} */
20
44
  export function readDiagnostics(root, viewId) {
21
45
  return readJsonl(P.diagnosticsPath(root, viewId)).map((e) => normalizeDiagnostic(viewId, e));
@@ -18,7 +18,18 @@ import { assistantText, detectNeedsInput, toolPath, toolSummary, truncate } from
18
18
  const PREVIEW_MAX = 240;
19
19
 
20
20
  /** Tool names whose interactive execution blocks on a user answer. */
21
- const QUESTION_TOOL_NAMES = new Set(["ask_questions", "question", "questionnaire"]);
21
+ const QUESTION_TOOL_NAMES = new Set(["ask_user_question", "ask_questions", "question", "questionnaire"]);
22
+
23
+ /** Questionnaire args shared by pi/Claude-Code style question tools. */
24
+ function isQuestionArgShape(args) {
25
+ const questions = Array.isArray(args?.questions) ? args.questions : null;
26
+ return Boolean(questions && questions.length > 0 && typeof questions[0]?.question === "string");
27
+ }
28
+
29
+ /** A start event is a question when its name is known or its args carry the questionnaire shape. */
30
+ function isQuestionToolCall(name, args) {
31
+ return QUESTION_TOOL_NAMES.has(name) || isQuestionArgShape(args);
32
+ }
22
33
 
23
34
  /**
24
35
  * Build the initial status for a freshly-launched run.
@@ -83,7 +94,7 @@ export function reduceEvent(status, event, now, opts = {}) {
83
94
  const name = event.toolName ?? event.args?.name ?? "tool";
84
95
  const args = event.args ?? {};
85
96
  status.toolCount += 1;
86
- if (opts.interactive && QUESTION_TOOL_NAMES.has(name)) {
97
+ if (opts.interactive && isQuestionToolCall(name, args)) {
87
98
  upsertPendingQuestion(status, event.toolCallId, questionFromArgs(args));
88
99
  } else if (pendingQuestions(status).length === 0) {
89
100
  status.currentTool = { name, path: toolPath(args), summary: toolSummary(name, args) };
@@ -97,7 +108,9 @@ export function reduceEvent(status, event, now, opts = {}) {
97
108
  }
98
109
  case "tool_execution_end": {
99
110
  if (event.isError) status.error = `Tool ${event.toolName ?? ""} failed`.trim();
100
- if (opts.interactive && QUESTION_TOOL_NAMES.has(event.toolName ?? "")) removePendingQuestion(status, event.toolCallId);
111
+ // The end event carries no args, so a shape-matched start cannot be recognized here;
112
+ // remove by call id instead (a no-op when this call had no pending question).
113
+ if (opts.interactive) removePendingQuestion(status, event.toolCallId);
101
114
  status.currentTool = null;
102
115
  status.semanticState = "working";
103
116
  status.question = null;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Process-local read-your-writes cache for foreground status projections
3
+ * (issue #225).
4
+ *
5
+ * `syncRowEvent` rebuilds its status from `state.json` on every event, while
6
+ * `writeForegroundState` is fire-and-forget: two events can have two
7
+ * `sync_foreground` commands in flight, and an older projection can materialize
8
+ * last. Because the rebuilt status carries no freshness signal, the next event
9
+ * reduces onto the stale state and writes it back — a cleared question comes
10
+ * back as `needs_input` until a terminal event lands.
11
+ *
12
+ * This cache stores the freshest whitelisted status fields with a strictly
13
+ * increasing per-view stamp (`nextStamp`), so a disk rebuild that is older than
14
+ * the last write is corrected before the new event is reduced.
15
+ *
16
+ * Module-level by necessity: `serviceFor()` creates a new service instance per
17
+ * call (src/index.ts), so a per-instance cache would be discarded between
18
+ * events.
19
+ */
20
+
21
+ /** Fields a cached snapshot may restore on a stale rebuild. */
22
+ const CACHED_FIELDS = [
23
+ "semanticState",
24
+ "processState",
25
+ "summary",
26
+ "currentTool",
27
+ "question",
28
+ "pendingQuestions",
29
+ "error",
30
+ "lastActivityAt",
31
+ "latestAssistantPreview",
32
+ "lastAgentActivityAt",
33
+ ];
34
+
35
+ /** @param {any} value */
36
+ function cloneValue(value) {
37
+ if (value === null || typeof value !== "object") return value;
38
+ return JSON.parse(JSON.stringify(value));
39
+ }
40
+
41
+ /** @param {any} status */
42
+ function snapshot(status) {
43
+ /** @type {Record<string, unknown>} */
44
+ const fields = {};
45
+ for (const key of CACHED_FIELDS) fields[key] = cloneValue(status?.[key]);
46
+ return fields;
47
+ }
48
+
49
+ export function createForegroundProjectionCache() {
50
+ /** @type {Map<string, { stamp: number, fields: Record<string, unknown> }>} */
51
+ const known = new Map();
52
+ /** @type {Map<string, number>} */
53
+ const stamps = new Map();
54
+
55
+ function nextStamp(viewId) {
56
+ const stamp = Math.max(Date.now(), (stamps.get(viewId) ?? 0) + 1);
57
+ stamps.set(viewId, stamp);
58
+ return stamp;
59
+ }
60
+
61
+ function remember(viewId, status, stamp) {
62
+ if (!viewId || !status || typeof stamp !== "number" || !Number.isFinite(stamp)) return;
63
+ known.set(viewId, { stamp, fields: snapshot(status) });
64
+ }
65
+
66
+ function adopt(viewId, status) {
67
+ if (!viewId || !status) return false;
68
+ const entry = known.get(viewId);
69
+ if (!entry) return false;
70
+ const at = typeof status.updatedAt === "number" ? status.updatedAt : 0;
71
+ if (entry.stamp <= at) return false;
72
+ for (const key of CACHED_FIELDS) status[key] = cloneValue(entry.fields[key]);
73
+ status.updatedAt = entry.stamp;
74
+ return true;
75
+ }
76
+
77
+ function forget(viewId) {
78
+ stamps.delete(viewId);
79
+ return known.delete(viewId);
80
+ }
81
+
82
+ function clear() {
83
+ known.clear();
84
+ stamps.clear();
85
+ }
86
+
87
+ function size() {
88
+ return known.size;
89
+ }
90
+
91
+ return { nextStamp, remember, adopt, forget, clear, size };
92
+ }
93
+
94
+ /**
95
+ * Shared cache used by the runtime service (module-level: see module doc).
96
+ * Keyed by view id only, matching the preview cache: production view ids are generated
97
+ * and never reused, and tests clear the cache per case.
98
+ */
99
+ export const foregroundProjectionCache = createForegroundProjectionCache();