@zhuxixi/pi-agent-board 0.12.0 → 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 (52) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +7 -7
  3. package/docs/superpowers/plans/2026-10-19-issue-213-reply-guard-csi-key.md +257 -0
  4. package/docs/superpowers/plans/2026-10-19-issue-214-attach-forward-alt-modifier.md +202 -0
  5. package/docs/superpowers/plans/2026-10-21-issue-221-ask-user-question.md +198 -0
  6. package/docs/superpowers/plans/2026-10-23-issue-225-monotonic-foreground-state.md +450 -0
  7. package/docs/superpowers/plans/2026-10-23-issue-229-vim-jkl.md +449 -0
  8. package/docs/superpowers/plans/2026-10-23-issue-232-attach-bg-only-cells.md +153 -0
  9. package/docs/superpowers/plans/2026-10-23-lease-heartbeat-staleness.md +537 -0
  10. package/docs/superpowers/plans/2026-10-23-selected-row-highlight.md +405 -0
  11. package/docs/superpowers/plans/2026-10-24-issue-217-windows-pid-reuse-stopping.md +367 -0
  12. package/docs/superpowers/plans/2026-10-24-issue-230-warm-host-background-runs.md +806 -0
  13. package/docs/superpowers/plans/2026-10-24-issue-238-windows-process-identity-token.md +490 -0
  14. package/docs/superpowers/plans/2026-10-24-issue-241-coordinator-root-exit.md +461 -0
  15. package/docs/superpowers/plans/2026-10-25-issue-239-coordinator-replacement-identity.md +504 -0
  16. package/docs/superpowers/specs/2026-10-14-issue-170-attach-reply-guard-design.md +5 -0
  17. package/docs/superpowers/specs/2026-10-19-issue-213-reply-guard-csi-key-design.md +165 -0
  18. package/docs/superpowers/specs/2026-10-19-issue-214-attach-forward-alt-modifier-design.md +131 -0
  19. package/docs/superpowers/specs/2026-10-20-issue-221-ask-user-question-design.md +270 -0
  20. package/docs/superpowers/specs/2026-10-22-issue-225-monotonic-foreground-state-design.md +225 -0
  21. package/docs/superpowers/specs/2026-10-23-issue-229-vim-jkl-design.md +90 -0
  22. package/docs/superpowers/specs/2026-10-23-issue-232-attach-bg-only-cells-design.md +146 -0
  23. package/docs/superpowers/specs/2026-10-23-lease-heartbeat-staleness-design.md +271 -0
  24. package/docs/superpowers/specs/2026-10-23-selected-row-highlight-design.md +191 -0
  25. package/docs/superpowers/specs/2026-10-24-issue-217-windows-pid-reuse-stopping-design.md +334 -0
  26. package/docs/superpowers/specs/2026-10-24-issue-230-warm-host-background-runs-design.md +283 -0
  27. package/docs/superpowers/specs/2026-10-24-issue-238-windows-process-identity-token-design.md +286 -0
  28. package/docs/superpowers/specs/2026-10-24-issue-241-coordinator-root-exit-design.md +381 -0
  29. package/docs/superpowers/specs/2026-10-25-issue-239-coordinator-replacement-identity-design.md +331 -0
  30. package/package.json +3 -3
  31. package/runner/pty-runner.mjs +18 -22
  32. package/runner/state-coordinator.mjs +213 -26
  33. package/scripts/release_helper.mjs +39 -7
  34. package/scripts/run-tests.mjs +375 -0
  35. package/src/core/background-runs.mjs +273 -0
  36. package/src/core/coordinator-client.mjs +346 -26
  37. package/src/core/diagnostics.mjs +24 -0
  38. package/src/core/events.mjs +16 -3
  39. package/src/core/foreground-projection-cache.mjs +99 -0
  40. package/src/core/host-coordination.mjs +69 -1
  41. package/src/core/launch.mjs +21 -1
  42. package/src/core/locks.mjs +176 -31
  43. package/src/core/pid.mjs +4 -2
  44. package/src/core/process-identity-probe.mjs +228 -0
  45. package/src/core/pty-scroll.mjs +21 -14
  46. package/src/core/state-commands.mjs +5 -1
  47. package/src/core/terminal-reply-guard.mjs +26 -4
  48. package/src/core/types.mjs +1 -0
  49. package/src/core/warm-host-sweeper.mjs +7 -2
  50. package/src/runtime/service.mjs +385 -73
  51. package/src/ui/dashboard.ts +48 -25
  52. package/src/ui/pty-attach.ts +18 -7
