@zhuxixi/pi-agent-board 0.13.0 → 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.
@@ -0,0 +1,380 @@
1
+ # Issue #255 — View State Coordinator endpoint zombie
2
+
3
+ Status: draft (round 4 revised after cross-review rounds 1–3; cross-review **converged** — no true gaps)
4
+ Repo: zhuxixi/pi-agent-board · issue #255 · base `79debb6` (v0.13.0)
5
+ Drafted: deepseek-account/deepseek-flash (selected) · deepseek-account/deepseek-flash (physical) @ 2026-10-28T19:36:26+08:00
6
+ Revised: deepseek-account/deepseek-flash (selected) · deepseek-account/deepseek-flash (physical) @ 2026-10-28T19:52:00+08:00 — merged recon rounds 2–3
7
+ Revised: deepseek-account/deepseek-flash (selected) · deepseek-account/deepseek-flash (physical) @ 2026-10-28T21:12:00+08:00 — round-1 cross-review: accepted R1-G1..G5 + R1-D1..D6 (all)
8
+ Revised: deepseek-account/deepseek-flash (selected) · deepseek-account/deepseek-flash (physical) @ 2026-10-28T21:20:00+08:00 — round-2 cross-review: accepted R2-G1/G2 + R2-D1..D4; re-ordered R1/R2 as contract-restoration vs primary self-heal after the R2-D3 physical critique
9
+ Revised: deepseek-account/deepseek-flash (selected) · deepseek-account/deepseek-flash (physical) @ 2026-10-28T21:28:00+08:00 — round-3 cross-review: accepted R3-G1 + R3-D1..D7 (all)
10
+ Revised: deepseek-account/deepseek-flash (selected) · deepseek-account/deepseek-flash (physical) @ 2026-10-28T21:36:00+08:00 — round-4 convergence: R4-D1 (A6 command pattern) + R4-D2 (status metadata)
11
+
12
+ ## 1. Problem
13
+
14
+ A live View State Coordinator can end up serving an endpoint that no longer exists on
15
+ disk. It keeps the `<_coordinator>` lease and keeps heartbeating, so `ensureCoordinator()`
16
+ treats it as healthy-busy, but every client connect fails with ENOENT and the caller
17
+ reports `state_command_not_applied … coordinator_unavailable`. Rows freeze at their last
18
+ materialized state with no user-visible error. Observed on macOS/APFS; manual recovery
19
+ required `kill <pid>`.
20
+
21
+ ## 2. Goals / constraints
22
+
23
+ - G1 A deposed coordinator must never be able to delete an endpoint it no longer owns
24
+ (restore #70's owner-token half of the cleanup contract).
25
+ - G2 A lease holder whose endpoint vanished or was replaced must stop claiming to serve
26
+ and must step down, so the next `ensureCoordinator()` can spawn a replacement. This is
27
+ the **primary** guarantee: it heals socket loss from *any* cause, including causes not
28
+ yet identified (§3.2). POSIX-only (see §4.3).
29
+ - G3 No new background timers, no new protocol messages, no diagnostics that can recreate
30
+ a deleted board root beyond the residue #241 already accepts, and no wire change.
31
+ - G4 Correct existing behaviour stays: SIGTERM on a healthy owner still unlinks its own
32
+ endpoint (new `#255 A6`), a forced-touch-failure step-down still unlinks (A14), root-gone
33
+ step-down still writes no diagnostic.
34
+ - G5 The cleanup fix restores an **existing** repo contract rather than inventing one:
35
+ #70's `cleanupOwnedSocket()` ("dev/ino match **and** owner token match, else no-op",
36
+ `docs/superpowers/specs/2026-09-05-pty-host-stacking-sock-race-design.md:418`).
37
+
38
+ ## 3. Root cause
39
+
40
+ ### 3.1 Confirmed by source (79debb6)
41
+
42
+ Facts, reconstructed from `runner/state-coordinator.mjs` (`:298-303`, `:344-421`),
43
+ `src/core/locks.mjs` (`:302-332`, `:372-419`, `:484-519`), `src/core/host-coordination.mjs`
44
+ (`:160-162`) and `src/core/coordinator-client.mjs` (`:488-527`), cross-checked against the
45
+ issue's `views/_coordinator/diagnostics.jsonl` timeline:
46
+
47
+ 1. **A stale reclaim can happen while the old owner is still alive.** `reclaimOrBlock` can
48
+ return `reclaim` for a declared lease whose heartbeat file reads as missing:
49
+ `classifyLeaseOwner` falls back to `heartbeatAgeMs ?? lockAgeMs` and reclaims at
50
+ `>= max(60 s, 3×heartbeatMs)` (locks.mjs:318-320, issue #224 D3). The old owner's lock
51
+ directory is renamed to quarantine, so its `touch()` immediately fails
52
+ (`stillOwns()` can no longer read its `owner.json`, locks.mjs:487-508).
53
+ 2. **The old owner stays up for 3 more seconds.** `heartbeatFailureAction` only steps down
54
+ after `MAX_CONSECUTIVE_TOUCH_FAILURES = 3` supervised failures at 1 s cadence
55
+ (locks.mjs:155, 472). Deterministic: the observed 3.001 s is D4's designed behaviour.
56
+ 3. **The successor boots and binds its own socket at the same path** (state-coordinator.mjs:298-303
57
+ unlinks the leftover first; libuv's `uv_pipe_bind` additionally pre-unlinks an existing path).
58
+ 4. **The deposed owner's `shutdown()` deletes the successor's socket through libuv.** The old
59
+ code calls `server.close()` on exit; libuv unlinks the unix-socket path captured at
60
+ `bind()` time, unconditionally (`nodejs/node#19729`: "if your old process calls
61
+ `server.close()` afterwards, it will unlink your *new* socket"). The deposed owner's dev+ino
62
+ comparison never enters into it — the deletion happens inside libuv. **This is the root
63
+ cause**, and it explains the evidence that looked like inode reuse: `lsof` shows the
64
+ successor listening on an inode that `ls` no longer shows.
65
+ 5. **Nothing heals it.** `ensureCoordinator` probes the missing path (null) → spawns one
66
+ replacement → the replacement loses the lease race to the zombie (fresh heartbeat ⇒
67
+ `busy`) → writes `coordinator_lease_unavailable` → exits 0 → the ~10 s poll window
68
+ expires → `coordinator_unavailable`. `launchCoordinator` never re-spawns, and the
69
+ client has no "endpoint unreachable while the lease looks healthy" shape detector.
70
+
71
+ Two structural gaps (confirmed): inside `shutdown()`, `lease.release()` is token-fenced but
72
+ the endpoint cleanup is not; and the cleanup leans on `server.close()`, whose libuv side
73
+ effect deletes whatever occupies the bind path. One guarded resource, one unguarded, one
74
+ implicit and unobservable from the project code.
75
+
76
+ ### 3.2 Inferred vs unknown
77
+
78
+ - **Root cause: libuv's close-time unlink (`nodejs/node#19729`).** A coordinator that closes
79
+ its listener deletes whatever currently occupies its bind path — including a successor's
80
+ endpoint. No inode reuse is needed, and the earlier inode-reuse hypothesis is superseded: it
81
+ is physically implausible (round-2 review: the deposed owner's listener fd keeps the old
82
+ inode alive, so the successor's `bind()` cannot reuse it). The Linux CI run of the new A3/A5
83
+ cases confirmed the libuv mechanism — both failed with the endpoint gone while the code
84
+ under test had already gated its own explicit unlink.
85
+ - **The two reclaims in the issue timeline have different (and partly mundane) readings:**
86
+ - `11:10:22, heartbeatAgeMs: 338, lockAgeMs: 346, eligibility: "declared"` — the declared
87
+ heartbeat branch cannot fire at 338 ms (`>= 60_000` required), but `eligibility` only
88
+ records the *record shape*, not which branch fired. The most mundane reading is the
89
+ **normal D1 crash reclaim**: the previous holder stopped touching ~8 ms before its lock
90
+ was inspected and `isProcessDead(pid)` was true (locks.mjs:325-327), which reclaims
91
+ regardless of heartbeat age. Treat "a healthy holder was reclaimed" as open until the
92
+ raw JSONL + pid-liveness evidence is available.
93
+ - `11:20:40, heartbeatAgeMs: null, eligibility: "declared", lockAge >= 60 s` — fully
94
+ explained by D3's declared fallback to lock age (a live holder whose heartbeat read
95
+ failed). Candidate mechanism (unproven, untested): `makeLease.touch()` overwrites the
96
+ heartbeat with a plain in-place `fs.writeFileSync` (locks.mjs:503, no temp+rename), so a
97
+ concurrent POSIX reader can observe a truncated file → `JSON.parse` throws →
98
+ `readLeaseHeartbeat` → null. Reclaim-audit input (R4), not a claimed trigger.
99
+ - #104 introduced the coordinator socket cleanup in one commit (`b022a7b`, 2026-09-09), never
100
+ touched since (`git blame` all `b022a7b`); #224 never considered endpoint self-checks (not
101
+ rejected — out of scope); #241 only added another reason to enter `shutdown()` (it guards
102
+ the root directory inode, which an inner-file unlink never changes); #239 proved the
103
+ client cannot infer liveness from a failed probe.
104
+
105
+ ## 4. Fix design
106
+
107
+ ### 4.1 Decision table
108
+
109
+ | # | Candidate | Verdict | Why |
110
+ | --- | --- | --- | --- |
111
+ | R2 | Supervise the bound endpoint in the existing 1 s heartbeat tick; step down when missing/replaced | **Do — primary self-heal** | Heals socket loss from any cause; reuses the #241 tick, no new timer; POSIX-only (§4.3) |
112
+ | R1 | Stop the implicit libuv unlink (never call `server.close()`) **and** restore the #70 cleanup contract (unlink only when the lease is still ours **and** the path still carries the inode we bound) | **Do — root-cause fix** | Removes the deletion path that actually created the zombie (§3.1 step 4); restores an existing spec'd invariant |
113
+ | R3 | Client kills a zombie lease owner before respawn | **No (non-goal)** | R2 caps the zombie window at one tick; #239 established `probe null ≠ dead`, so a client kill needs a boot-grace heuristic that would race the normal 1-3 s boot |
114
+ | R4 | Audit reclaim eligibility (declared fallback, torn heartbeat read) | **No (follow-up issue)** | Needs the reporter's raw JSONL + pid liveness; changing #224 D3 is a separate contract decision |
115
+ | R5 | Same guard in `runner/pty-runner.mjs` (ownedMain finishHost `:736-743` has dev+ino only; legacy `shutdown()` `:512` is unconditional; both close their listener → same libuv issue) | **No (follow-up issue)** | Different ownership model (per-view host record); own design + tests |
116
+ | R6 | Re-derive dropped `agent_end` projections at reconcile | **No (follow-up issue)** | Orthogonal recovery gap |
117
+
118
+ ### 4.2 R1 — stop the implicit unlink, restore the cleanup contract
119
+
120
+ Two changes in `shutdown()`:
121
+
122
+ 1. **Do not call `server.close()`.** libuv unlinks the bind path when the listening handle
123
+ closes (`nodejs/node#19729`). The process exits immediately afterwards, and
124
+ `process.exit()` skips the uv handle cleanup, so the implicit unlink never runs. Cleanup
125
+ becomes explicit.
126
+ 2. **Gate the explicit unlink** with `shouldUnlinkEndpoint`.
127
+
128
+ Pure function, added next to `ownsEndpoint` in `src/core/host-coordination.mjs`:
129
+
130
+ ```js
131
+ /**
132
+ * Whether this instance may unlink the endpoint path now.
133
+ * Restores the #70 cleanup contract: the path must still be the inode this
134
+ * instance bound AND this instance must still own the lease. `compromised`
135
+ * lets the supervised tick veto its own cleanup after detecting that the
136
+ * endpoint is gone/replaced (issue #255).
137
+ */
138
+ export function shouldUnlinkEndpoint({ stillOwner, compromised, bound, current }) {
139
+ if (!stillOwner || compromised) return false;
140
+ return ownsEndpoint(bound, current);
141
+ }
142
+ ```
143
+
144
+ `state-coordinator.mjs` shell changes:
145
+
146
+ - add `let endpointCompromised = false;` next to `boundSocketIdentity`;
147
+ - **remove `try { server.close(); } catch {}`** from `shutdown()` (with the nodejs/node#19729
148
+ comment), so no implicit libuv unlink can run;
149
+ - before the explicit unlink:
150
+ ```js
151
+ const stillOwner = safeIsOwner(); // lease.isOwner(); false on any throw
152
+ if (process.platform !== "win32" && stillOwner && !endpointCompromised && boundSocketIdentity) {
153
+ try {
154
+ const st = statSync(socketPath);
155
+ if (shouldUnlinkEndpoint({ stillOwner, compromised: endpointCompromised,
156
+ bound: boundSocketIdentity, current: { dev: st.dev, ino: st.ino } })) {
157
+ try { unlinkSync(socketPath); } catch { /* best effort */ }
158
+ }
159
+ } catch { /* path gone — nothing to clean */ }
160
+ }
161
+ ```
162
+ then `lease.release()` as today. `safeIsOwner` reads `lease.isOwner()` and returns false
163
+ on any throw (fail-closed: skip the unlink; the next boot's *boot-time site* unlink cleans
164
+ a leftover file).
165
+
166
+ Behaviour matrix:
167
+
168
+ | Scenario | stillOwner | compromised | unlink? |
169
+ | --- | --- | --- | --- |
170
+ | SIGTERM/SIGINT on healthy owner | true | false | yes (shutdown-time site) — new `#255 A6` pins it |
171
+ | Forced-touch-failure step-down, no reclaim (A14) | true | false | yes — regression, **no test change needed** |
172
+ | Step-down after the lease moved to a successor | false | n/a | no — R1 contract restoration (§4.2); not the reported trigger (§3.2) |
173
+ | Tick detected missing/replaced endpoint (R2) | true or false | true | no — the primary self-heal path |
174
+ | Root-gone step-down | true | false | stat ENOENT → no-op |
175
+ | owner.json unreadable during shutdown | unknown → false | — | no (fail-closed) |
176
+
177
+ ### 4.3 R2 — supervised endpoint health
178
+
179
+ Two pure functions in `host-coordination.mjs`, with an explicit three-state observation
180
+ (`R1-G1`: a bare string sentinel would make `ownsEndpoint` treat the sentinel as
181
+ `"replaced"`), plus an exported classifier for the shell's stat→observation mapping
182
+ (`R2-D2`: the "transient error never kills a healthy coordinator" guarantee needs a unit
183
+ test, so the mapping must live in the pure module, not in an unexported shell function):
184
+
185
+ ```js
186
+ /**
187
+ * Map one stat attempt to the supervised observation discriminator.
188
+ * `errorCode === null` means the stat succeeded.
189
+ * @param {{dev:number,ino:number}|null} stat
190
+ * @param {string|null} errorCode
191
+ * @returns {{kind:"ok",dev:number,ino:number}|{kind:"missing"}|{kind:"unknown"}}
192
+ */
193
+ export function socketIdentityObservation(stat, errorCode) {
194
+ if (stat) return { kind: "ok", dev: stat.dev, ino: stat.ino };
195
+ return errorCode === "ENOENT" ? { kind: "missing" } : { kind: "unknown" };
196
+ }
197
+
198
+ /**
199
+ * Classify the supervised endpoint against the identity bound at boot.
200
+ * @param {{dev:number,ino:number}|null} bound
201
+ * @param {{kind:"ok",dev:number,ino:number}|{kind:"missing"}|{kind:"unknown"}|null} observed
202
+ * @returns {"ok"|"missing"|"replaced"|"unknown"}
203
+ */
204
+ export function classifyEndpointHealth(bound, observed) {
205
+ if (!bound || !observed || observed.kind === "unknown") return "unknown";
206
+ if (observed.kind === "missing") return "missing";
207
+ return ownsEndpoint(bound, observed) ? "ok" : "replaced";
208
+ }
209
+ ```
210
+
211
+ Shell: in the existing `heartbeatTimer` tick (state-coordinator.mjs:344), **after**
212
+ `rootVanishedOrReplaced` and **before** `lease.touch()`:
213
+
214
+ ```js
215
+ const observation = statSocketObservation(socketPath); // shell: statSync + error code
216
+ const endpointState = classifyEndpointHealth(boundSocketIdentity, observation);
217
+ if (endpointState === "missing" || endpointState === "replaced") {
218
+ endpointCompromised = true; // veto cleanup in shutdown (R1)
219
+ try {
220
+ appendCoordinatorDiagnostic("coordinator_endpoint_lost",
221
+ { state: endpointState }, "warn");
222
+ } catch { /* a failing diagnostic must not block the step-down (#224 D4) */ }
223
+ process.stderr.write(`state-coordinator: endpoint ${endpointState} (${socketPath}); stepping down\n`);
224
+ shutdown(0);
225
+ return;
226
+ }
227
+ ```
228
+
229
+ with the shell helper `statSocketObservation(socketPath)` doing the single `statSync` and
230
+ delegating the classification to `socketIdentityObservation(statOrNull, errCodeOrNull)`.
231
+
232
+ Details that matter:
233
+
234
+ - `unknown` never steps down (degrades to today's behaviour).
235
+ - **The diagnostic is safe only to the same degree #241 accepts**: the root guard ran first
236
+ with the boot identity, but `captureRootIdentity()` degrades to existence-only when ino is
237
+ 0/unavailable, and a delete landing between the guard and the append can leave a directory
238
+ skeleton (exactly the #241-accepted residue: data, not a process).
239
+ - **R2 is POSIX-only.** `boundSocketIdentity` is captured only when
240
+ `process.platform !== "win32"` (state-coordinator.mjs:333-339), so on win32 the classifier
241
+ returns `unknown` forever. Deliberate degrade: Windows endpoints are named pipes with no
242
+ unlink/inode semantics; equivalent pipe liveness belongs to #104/#70, not this issue.
243
+ - **`boundSocketIdentity == null` also degrades R2 to a no-op on POSIX** (the existing
244
+ listen-callback `statSync` failed; the code already says "cleanup degrades to no-op"). The
245
+ tick then never steps down. To keep that from being silent, the same catch emits one
246
+ stderr line (`state-coordinator: endpoint identity unavailable (…); self-supervision
247
+ disabled`); A2 pins the pure-function behaviour (`null bound ⇒ unknown ⇒ never step down`).
248
+ - Step-down, not rebind: keeps the path a pure shutdown; a successor binds on the next
249
+ `ensureCoordinator()` call. Rebinding inside the tick would reopen the "who owns the path"
250
+ ambiguity (§9 Q4).
251
+
252
+ ### 4.4 End-to-end effect and its boundaries
253
+
254
+ 1. Old owner A is stale-reclaimed while alive → its `touch()` fails deterministically.
255
+ 2. Successor B boots: unlinks A's leftover socket (*boot-time site*) and binds. A still
256
+ listens on the orphaned inode but every new client reaches B.
257
+ 3. A's 3rd failed touch → `shutdown(0)`: `lease.isOwner()` is false → R1 suppresses the
258
+ unlink. This closes one unguarded path; whether it is the path that produced the report
259
+ is unknown (§3.2).
260
+ 4. If the endpoint disappears or is replaced for **any** reason, B's next tick sees
261
+ `missing`/`replaced` → R2 steps down with `coordinator_endpoint_lost` → the next
262
+ `ensureCoordinator()` acquires the released lease → fresh coordinator binds. **The
263
+ process vacates within ≤1 tick. The state_command that raced this window can still fail**
264
+ (the replacement spawned by that call loses the lease race and exits 0;
265
+ `launchCoordinator` never retries, so the caller waits out `ENSURE_WINDOW_MS` ≈ 10 s and
266
+ reports `coordinator_unavailable`). Recovery lands on the next command (§7-2).
267
+
268
+ **The fix does not retroactively heal.** A coordinator already in the zombie state at
269
+ upgrade time still holds a fresh lease; the client probes ENOENT, spawns, loses the lease
270
+ race, and the new R2 never gets a chance to run because the old (old-code) process is never
271
+ asked. Such an install must `kill` the old coordinator once; from then on R2 self-heals.
272
+
273
+ ## 5. Testability split (可测性拆分设计)
274
+
275
+ | Unit under test | Layer | Why pure |
276
+ | --- | --- | --- |
277
+ | `shouldUnlinkEndpoint({stillOwner, compromised, bound, current})` | `src/core/host-coordination.mjs` (pure export) | plain data only, no fs |
278
+ | `socketIdentityObservation(stat, errorCode)` | `src/core/host-coordination.mjs` (pure export) | maps one stat attempt; covers the EACCES/unknown branch that R2-D2 requires |
279
+ | `classifyEndpointHealth(bound, observed)` | `src/core/host-coordination.mjs` (pure export) | plain data only |
280
+ | `statSocketObservation(socketPath)` | `runner/state-coordinator.mjs` I/O shell (not exported) | one stat call; classification delegated to the pure mapper |
281
+ | `safeIsOwner()` | `runner/state-coordinator.mjs` I/O shell | one lease read; fenced |
282
+
283
+ Testing boundaries:
284
+ - Pure functions: `test/host-coordination.test.mjs` — exhaustive truth tables, no spawn,
285
+ every platform.
286
+ - Tick + shutdown wiring: `test/state-coordinator.integration.test.mjs` — real spawned
287
+ coordinator, temp root, POSIX-only assertions guarded by `process.platform !== "win32"`
288
+ (same style as A14 at :1274). New case titles MUST be prefixed `#255 A<n>: …` so
289
+ `--test-name-pattern` can select them.
290
+ - **A3's discriminating fixture (the one that can falsify R1):** start A, wait ready, assert
291
+ the endpoint file exists (guard against the #70 vacuous assertion), pin
292
+ `AGENT_BOARD_TEST_COORDINATOR_HEARTBEAT_MS` explicitly (default 1000), then **delete A's
293
+ lease directory** (simulating "the lease moved elsewhere / was quarantined") while leaving
294
+ A's socket untouched. A's next three touches fail (`stillOwns()` false) and it exits 0
295
+ after ~3 heartbeats. Two decidable assertions: (1) immediately after deleting the lease
296
+ directory, assert the endpoint file still exists (anti-vacuous precondition); (2) after
297
+ `waitForExit`, assert **it still exists**:
298
+ - old code: no `stillOwner` gate, `ownsEndpoint(bound, current)` is true (A's own inode
299
+ never changed) → unlinks → assertion fails ⇒ **red test**;
300
+ - fixed code: `stillOwner` false → keeps the file ⇒ green.
301
+ No inode reuse, no successor. A14 asserts the mirror case (socket gone when the lease was
302
+ not revoked); together they pin the token condition.
303
+ - **A5's replaced fixture must be atomic** (R2-G2): bind the stand-in on a temp path first,
304
+ then `renameSync(tmp, socketPath)` — the deposed owner's old inode is still held by its own
305
+ listener fd, so the replacement inode is guaranteed different and the tick can never
306
+ observe an intermediate `missing`. **The temp path MUST live inside `<root>`** (same
307
+ filesystem: `rename(2)` throws EXDEV across mounts), e.g. `<root>/.standin-<pid>.sock`.
308
+ Pin the heartbeat knob and, before asserting, read `statSync(socketPath).ino` to prove the
309
+ inode really changed.
310
+ - **No CI-constructible test can exercise the hypothesised inode-reuse trigger itself**
311
+ (APFS-only physics, and §3.2 doubts it). R2's missing/replaced paths are tested with a
312
+ deleted endpoint and an atomically replaced stand-in; the trigger-cause investigation is
313
+ U1 + R4.
314
+ - Dual-owner handoff (optional smoke, not a gate): spawn A, delete A's lease, spawn B, assert
315
+ B binds and answers a ping while A exits. Kept out of the acceptance gate because it
316
+ cannot falsify R1 without inode reuse.
317
+
318
+ ## 6. Acceptance matrix
319
+
320
+ | ID | Functional point | Verification | Command / steps | Pass criteria |
321
+ | --- | --- | --- | --- | --- |
322
+ | A1 | `shouldUnlinkEndpoint` truth table | 自动化验证(unit) | `npm test` (host-coordination suite) / `node --test test/host-coordination.test.mjs` | 8 combinations (`stillOwner` × `compromised` × match) + 2 null-degenerate rows: only owner=true, compromised=false, match=true ⇒ true |
323
+ | A2 | `socketIdentityObservation` + `classifyEndpointHealth` truth tables | 自动化验证(unit) | `node --test test/host-coordination.test.mjs` | observation: success ⇒ ok+dev/ino; ENOENT ⇒ missing; EACCES/ELOOP/anything else ⇒ unknown. classify: null bound ⇒ unknown; `{kind:"unknown"}` ⇒ unknown; `{kind:"missing"}` ⇒ missing; different dev/ino ⇒ replaced; equal ⇒ ok |
324
+ | A3 | Deposed owner (lease gone, endpoint unchanged) keeps its own socket | 自动化验证(integration, POSIX) | `node --test --test-name-pattern="#255 A3" test/state-coordinator.integration.test.mjs` | pin heartbeat; delete A's lease dir; A exits 0; **A's socket file still exists** (assert present before exit; old code fails this) |
325
+ | A4 | Missing endpoint ⇒ supervised step-down | 自动化验证(integration, POSIX) | `node --test --test-name-pattern="#255 A4" test/state-coordinator.integration.test.mjs` | unlink the endpoint under a ready A (heartbeat pinned); A exits 0 within bounded ticks; `coordinator_endpoint_lost` with `state:"missing"`; lease released |
326
+ | A4b | A failing diagnostic write must not block the step-down | 自动化验证(integration, POSIX) | `node --test --test-name-pattern="#255 A4b" test/state-coordinator.integration.test.mjs` | `AGENT_BOARD_TEST_FAIL_DIAGNOSTIC=1` + unlink endpoint ⇒ still exits 0, lease released |
327
+ | A5 | Replaced endpoint ⇒ step-down, replacement not unlinked | 自动化验证(integration, POSIX) | `node --test --test-name-pattern="#255 A5" test/state-coordinator.integration.test.mjs` | atomic rename of a stand-in bound **inside `<root>`** (same filesystem; heartbeat pinned); assert `statSync` ino changed; A exits 0; `state:"replaced"`; stand-in file still present; old code fails this. Note: the `compromised` veto checked by this case is defence in depth — a genuinely different inode is already refused by the dev+ino comparison, so this case pins R2's step-down + endpoint survival; the veto's own truth table is pinned by A1 |
328
+ | A6 | Healthy SIGTERM still unlinks its own endpoint (regression) | 自动化验证(integration, POSIX) | `node --test --test-name-pattern="#224 A14|#255 A6" test/state-coordinator.integration.test.mjs` | A14/A14b unchanged and green; new `#255 A6`: SIGTERM ⇒ exit 0, endpoint absent after exit |
329
+ | A7 | Root-gone step-down still writes no diagnostic/state | 自动化验证(integration, POSIX) | `node --test --test-name-pattern="A3|A4" test/coordinator-lifecycle.test.mjs` | existing #241 assertions unchanged, including A3's "root stays deleted after the self-exit" (:374) — the assertion that proves no diagnostic/state write; A3/A3b/A3c/A4 all match and run |
330
+ | A8 | Dual-owner handoff smoke (B serves after A vacates) | 自动化验证(integration, POSIX, non-gating smoke) | `node --test --test-name-pattern="#255 A8" test/state-coordinator.integration.test.mjs` | B answers a ping after A exits; not a PR gate (cannot falsify R1 without inode reuse) |
331
+ | A9 | Type contract | 自动化验证(static) | `npm run typecheck` | exit 0 |
332
+ | A10 | No collateral breakage | 自动化验证(unit+integration) | `npm run test:coverage` | all pass; thresholds lines 85 / funcs 80 / branches 70 |
333
+ | A11 | Perf gate unaffected | 自动化验证(build/perf) | `npm run test:perf` | passes |
334
+ | A12 | Full pre-PR gate | 自动化验证(static+build+test) | `npm run verify` | exit 0 |
335
+ | U1 | Socket-loss observation on the reporter's macOS box | 用户实测 | **前置**:merge 后 `git pull` 到含 fix 的 commit;`pkill -f runner/state-coordinator.mjs`(旧 detached 进程不随 Pi 重启退出);触发一次 ensure 让新代码 coordinator 成为租约主;确认 `lsof -p <新 pid>` 路径与 `ls` 一致。**执行**:24 h 观察;记录 `views/_coordinator/diagnostics.jsonl`;每次 endpoint 丢失时采集**谁 unlink 了它**的证据(`lsof`/`fs_usage`/外部清理脚本排查)。inode 复用不可按需制造。 | 24 h 内 `coordinator_unavailable` 次数 ≤ 基线(先记录基线);有 coordinator 时 `ls` 与 `lsof` 一致;**条件判据**:若 24 h 内发生 endpoint 丢失,须附至少一次归因证据;若未发生丢失,本条记 N/A,以前两条为准;若出现 `coordinator_endpoint_lost`,其后下一次操作应恢复 |
336
+ | U2 | Zombie recovery without manual kill | 用户实测 | **前置**:同 U1(必须先 kill 旧 coordinator,否则测的是旧代码)。**执行**:对一个运行中的新代码 coordinator `rm <root>/coordinator.sock`;立即触发一次 dashboard 操作并等待其返回(允许一次 `coordinator_unavailable`);再触发第二次 | 第二次操作在本次 `ENSURE_WINDOW_MS`(10 s)内成功应用;`coordinator_endpoint_lost` 出现一次;全程无需 `kill` |
337
+
338
+ ## 7. Non-goals (tracked separately)
339
+
340
+ 1. **Identify the actual unlink cause / reclaim-eligibility audit** — declared fallback
341
+ (#224 D3), torn heartbeat write, external unlink. Needs raw JSONL + pid liveness + FS
342
+ evidence (§3.2).
343
+ 2. **Accepted residual: the command that races the step-down can still fail once** (the
344
+ single-shot spawn loses the lease race; §4.4). Recovery lands on the next command.
345
+ 3. **Dual-writer window during stale reclaim** (≤3 s) — accepted residual.
346
+ 4. **`pty-runner.mjs` endpoint cleanup** (ownedMain finishHost is dev+ino-only; the legacy
347
+ shutdown path is unconditional) — different ownership model, own issue.
348
+ 5. **Client-side zombie killer / boot-grace heuristic** — superseded by R2 here.
349
+ 6. **Re-projection of `agent_end` events dropped during an outage.**
350
+ 7. **R2 on win32** — no inode identity exists; named-pipe liveness is #104/#70 territory.
351
+
352
+ ## 8. Risks / rollback
353
+
354
+ | Risk | Mitigation |
355
+ | --- | --- |
356
+ | `lease.isOwner()` throws during shutdown | `safeIsOwner()` → false (fail-closed; next boot's *boot-time site* unlink cleans a leftover) |
357
+ | Classifier reads a transient stat error as replaced | exported `socketIdentityObservation` maps only ENOENT → missing; A2 pins EACCES/ELOOP |
358
+ | Diagnostic write throws in the tick | fenced `try/catch` (same shape as :390-392); A4b pins it |
359
+ | Delete-window skeleton on the diagnostic append | same residue #241 already accepted (skeleton directory, never a process) |
360
+ | A14 regression | run A14/A14b by name before the full suite; A14's lease is not revoked so `stillOwner` stays true |
361
+ | Step-down loop | each step-down releases the lease; the successor binds before the next tick; `coordinator_endpoint_lost` makes a loop visible |
362
+ | Rollback | revert two source files (`src/core/host-coordination.mjs`, `runner/state-coordinator.mjs`) + two test files (`test/host-coordination.test.mjs`, `test/state-coordinator.integration.test.mjs`); no persisted state or wire-format change |
363
+
364
+ ## 9. Open questions for cross-review
365
+
366
+ 1. Does A3 + A1 adequately pin R1 in CI given the §3.2 physical objection? (Current answer:
367
+ they pin the *gate logic*; the trigger itself needs U1/R4.)
368
+ 2. Diagnostic name `coordinator_endpoint_lost` — consistent with
369
+ `coordinator_heartbeat_lost` / `coordinator_lease_unavailable`? Naming only.
370
+ 3. Should A8 (handoff smoke) be kept, or is it noise without inode reuse?
371
+ 4. Step-down vs rebind on endpoint loss — decision recorded in §4.3.
372
+ 5. Is "delete the lease directory" the right fixture for A3, or should a second case go
373
+ through the real reclaim path (#224 A10 pattern: fabricated stale `startedAt`)? The
374
+ delete fixture is deterministic and tests R1's gate; the A10 pattern also exercises
375
+ `lease_reclaimed`.
376
+ 6. Given §3.2, is the issue's title/root-cause framing ("live lease holder serves an
377
+ unlinked socket") still the right scope, or should this PR be split into "self-heal
378
+ (R2)" + "contract restoration (R1)" + "cause investigation (R4)" as separate issues?
379
+ Current plan keeps one PR because both changes are small and the acceptance matrix
380
+ covers both; R4 is tracked as a follow-up.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zhuxixi/pi-agent-board",
3
- "version": "0.13.0",
3
+ "version": "0.13.1",
4
4
  "description": "Agent-board dashboard for Pi: dispatch, monitor, peek/reply, and attach to background Pi sessions.",
5
5
  "type": "module",
6
6
  "main": "./index.ts",
@@ -54,7 +54,7 @@ import {
54
54
  repairJournalTail,
55
55
  writeCheckpoint,
56
56
  } from "../src/core/coordinator-journal.mjs";
57
- import { ownsEndpoint } from "../src/core/host-coordination.mjs";
57
+ import { classifyEndpointHealth, shouldUnlinkEndpoint, socketIdentityObservation } from "../src/core/host-coordination.mjs";
58
58
  import { appendDiagnostic } from "../src/core/diagnostics.mjs";
59
59
  import { acquireOwnedViewLock, describeLeaseConflict, heartbeatFailureAction, withViewLockSync } from "../src/core/locks.mjs";
60
60
  import { captureStartToken } from "../src/core/pid.mjs";
@@ -303,6 +303,10 @@ async function main() {
303
303
  }
304
304
  /** {dev,ino} recorded at bind time; cleanup unlinks only this exact inode. */
305
305
  let boundSocketIdentity = null;
306
+ /** Set by the supervised tick when the bound endpoint is gone or replaced:
307
+ * shutdown must then leave the path alone even while the lease still looks
308
+ * ours (issue #255). */
309
+ let endpointCompromised = false;
306
310
 
307
311
  const server = createServer((socket) => {
308
312
  let buffer = "";
@@ -335,7 +339,11 @@ async function main() {
335
339
  try {
336
340
  const st = statSync(socketPath);
337
341
  boundSocketIdentity = { dev: st.dev, ino: st.ino };
338
- } catch { /* without the identity, cleanup degrades to no-op */ }
342
+ } catch (err) {
343
+ // Without the bind identity both endpoint cleanup and self-supervision
344
+ // degrade to a no-op; say so instead of failing silently (issue #255).
345
+ process.stderr.write(`state-coordinator: endpoint identity unavailable (${err instanceof Error ? err.message : String(err)}); self-supervision disabled\n`);
346
+ }
339
347
  }
340
348
  // Supervision starts only after the endpoint is bound (issue #224 D4):
341
349
  // a live-but-stuck holder must step down before its lease can be
@@ -374,6 +382,28 @@ async function main() {
374
382
  shutdown(0);
375
383
  return;
376
384
  }
385
+ // Self-supervise the endpoint (issue #255): a lease holder whose socket
386
+ // vanished or was replaced serves nobody — every client write fails with
387
+ // ENOENT while its fresh heartbeat keeps replacement coordinators losing
388
+ // the lease race. Step down so the next ensureCoordinator() binds a fresh
389
+ // endpoint. MUST stay after the root guard: a diagnostic append for a
390
+ // deleted root would recreate the directory skeleton (#241). `unknown`
391
+ // (transient stat error, or no bound identity) never steps a holder down.
392
+ // Short-circuit on the bound identity: without it (win32 named pipe, or a
393
+ // failed bind-time stat) there is nothing to compare against, and skipping
394
+ // the stat also avoids win32's non-trivial pipe stat side effects.
395
+ const endpointState = boundSocketIdentity
396
+ ? classifyEndpointHealth(boundSocketIdentity, statSocketObservation(socketPath))
397
+ : "unknown";
398
+ if (endpointState === "missing" || endpointState === "replaced") {
399
+ endpointCompromised = true; // veto endpoint cleanup in shutdown (R1)
400
+ try {
401
+ appendCoordinatorDiagnostic("coordinator_endpoint_lost", { state: endpointState }, "warn");
402
+ } catch { /* a failing diagnostic must not block the step-down (#224 D4) */ }
403
+ process.stderr.write(`state-coordinator: endpoint ${endpointState} (${socketPath}); stepping down\n`);
404
+ shutdown(0);
405
+ return;
406
+ }
377
407
  let ok;
378
408
  try {
379
409
  ok = process.env.AGENT_BOARD_TEST_FORCE_TOUCH_FAILURE === "1" ? false : lease.touch();
@@ -403,15 +433,42 @@ async function main() {
403
433
  process.on("SIGTERM", () => shutdown(0));
404
434
  process.on("SIGINT", () => shutdown(0));
405
435
 
436
+ /** One stat attempt, classified into the supervised observation discriminator.
437
+ * A transient access error is `unknown`, never `missing`/`replaced` (issue #255). */
438
+ function statSocketObservation(path) {
439
+ let stat = null;
440
+ let errorCode = null;
441
+ try {
442
+ stat = statSync(path);
443
+ } catch (err) {
444
+ errorCode = /** @type {NodeJS.ErrnoException} */ (err)?.code ?? "UNKNOWN";
445
+ }
446
+ return socketIdentityObservation(stat, errorCode);
447
+ }
448
+
449
+ /** Lease ownership at cleanup time; a read failure fails closed (no unlink). */
450
+ function safeIsOwner() {
451
+ try { return lease.isOwner(); } catch { return false; }
452
+ }
453
+
406
454
  function shutdown(code) {
407
455
  if (shuttingDown) return;
408
456
  shuttingDown = true;
409
457
  try { clearInterval(heartbeatTimer); } catch { /* best effort */ }
410
- try { server.close(); } catch { /* already closed */ }
411
- if (process.platform !== "win32" && boundSocketIdentity) {
458
+ // Do NOT call server.close() (issue #255, nodejs/node#19729): libuv unlinks the
459
+ // unix-socket bind path when the handle closes, so a deposed coordinator closing
460
+ // after a successor bound would delete the successor's endpoint. The process is
461
+ // exiting anyway, and process.exit() skips the uv handle cleanup, so the implicit
462
+ // unlink never runs. Cleanup is explicit and ownership-gated below — the #70
463
+ // contract: unlink only while this instance still holds the lease AND the path
464
+ // still carries the inode it bound.
465
+ // `endpointCompromised` (set by the supervised tick) vetoes that explicit unlink
466
+ // as well; it is defence in depth on top of the dev+ino comparison.
467
+ const stillOwner = safeIsOwner();
468
+ if (process.platform !== "win32" && stillOwner && !endpointCompromised && boundSocketIdentity) {
412
469
  try {
413
470
  const st = statSync(socketPath);
414
- if (ownsEndpoint(boundSocketIdentity, { dev: st.dev, ino: st.ino })) {
471
+ if (shouldUnlinkEndpoint({ stillOwner, compromised: endpointCompromised, bound: boundSocketIdentity, current: { dev: st.dev, ino: st.ino } })) {
415
472
  try { unlinkSync(socketPath); } catch { /* best effort */ }
416
473
  }
417
474
  } catch { /* path gone — nothing to clean */ }
@@ -161,6 +161,54 @@ export function ownsEndpoint(bound, current) {
161
161
  return Boolean(bound && current && bound.dev === current.dev && bound.ino === current.ino);
162
162
  }
163
163
 
164
+ /**
165
+ * Whether this instance may unlink the endpoint path now.
166
+ * Restores the #70 cleanup contract (docs/superpowers/specs/
167
+ * 2026-09-05-pty-host-stacking-sock-race-design.md:418): the path must still be
168
+ * the inode this instance bound AND this instance must still own the lease.
169
+ * `compromised` lets the supervised tick veto its own cleanup after detecting
170
+ * that the endpoint is gone or replaced (issue #255).
171
+ * @param {{
172
+ * stillOwner: boolean,
173
+ * compromised: boolean,
174
+ * bound: {dev:number,ino:number}|null|undefined,
175
+ * current: {dev:number,ino:number}|null|undefined,
176
+ * }} input
177
+ * @returns {boolean}
178
+ */
179
+ export function shouldUnlinkEndpoint({ stillOwner, compromised, bound, current }) {
180
+ if (!stillOwner || compromised) return false;
181
+ return ownsEndpoint(bound, current);
182
+ }
183
+
184
+ /**
185
+ * Map one supervised stat attempt to the endpoint observation discriminator.
186
+ * A transient stat failure (EACCES/EBUSY/...) must never be read as "replaced":
187
+ * only ENOENT means the endpoint is actually gone (issue #255, mirrors the
188
+ * rootVanishedOrReplaced rule of issue #241).
189
+ * @param {{dev:number,ino:number}|null} stat The successful stat snapshot, or null.
190
+ * @param {string|null} errorCode The stat error code, or null on success.
191
+ * @returns {{kind:"ok",dev:number,ino:number}|{kind:"missing"}|{kind:"unknown"}}
192
+ */
193
+ export function socketIdentityObservation(stat, errorCode) {
194
+ if (stat) return { kind: "ok", dev: stat.dev, ino: stat.ino };
195
+ return errorCode === "ENOENT" ? { kind: "missing" } : { kind: "unknown" };
196
+ }
197
+
198
+ /**
199
+ * Classify the supervised endpoint against the identity bound at boot.
200
+ * `unknown` never steps a holder down: without a bound identity (win32, or a
201
+ * failed bind-time stat) the supervisor degrades to a no-op.
202
+ * @param {{dev:number,ino:number}|null|undefined} bound
203
+ * @param {{kind:"ok",dev:number,ino:number}|{kind:"missing"}|{kind:"unknown"}|null|undefined} observed
204
+ * @returns {"ok"|"missing"|"replaced"|"unknown"}
205
+ */
206
+ export function classifyEndpointHealth(bound, observed) {
207
+ if (!bound || !observed || observed.kind === "unknown") return "unknown";
208
+ if (observed.kind === "missing") return "missing";
209
+ return ownsEndpoint(bound, observed) ? "ok" : "replaced";
210
+ }
211
+
164
212
  /**
165
213
  * Classify a connect+hello probe snapshot into the coordination enum.
166
214
  * Order: connection errors first (they carry the errorCode), then protocol
@@ -269,15 +269,15 @@ export function resolvePasteSelectionSource(value) {
269
269
  }
270
270
 
271
271
  /**
272
- * Issue #174 (B2): whether a normalized mouse event ends a selection gesture
273
- * we should mirror into the X11 PRIMARY selection. Only release/click of the
274
- * left button with native paste enabled (pi's fullscreen selection owns the
275
- * gesture; we observe without consuming). Pure by contract.
272
+ * Issue #174 (B2) / #172: whether a normalized mouse event ends a fullscreen text
273
+ * selection gesture the attach overlay must settle — mirror the selection into X11
274
+ * PRIMARY (#174) and drop pi's highlight once copy-on-select has run (#172). Only
275
+ * release/click of the left button ends a selection in TuiAltScreen; pi owns the
276
+ * gesture, so the overlay observes without consuming. Pure: the native-paste kill
277
+ * switch is applied by writePrimarySelection, not here.
276
278
  */
277
- export function shouldMirrorSelectionToPrimary(event, { nativePasteEnabled }) {
278
- if (!nativePasteEnabled) return null;
279
- if ((event.type === "release" || event.type === "click") && event.button === "left") return "mirror-primary";
280
- return null;
279
+ export function isFullscreenSelectionEnd(event) {
280
+ return (event.type === "release" || event.type === "click") && event.button === "left";
281
281
  }
282
282
 
283
283
  /**
@@ -1352,9 +1352,11 @@ export class DashboardComponent implements Component {
1352
1352
  "space toggle",
1353
1353
  "a all visible",
1354
1354
  "u clear",
1355
- "d move done",
1356
- "ctrl+x delete done",
1357
- "esc cancel",
1355
+ "d done",
1356
+ "ctrl+x delete",
1357
+ "m/esc cancel",
1358
+ "? help",
1359
+ "! pty",
1358
1360
  ]);
1359
1361
  }
1360
1362
  const primary = this.input.trim() ? "enter launch" : live ? "enter attach live" : "enter resume";
@@ -1540,7 +1542,7 @@ export class DashboardComponent implements Component {
1540
1542
  const notice = this.currentInputNotice();
1541
1543
  if (notice) out.push(clip(t.fg(notice.color, `ⓘ ${notice.text}`), width));
1542
1544
  } else {
1543
- out.push(clip(t.fg("dim", "↑↓ prev/next · →/> attach · d done · v transcript · e evidence · r reply · esc back"), width));
1545
+ out.push(clip(t.fg("dim", "↑↓/j/k prev/next · →/l attach · d done · v transcript · e evidence · r reply · esc back"), width));
1544
1546
  }
1545
1547
  return out;
1546
1548
  }
@@ -1713,6 +1715,7 @@ export class DashboardComponent implements Component {
1713
1715
  ["space", "Peek when input is empty; in multi-select: toggle current row"],
1714
1716
  ["e", "Open evidence / diagnostics panel for selected session"],
1715
1717
  ["/", "Filter in normal mode; use i then / for slash commands"],
1718
+ ["?", "Open the key help overlay (list and multi-select)"],
1716
1719
  ["!", "Open node-pty diagnostics and fix steps"],
1717
1720
  ["ctrl+n", "Open the new-session launch dialog (prompt pre-filled)"],
1718
1721
  ["ctrl+r/t/s", "Rename · pin · stop selected"],
@@ -1720,7 +1723,7 @@ export class DashboardComponent implements Component {
1720
1723
  ["ctrl+x x2", "Delete selected session (quick double-press, no confirm)"],
1721
1724
  ["X", "Delete all inactive sessions in selected state"],
1722
1725
  ["v", "Open read-only transcript view"],
1723
- ["In select", "j/k move · a select all · u clear · d move done · ctrl+x delete · esc cancel"],
1726
+ ["In select", "↑↓/j/k move · space toggle · a all · u clear · d done · ctrl+x delete · m/esc cancel"],
1724
1727
  ["In peek", "→/l attach · v transcript · e evidence · r reply · ↑↓/j/k adjacent"],
1725
1728
  ["In session", "← back · ↑↓/j/k scroll · e evidence · enter attach · r reply"],
1726
1729
  ["In evidence", "← back · ↑↓/j/k scroll · →/l attach · r reply · v transcript · x clear diag"],