@@ -41,18 +41,86 @@ export function isStartingWithinGrace(host, now, graceMs) {
41
41
  * Five states — `not_started` (never spawned) must never be conflated with
42
42
  * `dead`, and a missing stable token must never be guessed as alive-owned:
43
43
  * it degrades to `unknown` so recovery can only refuse, never misfire.
44
+ *
45
+ * `not_started` requires BOTH the identity and `spawnedAt` to be absent: a
46
+ * recorded identity is proof the spawn happened, so such a record is judged by
47
+ * the observation. Calling it `not_started` (a releasable state) on a
48
+ * spawned-but-incomplete record could release a still-live host and let a new
49
+ * host double-write the session file.
44
50
  * @param {{pid:number,startToken:string|null}|null|undefined} identity The recorded identity.
45
51
  * @param {{alive:boolean,startToken:string|null}|null|undefined} observed The observation.
46
52
  * @param {number|null|undefined} spawnedAt Non-null only after spawn was confirmed.
47
53
  * @returns {"not_started"|"dead"|"owned"|"foreign"|"unknown"}
48
54
  */
49
55
  export function processIdentityState(identity, observed, spawnedAt) {
50
- if (spawnedAt == null) return "not_started";
56
+ if (spawnedAt == null && identity == null) return "not_started";
51
57
  if (observed?.alive === false) return "dead";
52
58
  if (identity?.startToken == null || observed?.startToken == null) return "unknown";
53
59
  return identity.startToken === observed.startToken ? "owned" : "foreign";
54
60
  }
55
61
 
62
+ /** Characters that may abut a path fragment in a command line without being part of it. */
63
+ const COMMAND_LINE_BOUNDARIES = /[\s"']/;
64
+
65
+ /** Windows path semantics: separators and case are not significant. */
66
+ function normalizeCommandLine(text) {
67
+ return text.replace(/\\/g, "/").toLowerCase();
68
+ }
69
+
70
+ function isCommandLineBoundary(text, index, length) {
71
+ const before = index === 0 ? null : text[index - 1];
72
+ const after = index + length >= text.length ? null : text[index + length];
73
+ return (before == null || COMMAND_LINE_BOUNDARIES.test(before)) && (after == null || COMMAND_LINE_BOUNDARIES.test(after));
74
+ }
75
+
76
+ /**
77
+ * Whether a process command line mentions `fragment` as a whole path, not as a
78
+ * prefix of a longer one (`view_abc` must not match `view_abcd`, nor
79
+ * `session.jsonl` match `session-2.jsonl`). Comparison is slash- and
80
+ * case-insensitive because Windows reports `C:\x\y` inside quotes while the
81
+ * recorded fragment is a plain path (issue #217). Empty/missing input is never
82
+ * a match: a blank fragment would otherwise corroborate any process.
83
+ * @param {string|null|undefined} commandLine
84
+ * @param {string|null|undefined} fragment
85
+ * @returns {boolean}
86
+ */
87
+ export function commandLineMentions(commandLine, fragment) {
88
+ if (!commandLine || !fragment) return false;
89
+ const haystack = normalizeCommandLine(commandLine);
90
+ const needle = normalizeCommandLine(fragment);
91
+ let index = haystack.indexOf(needle);
92
+ while (index !== -1) {
93
+ if (isCommandLineBoundary(haystack, index, needle.length)) return true;
94
+ index = haystack.indexOf(needle, index + 1);
95
+ }
96
+ return false;
97
+ }
98
+
99
+ /**
100
+ * Refine a host-role observation that the token path could only call `unknown`
101
+ * (platforms without a start token) using deterministic probe evidence
102
+ * (issue #217). The command line is authoritative because every host role we
103
+ * spawn carries its own unique path argument; process creation time only
104
+ * corroborates when the command line is unreadable, and the tolerance absorbs
105
+ * spawn→record skew. A missing probe stays `unknown` — the #70 contract: an
106
+ * unverifiable process is never guessed as foreign.
107
+ * @param {{
108
+ * spawnedAt: number|null,
109
+ * probe: {creationTimeMs: number|null, commandLine: string|null}|null,
110
+ * expectedCommandFragment: string|null,
111
+ * toleranceMs: number,
112
+ * }} input
113
+ * @returns {"owned"|"foreign"|"unknown"}
114
+ */
115
+ export function classifyUnverifiableProcess({ spawnedAt, probe, expectedCommandFragment, toleranceMs }) {
116
+ if (!probe) return "unknown";
117
+ if (probe.commandLine && expectedCommandFragment) {
118
+ return commandLineMentions(probe.commandLine, expectedCommandFragment) ? "owned" : "foreign";
119
+ }
120
+ if (spawnedAt == null || probe.creationTimeMs == null) return "unknown";
121
+ return Math.abs(probe.creationTimeMs - spawnedAt) <= toleranceMs ? "owned" : "foreign";
122
+ }
123
+
56
124
  /** Role observations that mean "no live process can belong to the old instance". */
57
125
  const SAFE_TO_RELEASE = new Set(["not_started", "dead", "foreign"]);
58
126
 
@@ -6,6 +6,7 @@
6
6
  * records the runner pid in `pid.json` and watches the store files the runner writes.
7
7
  */
8
8
  import { spawn } from "node:child_process";
9
+ import { dirname, resolve } from "node:path";
9
10
  import { atomicWriteJson } from "./atomic.mjs";
10
11
  import { resolveNode } from "./invocation.mjs";
11
12
  import * as P from "./paths.mjs";
@@ -121,17 +122,36 @@ export function launchAutoState(root, config, opts) {
121
122
  return { pid: child.pid ?? null, configPath };
122
123
  }
123
124
 
125
+ /**
126
+ * Compute the detached coordinator spawn plan (issue #241): an absolute root
127
+ * argv and a cwd OUTSIDE the root (the root's parent; at a drive/filesystem
128
+ * root the parent is the root itself). The coordinator derives all paths from
129
+ * the root argument and never uses cwd, so keeping cwd off the root releases
130
+ * the win32 directory handle that made throwaway roots undeletable.
131
+ * @param {string} root
132
+ * @returns {{ root: string, cwd: string }}
133
+ */
134
+ export function coordinatorSpawnPlan(root) {
135
+ const absoluteRoot = resolve(root);
136
+ return { root: absoluteRoot, cwd: dirname(absoluteRoot) };
137
+ }
138
+
124
139
  /**
125
140
  * Launch the detached view-state coordinator for a board root (issue #91, spec
126
141
  * D3). No config file: the coordinator takes the root as its only argument.
127
142
  * Idempotent by lease — a second instance loses the coordinator lease and
128
143
  * exits silently, so callers may spawn freely on probe failure.
144
+ * The child's cwd is the root's PARENT (issue #241): the coordinator derives
145
+ * paths from argv and cwd must not pin the root on win32. At a drive/filesystem
146
+ * root (win32 `C:\`, POSIX `/`) the parent is the root itself — see
147
+ * `coordinatorSpawnPlan`.
129
148
  * @param {string} root
130
149
  * @param {{ runnerScript: string, node?: string }} opts
131
150
  * @returns {{ pid: number|null }}
132
151
  */
133
152
  export function launchCoordinator(root, opts) {
134
153
  const node = opts.node ?? resolveNode();
135
- const child = spawnDetached(node, [opts.runnerScript, root], root);
154
+ const plan = coordinatorSpawnPlan(root);
155
+ const child = spawnDetached(node, [opts.runnerScript, plan.root], plan.cwd);
136
156
  return { pid: child.pid ?? null };
137
157
  }
@@ -149,15 +149,29 @@ const MAX_LEASE_RECLAIM_ATTEMPTS = 3;
149
149
  * holder reaches this (issue #112).
150
150
  */
151
151
  const ORPHAN_LEASE_AGE_MS = 5 * 60_000;
152
+ /** Age past which a heartbeating lease with no live proof of ownership is an orphan. */
153
+ export const LEASE_HEARTBEAT_STALE_MS = 60_000;
154
+ /** Consecutive supervised heartbeat failures after which a holder must vacate. */
155
+ export const MAX_CONSECUTIVE_TOUCH_FAILURES = 3;
152
156
 
153
157
  /**
154
158
  * A token-fenced lease over the view-lock directory. Every operation re-reads
155
159
  * owner.json and only acts while it still carries this lease's token, so a
156
160
  * superseded owner can never touch — heartbeat or delete — the current owner's
157
161
  * lock. Unlike withFileLockSync, a held lock is never stolen by age alone; it
158
- * can only be reclaimed when its recorded owner process is provably dead.
162
+ * can only be reclaimed when its recorded owner process is provably dead, or
163
+ * when a heartbeating owner stopped heartbeating (issue #224).
164
+ * @typedef {Object} LeaseReclaimed
165
+ * @property {number} ownerPid
166
+ * @property {number|null} heartbeatAgeMs
167
+ * @property {number} lockAgeMs
168
+ * @property {"declared" | "legacy"} eligibility
169
+ */
170
+
171
+ /**
159
172
  * @typedef {Object} Lease
160
173
  * @property {string} token
174
+ * @property {LeaseReclaimed|null} reclaimed metadata when this acquire reclaimed a stale lease
161
175
  * @property {() => boolean} touch
162
176
  * @property {() => boolean} isOwner
163
177
  * @property {() => boolean} release
@@ -167,7 +181,7 @@ const ORPHAN_LEASE_AGE_MS = 5 * 60_000;
167
181
  * @param {string} root
168
182
  * @param {string} viewId
169
183
  * @param {string} name
170
- * @param {{ waitMs?: number, identity?: object|null, fs?: Partial<typeof defaultLeaseFs>, clock?: () => number, isProcessDead?: (pid: number) => boolean }} [opts]
184
+ * @param {{ waitMs?: number, identity?: object|null, heartbeatMs?: number, fs?: Partial<typeof defaultLeaseFs>, clock?: () => number, isProcessDead?: (pid: number) => boolean }} [opts]
171
185
  * @returns {Lease}
172
186
  * @throws {Error & { code: "LOCK_TIMEOUT" }} when the lock is still held after waitMs
173
187
  */
@@ -186,7 +200,7 @@ export function acquireOwnedViewLock(root, viewId, name, opts = {}) {
186
200
  * @param {string} root
187
201
  * @param {string} viewId
188
202
  * @param {string} name
189
- * @param {{ identity?: object|null, fs?: Partial<typeof defaultLeaseFs>, clock?: () => number, isProcessDead?: (pid: number) => boolean }} [opts]
203
+ * @param {{ identity?: object|null, heartbeatMs?: number, fs?: Partial<typeof defaultLeaseFs>, clock?: () => number, isProcessDead?: (pid: number) => boolean }} [opts]
190
204
  * @returns {{ acquired: true, lease: Lease } | { acquired: false, reason: "busy"|"blocked" }}
191
205
  */
192
206
  export function tryAcquireOwnedViewLock(root, viewId, name, opts = {}) {
@@ -217,7 +231,7 @@ export function isPublishConflictCode(code) {
217
231
  * written BEFORE the lock path exists) via atomic rename, and on contention
218
232
  * either reclaim a provably-dead owner's lock via quarantine or report.
219
233
  * @param {string} lockPath
220
- * @param {{ identity?: object|null, fs?: Partial<typeof defaultLeaseFs>, clock?: () => number, isProcessDead?: (pid: number) => boolean }} opts
234
+ * @param {{ identity?: object|null, heartbeatMs?: number, fs?: Partial<typeof defaultLeaseFs>, clock?: () => number, isProcessDead?: (pid: number) => boolean }} opts
221
235
  * @returns {Lease | "busy" | "blocked"}
222
236
  */
223
237
  function attemptAcquireLease(lockPath, opts) {
@@ -225,6 +239,11 @@ function attemptAcquireLease(lockPath, opts) {
225
239
  const now = opts.clock ?? Date.now;
226
240
  const isProcessDead = opts.isProcessDead ?? ((pid) => !isAlive(pid));
227
241
  const identity = opts.identity ?? null;
242
+ const heartbeatMs = Number(opts.heartbeatMs ?? 0);
243
+ // Declaring the period is what makes this lease reclaimable on staleness
244
+ // alone (issue #224 D2); unset keeps the pre-#224 record shape.
245
+ const declaresHeartbeat = Number.isFinite(heartbeatMs) && heartbeatMs > 0;
246
+ let reclaimed = null;
228
247
  for (let attempt = 0; attempt < MAX_LEASE_RECLAIM_ATTEMPTS; attempt++) {
229
248
  const token = randomBytes(16).toString("hex");
230
249
  const candidate = `${lockPath}.candidate.${token}`;
@@ -235,18 +254,22 @@ function attemptAcquireLease(lockPath, opts) {
235
254
  fs.mkdirSync(candidate);
236
255
  fs.writeFileSync(
237
256
  path.join(candidate, "owner.json"),
238
- JSON.stringify({ token, pid: process.pid, identity, startedAt: now() }),
257
+ JSON.stringify({
258
+ token, pid: process.pid, identity, startedAt: now(),
259
+ ...(declaresHeartbeat ? { heartbeatMs } : {}),
260
+ }),
239
261
  "utf8",
240
262
  );
241
263
  fs.renameSync(candidate, lockPath);
242
- return makeLease(lockPath, token, fs, now);
264
+ return makeLease(lockPath, token, fs, now, reclaimed);
243
265
  } catch (err) {
244
266
  try { fs.rmSync(candidate, { recursive: true, force: true }); } catch { /* best effort */ }
245
267
  const code = /** @type {NodeJS.ErrnoException|undefined} */ (err)?.code;
246
268
  if (!isPublishConflictCode(code)) throw err;
247
- const verdict = reclaimOrBlock(lockPath, token, fs, isProcessDead, now);
248
- if (verdict !== true) return verdict;
249
- // Reclaimed a dead owner's lock — retry the publish on the next round.
269
+ const outcome = reclaimOrBlock(lockPath, token, fs, isProcessDead, now);
270
+ if (typeof outcome === "string") return outcome;
271
+ reclaimed = outcome.reclaimed;
272
+ // Reclaimed a stale owner's lock — retry the publish on the next round.
250
273
  }
251
274
  }
252
275
  return "busy";
@@ -254,47 +277,97 @@ function attemptAcquireLease(lockPath, opts) {
254
277
 
255
278
  /**
256
279
  * Decide what to do with an inspected lease owner. Pure: the caller supplies
257
- * `now` and a pid-liveness probe.
280
+ * `now`, a pid-liveness probe and the observed heartbeat age.
258
281
  *
259
- * A full identity (pid + startToken) reclaims exactly when its pid is dead.
260
- * An identity-less owner — legacy short-hold locks, or platforms where
261
- * startToken cannot be captured — is only reclaimable past `orphanAgeMs`
262
- * with a provably dead top-level pid: fresh identity-less locks stay blocked,
263
- * preserving the short-critical-section contract (issue #112).
282
+ * Heartbeat eligibility comes first, because a reused pid looks alive while the
283
+ * recorded owner is long gone (issue #224). Two mutually exclusive paths:
284
+ * - declared: the owner wrote `heartbeatMs` into owner.json. Threshold is
285
+ * `max(heartbeatStaleMs, 3 × heartbeatMs)`; a missing heartbeat falls back to
286
+ * the lock age. This path applies to identity and identity-less owners and
287
+ * bypasses the identity-less age gate, or a crash would take 5 minutes to heal.
288
+ * - legacy: a `heartbeat.<token>` file exists (hence `heartbeatAgeMs != null`)
289
+ * and the lock is past `orphanAgeMs`. The age gate keeps millisecond-scale
290
+ * short-hold leases (`host-meta`, `host-start`) out of this path.
291
+ *
292
+ * Without heartbeat evidence the pre-#224 liveness rules apply unchanged: a
293
+ * full identity (pid + startToken) reclaims exactly when its pid is dead; an
294
+ * identity-less owner is only reclaimable past `orphanAgeMs` with a provably
295
+ * dead pid, so fresh identity-less locks stay blocked (issue #112).
264
296
  * @param {any} owner parsed owner.json
265
297
  * @param {number} now
266
298
  * @param {(pid: number) => boolean} isProcessDead
267
- * @param {{ orphanAgeMs?: number }} [opts]
299
+ * @param {{ orphanAgeMs?: number, heartbeatAgeMs?: number|null, heartbeatMs?: number, heartbeatStaleMs?: number }} [opts]
268
300
  * @returns {"reclaim" | "busy" | "blocked"}
269
301
  */
270
302
  export function classifyLeaseOwner(owner, now, isProcessDead, opts = {}) {
271
303
  if (!owner || typeof owner !== "object") return "blocked";
272
- const ownPid = Number(owner?.identity?.pid ?? 0);
273
- const hasIdentity = Number.isFinite(ownPid) && ownPid > 0 && typeof owner?.identity?.startToken === "string";
274
- if (hasIdentity) {
275
- if (!isProcessDead(ownPid)) return "busy";
276
- // Quarantine-mode reclaim verifies by token that it renamed the lock it
277
- // inspected — without one nothing may be deleted.
278
- return typeof owner.token === "string" ? "reclaim" : "blocked";
279
- }
280
- const pid = Number(owner?.pid ?? 0);
304
+ const identityPid = Number(owner?.identity?.pid ?? 0);
305
+ const hasIdentity = Number.isFinite(identityPid) && identityPid > 0 && typeof owner?.identity?.startToken === "string";
306
+ const pid = Number(owner?.identity?.pid ?? owner?.pid ?? 0);
281
307
  if (!Number.isFinite(pid) || pid <= 0) return "blocked";
308
+ // Quarantine-mode reclaim verifies by token that it renamed the lock it
309
+ // inspected — without one nothing may be deleted.
310
+ const reclaimable = typeof owner.token === "string";
282
311
  const orphanAgeMs = Number(opts.orphanAgeMs ?? ORPHAN_LEASE_AGE_MS);
283
- if (!(Number(now) - Number(owner?.startedAt ?? 0) >= orphanAgeMs)) return "blocked";
312
+ // The declared period may arrive via opts (I/O shell) or already be on the
313
+ // parsed owner record (pure callers); opts wins.
314
+ const heartbeatMs = Number(opts.heartbeatMs ?? owner?.heartbeatMs ?? 0);
315
+ const declared = Number.isFinite(heartbeatMs) && heartbeatMs > 0;
316
+ const heartbeatStaleMs = Number(opts.heartbeatStaleMs ?? LEASE_HEARTBEAT_STALE_MS);
317
+ const lockAgeMs = Number(now) - Number(owner?.startedAt ?? 0);
318
+ if (declared) {
319
+ const heartbeatAgeMs = Math.max(0, Number(opts.heartbeatAgeMs ?? lockAgeMs));
320
+ if (heartbeatAgeMs >= Math.max(heartbeatStaleMs, 3 * heartbeatMs)) return reclaimable ? "reclaim" : "blocked";
321
+ } else if (opts.heartbeatAgeMs != null && lockAgeMs >= orphanAgeMs) {
322
+ const heartbeatAgeMs = Math.max(0, Number(opts.heartbeatAgeMs));
323
+ if (heartbeatAgeMs >= heartbeatStaleMs) return reclaimable ? "reclaim" : "blocked";
324
+ }
325
+ if (hasIdentity) {
326
+ if (!isProcessDead(pid)) return "busy";
327
+ return reclaimable ? "reclaim" : "blocked";
328
+ }
329
+ if (!declared && lockAgeMs < orphanAgeMs) return "blocked";
284
330
  if (!isProcessDead(pid)) return "busy";
285
- return typeof owner.token === "string" ? "reclaim" : "blocked";
331
+ return reclaimable ? "reclaim" : "blocked";
332
+ }
333
+
334
+ /**
335
+ * Read the owner-written heartbeat and return its age in ms. A future `at`
336
+ * (clock skew) clamps to 0: a heartbeat must never look older than it is.
337
+ * @param {string} lockPath
338
+ * @param {any} token the recorded owner token (names the heartbeat file)
339
+ * @param {{ readFileSync: (path: string, encoding: string) => string }} [fs]
340
+ * @param {number} [now]
341
+ * @returns {number|null} null when the file is missing or its `at` is unusable
342
+ */
343
+ export function readLeaseHeartbeat(lockPath, token, fs = defaultLocksFs, now = Date.now()) {
344
+ if (typeof token !== "string" || token.length === 0) return null;
345
+ let parsed;
346
+ try {
347
+ parsed = JSON.parse(fs.readFileSync(path.join(lockPath, `heartbeat.${token}`), "utf8"));
348
+ } catch {
349
+ return null;
350
+ }
351
+ const at = parsed?.at;
352
+ if (typeof at !== "number" || !Number.isFinite(at)) return null;
353
+ return Math.max(0, now - at);
286
354
  }
287
355
 
288
356
  /**
289
357
  * Decide whether an existing lock may be reclaimed. Verdicts come from the
290
358
  * pure `classifyLeaseOwner`; reclaim itself quarantines via rename first so a
291
359
  * concurrent winner can only ever delete the directory it itself renamed.
360
+ *
361
+ * The observed heartbeat age is the only I/O this adds: a missing or broken
362
+ * heartbeat file resolves to null, which grants no eligibility to an
363
+ * undeclared lease (fail closed) and falls back to the lock age for a declared
364
+ * one (issue #224 D3).
292
365
  * @param {string} lockPath
293
366
  * @param {string} token the caller's own token (names the quarantine dir)
294
367
  * @param {typeof defaultLeaseFs} fs
295
368
  * @param {(pid: number) => boolean} isProcessDead
296
369
  * @param {() => number} now clock (matching the caller's candidate timestamps)
297
- * @returns {true | "busy" | "blocked"}
370
+ * @returns {{ reclaimed: LeaseReclaimed } | "busy" | "blocked"}
298
371
  */
299
372
  function reclaimOrBlock(lockPath, token, fs, isProcessDead, now) {
300
373
  let owner;
@@ -303,7 +376,15 @@ function reclaimOrBlock(lockPath, token, fs, isProcessDead, now) {
303
376
  } catch {
304
377
  return "blocked";
305
378
  }
306
- const verdict = classifyLeaseOwner(owner, now(), isProcessDead);
379
+ const at = now();
380
+ const heartbeatAgeMs = readLeaseHeartbeat(lockPath, owner?.token, fs, at);
381
+ const declaredHeartbeatMs = Number(owner?.heartbeatMs ?? 0);
382
+ const declared = Number.isFinite(declaredHeartbeatMs) && declaredHeartbeatMs > 0;
383
+ const verdict = classifyLeaseOwner(owner, at, isProcessDead, {
384
+ heartbeatAgeMs,
385
+ heartbeatMs: declared ? declaredHeartbeatMs : undefined,
386
+ heartbeatStaleMs: LEASE_HEARTBEAT_STALE_MS,
387
+ });
307
388
  if (verdict !== "reclaim") return verdict;
308
389
  // classifyLeaseOwner only returns "reclaim" when owner.token is a string.
309
390
  const inspectedToken = owner.token;
@@ -327,7 +408,69 @@ function reclaimOrBlock(lockPath, token, fs, isProcessDead, now) {
327
408
  return "busy";
328
409
  }
329
410
  try { fs.rmSync(quarantine, { recursive: true, force: true }); } catch { /* best effort */ }
330
- return true;
411
+ return {
412
+ reclaimed: {
413
+ ownerPid: Number(owner?.identity?.pid ?? owner?.pid ?? 0),
414
+ heartbeatAgeMs,
415
+ lockAgeMs: at - Number(owner?.startedAt ?? 0),
416
+ eligibility: declared ? "declared" : "legacy",
417
+ },
418
+ };
419
+ }
420
+
421
+ /**
422
+ * Summarize why an existing lock is not acquirable, so the coordinator can
423
+ * record a diagnostic instead of exiting silently (issue #224 D6).
424
+ *
425
+ * Returns exactly the six keys that become the `coordinator_lease_unavailable`
426
+ * details — no more, no less. `reason` is the raw `classifyLeaseOwner` verdict
427
+ * at call time, so on the acquisition-failure path it is `"busy"` or
428
+ * `"blocked"`.
429
+ * @param {string} root
430
+ * @param {string} viewId
431
+ * @param {string} name
432
+ * @param {{ fs?: Partial<typeof defaultLeaseFs>, clock?: () => number, isProcessDead?: (pid: number) => boolean }} [opts]
433
+ * @returns {{ reason: "reclaim"|"busy"|"blocked", ownerPid: number, hasIdentity: boolean, lockAgeMs: number, heartbeatAgeMs: number|null, heartbeatMs: number|null } | null}
434
+ */
435
+ export function describeLeaseConflict(root, viewId, name, opts = {}) {
436
+ const fs = { ...defaultLeaseFs, ...(opts.fs ?? {}) };
437
+ const lockPath = P.viewLockPath(root, viewId, name);
438
+ let owner;
439
+ try {
440
+ owner = JSON.parse(fs.readFileSync(path.join(lockPath, "owner.json"), "utf8"));
441
+ } catch {
442
+ return null;
443
+ }
444
+ if (!owner || typeof owner !== "object") return null;
445
+ const at = (opts.clock ?? Date.now)();
446
+ const isProcessDead = opts.isProcessDead ?? ((pid) => !isAlive(pid));
447
+ const identityPid = Number(owner?.identity?.pid ?? 0);
448
+ const heartbeatAgeMs = readLeaseHeartbeat(lockPath, owner?.token, fs, at);
449
+ const declaredHeartbeatMs = Number(owner?.heartbeatMs ?? 0);
450
+ const heartbeatMs = Number.isFinite(declaredHeartbeatMs) && declaredHeartbeatMs > 0 ? declaredHeartbeatMs : null;
451
+ return {
452
+ reason: classifyLeaseOwner(owner, at, isProcessDead, {
453
+ heartbeatAgeMs,
454
+ heartbeatMs: heartbeatMs ?? undefined,
455
+ heartbeatStaleMs: LEASE_HEARTBEAT_STALE_MS,
456
+ }),
457
+ ownerPid: Number(owner?.identity?.pid ?? owner?.pid ?? 0),
458
+ hasIdentity: Number.isFinite(identityPid) && identityPid > 0 && typeof owner?.identity?.startToken === "string",
459
+ lockAgeMs: at - Number(owner?.startedAt ?? 0),
460
+ heartbeatAgeMs,
461
+ heartbeatMs,
462
+ };
463
+ }
464
+
465
+ /**
466
+ * Supervised heartbeat failure policy: a holder that cannot prove liveness for
467
+ * `maxFailures` consecutive ticks must vacate rather than be preempted later.
468
+ * @param {number} consecutiveFailures
469
+ * @param {number} [maxFailures]
470
+ * @returns {"continue" | "abandon"}
471
+ */
472
+ export function heartbeatFailureAction(consecutiveFailures, maxFailures = MAX_CONSECUTIVE_TOUCH_FAILURES) {
473
+ return Number(consecutiveFailures) >= Number(maxFailures) ? "abandon" : "continue";
331
474
  }
332
475
 
333
476
  /**
@@ -335,9 +478,10 @@ function reclaimOrBlock(lockPath, token, fs, isProcessDead, now) {
335
478
  * @param {string} token
336
479
  * @param {typeof defaultLeaseFs} fs
337
480
  * @param {() => number} now
481
+ * @param {LeaseReclaimed|null} [reclaimed]
338
482
  * @returns {Lease}
339
483
  */
340
- function makeLease(lockPath, token, fs, now) {
484
+ function makeLease(lockPath, token, fs, now, reclaimed = null) {
341
485
  const ownerPath = path.join(lockPath, "owner.json");
342
486
  const heartbeatPath = path.join(lockPath, `heartbeat.${token}`);
343
487
  const stillOwns = () => {
@@ -349,6 +493,7 @@ function makeLease(lockPath, token, fs, now) {
349
493
  };
350
494
  return {
351
495
  token,
496
+ reclaimed,
352
497
  isOwner: () => stillOwns(),
353
498
  touch() {
354
499
  if (!stillOwns()) return false;
package/src/core/pid.mjs CHANGED
@@ -45,8 +45,10 @@ export function killProcess(pid, graceMs = 4000) {
45
45
  /**
46
46
  * POSIX process start token — /proc/<pid>/stat field 22 (starttime), stable
47
47
  * across exec(2). Distinguishes an owned-live pid from a reused one; null on
48
- * failure or non-Linux platforms. Mirrors the runner's captureStartToken
49
- * (issue #70); shared here for host-meta lease identity (issue #112).
48
+ * failure or non-Linux platforms. This is the single synchronous implementation
49
+ * (issue #238 removed the runner copies); the cross-platform async reader in
50
+ * process-identity-probe.mjs layers a win32 creation-time token on top, and
51
+ * host-meta lease identity uses this function directly (issue #112).
50
52
  * @param {number|null|undefined} pid
51
53
  * @returns {string|null}
52
54
  */