Skip to content

fix(daemon): let the publisher replace a dead endpoint, not a third party - #12882

Merged
nwparker merged 64 commits into
stablyai:mainfrom
nwparker:nwparker/daemon-stale-cleanup-fencing
Aug 8, 2026
Merged

nwparker merged 64 commits into
stablyai:mainfrom
nwparker:nwparker/daemon-stale-cleanup-fencing

Conversation

@nwparker

@nwparker nwparker commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Every terminal in the app is run by a background helper process — the daemon. Clients find it through one file on disk: a Unix socket at a fixed path. Think of it as the daemon's phone number, written on a sticky note in a known spot.

The bug: when any daemon shut down, Node erased whatever was written on that sticky note — even if a different, healthy daemon had already written its own number there. Node/libuv unlinks the path a server bound to when that server closes, and it never checks whether the file still belongs to it.

So: your old daemon exits, a new one takes over, the old one's exit wipes the new one's number. The new daemon is alive and hosting all your terminals, but nothing can call it. Terminals accept keystrokes and never run them. The user reporting this needed pkill several times a day.

The fix, in one line: a daemon now writes its number on its own private note first, then swaps it into the official slot in a single atomic move — and only after checking that the number already there doesn't answer. Nobody is ever allowed to erase the official note — not a launcher, not a cleanup sweeper, not a departing daemon.

"2,679 lines?" — where it actually goes

The headline number is mostly tests and a design doc. The behaviour change is small:

added removed net
Production logic 460 223 +237
Production comments 243 79 +164
Tests & smokes 1,896 342 +1,554
src/main/daemon/AGENTS.md 50 0 +50

The actual logic change is +237 lines net, across 8 files. It replaces a protocol that three separate actors could mutate with one only the publishing daemon can, which is why it deletes nearly as much as it adds.

Comments were cut from 383 to 243 to match house style — daemon-endpoint-ownership.ts once had more comment lines than code. What's left is the non-obvious "why" on each subtle branch.

The rationale lives in a 50-line src/main/daemon/AGENTS.md, which loads only when an agent works in that directory (the convention tests/e2e/AGENTS.md already sets) rather than costing every agent context on every task. An earlier revision of this PR carried a 480-line reference doc plus a root AGENTS.md entry; both are gone.

Why 8 production files and not 1

The defect wasn't in one function — it was a rule that three actors each broke differently. Each file is where one actor stopped being allowed to touch the endpoint:

file net code why it's here
daemon-endpoint-ownership.ts +58 the publish protocol itself
daemon-endpoint-probe.ts +63 is anything actually serving that name? (extracted so both callers classify identically)
daemon-server.ts +60 publish on startup; stand down if the name is taken from you
daemon-health.ts −2 killStaleDaemon no longer reclaims the name on a dead process's behalf
daemon-init.ts +27 removes three unfenced unlinkSync(socketPath) calls in the launcher
daemon-spawner.ts +21 claim namespaces moved out of released builds' sweeper regex
daemon-entry.ts / daemon-pty-adapter.ts +10 stand-down exit code; client recognises the new refusal

daemon-endpoint-claim-sweep.ts (95 lines) is deleted outright.

Those three launcher unlinks are the ones worth a reviewer's eye: plain check-then-act with no fencing — the original bug's exact shape — and one ran over every previous protocol version on every app start.

The protocol

Bind a private name → try an exclusive link → on EEXIST prove the incumbent dead by connecting → re-check the entry hasn't changed hands → probe once more → rename in one syscall → verify we kept it.

  • link first, not rename always. rename replaces whatever it finds, so using it unconditionally would let a starting daemon destroy a healthy one. link fails loudly instead, forcing the liveness question.
  • Three-way classification. Only connected means occupied; only refused/missing prove death; anything else, including a timeout, proves nothing and declines. Collapsing "can't tell" into "dead" is what deletes a live endpoint.
  • A second probe before the rename. A dead entry's inode number can be recycled straight back to a replacement, which then compares equal on dev+ino. Asking whether anything is serving answers that directly.

Invariants, the traps that each cost a defect, and the residual risk: src/main/daemon/AGENTS.md.

Measured, not assumed

Across a live handover, hammering connect:

primitive probes saw the name absent
rename (this PR) 6,525 darwin / 8,004 linux 0
unlink-then-link (what it replaces) 200 200

The old shape doesn't narrowly race — it gaps essentially every time it's observed.

Also measured: the now-common occupied path costs ~0.02ms; rename replaces a planted symlink rather than following it, so publishing can't be turned into a write primitive; no fd leak across 400 double-probes.

Honest limits

  • The race is narrowed, not closed. The final probe and the rename are two syscalls, and POSIX has no rename-if-target-is-inode-X. What changed is that the check inside that gap became sound, and the harm is separately unreachable: a daemon never creates a session on an endpoint it doesn't hold.
  • An already-released build's cleanup can still unlink a live socket. That's shipped code; nothing here can fence it. Landing this stops the behaviour going forward.
  • Scratch debris is no longer swept — deliberate; every actor removes its own on each non-crash path, so what a sweeper would collect is mostly crash debris.

Verification

19,583 tests green across src/main (1,385 in the daemon suites, stable across repeated runs); typecheck, oxlint, type-aware lint, max-lines ratchet and build clean; both real-process smokes pass; the e2e retirement spec — which this change had silently broken, since CI excludes e2e from needs — now passes.

Roughly 40 mutations applied across the protocol, guard, lifecycle and namespaces; all caught. Several tests were vacuous when first written and only mutation testing exposed them — and four times a "passing" mutation turned out never to have reached the code, so each is now verified to have applied.

Fifteen adversarial review rounds, plus a final full-diff read returning an unqualified merge verdict.

Two redesigns, not patches. The claim sweeper was deleted after producing five defects across three fix attempts. Birth-time identity was dropped entirely after three failed patches — Node documents that field as sometimes holding ctime, so on such hosts a healthy daemon would have bricked itself on its first terminal, invisibly on both APFS and Ubuntu CI.

One CI flake, investigated and cleared

A run failed in ssh-pty-provider-agent-session-create-operation.test.ts (request not dispatched: pty.cancelDelivery). Not caused by this PR, established four ways: that test's transitive import closure is 164 modules and contains none of the files changed here; it passed 25/25 in isolation and 3/3 replaying the exact CI shard command; its waitForRequest helper budgets the dispatch only 10 microtask turns, so one macrotask on that path throws exactly this error; and re-running the identical commit passed.

That hunt did surface a real defect here, now fixed: the mock subprocess in daemon-server-error-handling.test.ts had a no-op kill() and never fired onExit, so teardown waited out IMMEDIATE_KILL_PHYSICAL_EXIT_TIMEOUT_MS four times over — 32s of dead waiting in that same shard. Wiring kill/forceKill to the registered callback takes the file from 32.6s to 0.7s, and the tests keep their teeth: neutering the createOrAttach ownership guard still fails three of them.

The underlying SSH test remains fragile and is left alone deliberately — it belongs to another subsystem and doesn't belong in a daemon-ownership diff.

Review of stablyai#12709 found two ways the split-brain it fixed could still be
reached. Both are confirmed, and both now have regression tests that
fail against the previous behaviour.

Stale cleanup was unfenced. After killing daemon A, killStaleDaemon
removed whatever occupied the PID path rather than A's own record, and
treated "we killed something" as licence to unlink the socket even when
the final probe connected. A replacement that published during the kill
wait therefore lost its ownership record and its endpoint, and was left
alive hosting sessions that nothing could reach — the original failure.
Cleanup is now fenced to the exact incarnation we inspected, and the
endpoint is reclaimed only on positive evidence that it is dead.

The process-identity probe treated inspection failure as proof the PID
was not ours. `ps` runs under a 2s budget and PowerShell CIM under 3s,
and a loaded machine blows both — which is the root cause stablyai#12709 named.
The guard added there sat inside the kill block, but the entry condition
had the same flaw and is the more common path: a timed-out probe deleted
a live daemon's record, reported liveOwnerSurvived:false, and let the
launcher fork onto a still-live endpoint, ending in non-persistent local
PTYs. Identity is now tri-state, and 'unknown' preserves ownership,
falling back to the endpoint as the tiebreaker.

unlinkOwnedDaemonPidFile accepts a null nonce so records written before
launch nonces existed can still be fenced on PID alone.
@coderabbitai

coderabbitai Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Daemon health checks now classify process identity as match, mismatch, or unknown. Stale-daemon cleanup preserves endpoints when inspection is inconclusive, rechecks identity before termination, and removes PID and socket records only when ownership matches. Legacy PID records remain supported when no nonce is expected. Socket identity checks now include birth time. Tests cover replacement daemons, endpoint races, EPERM handling, and PID-record preservation.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the change in detail but omits the required template sections for screenshots, testing checkboxes, AI review, security audit, and notes. Add the required template headings and complete the testing, cross-platform AI review, security audit, screenshots, and notes sections.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly describes the main endpoint ownership fix and is concise enough for repository history.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
src/main/daemon/daemon-health.test.ts (3)

496-498: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use it.skipIf for the platform guard.

This test returns early on win32. The adjacent test at Line 562 uses it.skipIf. An early return reports the test as passed on Windows. it.skipIf reports it as skipped, which is accurate.

♻️ Proposed change
-  it("leaves a replacement's pid record and endpoint alone when cleanup runs late", async () => {
-    if (process.platform === 'win32') {
-      return
-    }
+  it.skipIf(process.platform === 'win32')(
+    "leaves a replacement's pid record and endpoint alone when cleanup runs late",
+    async () => {

562-591: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add the complementary case: unknown identity with a dead endpoint.

This test covers unknown identity with a reachable endpoint. It does not cover unknown identity when the endpoint does not answer. That branch falls through in killStaleDaemon and reaches the fenced unlink at daemon-health.ts Line 890, which removes the recorded PID file. It is the path I flagged at daemon-health.ts Lines 798-808.

Add a case that keeps processInspection.broken = true and binds no server. Assert the intended PID-record outcome. The test will then pin whichever behavior you settle on for that branch.


536-547: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add a rejection handler to the replacement bind path.

void listenOnSocketPath(replacement, socketPath).then(...) leaves bind failures as unhandled rejections; attach a .catch(...) handler alongside the success path.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8aaae5a2-461c-458a-8142-4b9b18b9f3e1

📥 Commits

Reviewing files that changed from the base of the PR and between c3db2b8 and f6f3657.

📒 Files selected for processing (3)
  • src/main/daemon/daemon-health.test.ts
  • src/main/daemon/daemon-health.ts
  • src/main/daemon/daemon-spawner.ts

Comment thread src/main/daemon/daemon-health.ts Resolved
Comment thread src/main/daemon/daemon-health.ts Resolved
Second review round found three remaining P1 paths. All three confirmed;
each now has a deterministic regression test that fails against the
previous behaviour.

Endpoint removal was not generation-fenced. The probe and the unlink are
separate syscalls, so a replacement publishing in between lost its only
reachable name — alive, hosting sessions, unreachable. Capture the
endpoint identity before judging it and remove only that exact entry.

Inconclusive evidence could still authorize deletion in three places.
`process.kill(pid, 0)` treated every error as absence, but only ESRCH
proves that; EPERM means the process exists and belongs to another user.
Both the entry check and the post-SIGTERM recheck required the endpoint
to report 'connected' before preserving, so a probe that merely timed out
combined with a failed inspection into a licence to delete. Two
inconclusive signals are not proof: preservation now requires positive
evidence that nothing is serving, via endpointIsProvenDead.

Fencing the PID unlink to JSON records broke the oldest format, a bare
integer. unlinkOwnedDaemonPidFile refused to match it, so the record
survived and the replacement's exclusive publish then failed with
EEXIST — trading a stale record for no daemon at all.

Adds a direct-construction-only seam so a test can interleave a
replacement publish between the endpoint probe and its removal.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
src/main/daemon/daemon-health.test.ts (1)

495-498: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use it.skipIf instead of an early return for the platform guard.

The early return makes the test report as passed on Windows. it.skipIf(process.platform === 'win32') reports it as skipped, so the coverage gap stays visible. The same pattern appears at Lines 532-534, 561-563, and 591-593.

♻️ Proposed change
-  it('does not unlink an endpoint republished between the probe and the removal', async () => {
-    if (process.platform === 'win32') {
-      return
-    }
+  it.skipIf(process.platform === 'win32')(
+    'does not unlink an endpoint republished between the probe and the removal',
+    async () => {

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1ff05cfc-9466-4d10-ae50-fe29ed329bcc

📥 Commits

Reviewing files that changed from the base of the PR and between f6f3657 and fb18954.

📒 Files selected for processing (3)
  • src/main/daemon/daemon-health.test.ts
  • src/main/daemon/daemon-health.ts
  • src/main/daemon/daemon-spawner.ts

Comment thread src/main/daemon/daemon-health.test.ts Resolved
The inconclusive-evidence regression passed on macOS and failed on Linux
in CI. It provoked the unknown identity by breaking `ps`, but Linux reads
/proc/<pid>/cmdline first and never reaches `ps`, so identity came back
as a definite mismatch and the branch under test never ran.

Drive it through an EPERM from process.kill(pid, 0) instead, which is
evaluated before any platform split, so the branch is exercised on every
platform rather than silently skipped on one.
…form

CI is ubuntu-only for unit shards, so a macOS-gated test never runs there
at all — the gate I added last round was a coverage illusion, not
coverage. And the replacement test still failed on Linux: which errno a
non-socket path yields is platform-specific, ENOTSOCK on macOS versus a
refused classification on Linux, so the "endpoint cannot be judged" state
cannot be produced portably through real syscalls.

Inject the endpoint verdict through a direct-construction-only seam
instead. The probe implementation is covered separately; what these tests
exercise is the decision rule that combines process identity with the
endpoint verdict, and that rule is platform-shared.

Drops the macOS-gated `ps`-failure test with its module mock: EPERM from
process.kill reaches the same inconclusive-identity branch before any
platform split, so the branch is now covered on every platform rather
than on one that CI never runs.
The identity fence added last commit was not sufficient. Linux recycles
inode numbers as soon as the inode is freed, so a replacement socket can
land on the exact dev+ino we captured and match the fence — letting the
removal delete a live replacement's only reachable name. This is the
failure the fence existed to prevent, and CI caught it: the interleaving
regression passed on macOS, where APFS does not recycle, and failed on
Linux, where it does.

Re-probe immediately before the removal. A replacement is by definition
listening, so a fresh probe reports it and vetoes the unlink regardless
of what the inode number says. Identity now also carries birthtimeMs, so
a recycled number no longer matches on its own.

This narrows the window rather than closing it: probe and unlink remain
separate syscalls. Closing it properly needs the publishing daemon to
replace a proven-dead entry atomically, rather than a third party
unlinking on its behalf.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 7138795d-f5a3-4592-a28a-eb58e2cbdd2a

📥 Commits

Reviewing files that changed from the base of the PR and between e71dd55 and 00af54b.

📒 Files selected for processing (3)
  • src/main/daemon/daemon-endpoint-ownership.ts
  • src/main/daemon/daemon-health.test.ts
  • src/main/daemon/daemon-health.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/daemon/daemon-health.test.ts
  • src/main/daemon/daemon-health.ts

nwparker and others added 8 commits August 6, 2026 03:27
Third review round. Two of the three findings are regressions from this
PR's own earlier commits.

Endpoint removal checked identity and then unlinked as separate syscalls,
so a replacement publishing between them was deleted. Re-probing narrowed
that window but could not close it. Claim the directory entry with a
rename first: from that point nobody else's entry can be at the canonical
path, so what we then inspect is unambiguously ours to drop. Anything
else gets linked back, and a replacement that published while we held the
claim wins the restore by EEXIST.

A live replacement found by the late probe was preserved but still
reported as liveOwnerSurvived:false, so the caller went off to fork
beside it — and that fork cannot publish, because the exclusive claim is
already held. The user ended up with no daemon rather than the working
one already running. Report the live owner instead.

Fencing PID-record removal to a parseable record left malformed ones
unremovable, and the next daemon's exclusive publish then failed with
EEXIST. Reclaim an unparseable record under the same rename claim, and
only while it is still unparseable, so a valid record published in the
meantime is left alone.

Also converts the platform guards in this file from early returns, which
report as passed on Windows, to real skips.

Note on scope: the rename makes the removal atomic with respect to the
directory entry. It does not make the surrounding kill-then-reclaim
sequence atomic, and no in-function interleave is reachable from a test.
Fourth review round. All four findings valid; two are regressions from
this PR's own earlier commits.

A live replacement found by the FIRST cleanup probe was still reported as
liveOwnerSurvived:false. Last round fixed only the second probe, leaving
the identical case one branch over — the caller forked beside an endpoint
it could never publish onto, so the user got no daemon rather than the
working one already running. Both probes now apply the same rule.
'unknown' deliberately still does not count as a live owner: it keeps the
endpoint file but must not block a cold start where nothing ever ran.

Identity after claiming was still trusted. The inode we mean to remove
has already been freed, and Linux hands the same number straight back;
birthtimeMs is frequently unavailable there, so identity can match a live
replacement and delete it. Reclaim now decides by liveness — nothing
answers it — which is the property that actually distinguishes a dead
endpoint. The daemon's own shutdown keeps the identity check, where it is
sound because a bound inode cannot be freed underneath its owner.

Restore-link failure was treated as EEXIST and the claim dropped, so an
EPERM destroyed the endpoint outright. Only a confirmed EEXIST with a
canonical entry present may drop the claim; anything else falls back to a
rename restore, and failing that keeps the claim rather than losing the
only copy.

The .c claims this file creates were missing from the sweep it also owns.
Fifth review round. Two of the four findings are regressions from this
PR's own round-four commits.

The claim result was discarded, so a replacement found alive by the claim
— or one that published during the claimed-path probe — was preserved
correctly but still reported as no owner, sending the caller off to fork
onto a name it could never publish. Reclaim now returns a four-way
outcome and the caller reports a live owner for both live-owner and
inconclusive.

Claimed-path liveness was collapsed to a boolean, so an unclassifiable
probe read as dead and deleted a live claim. It is tri-state now: only
proof of death removes an entry. The mirror case is fixed too — an
endpoint file we cannot classify still occupies the name, so reporting no
owner invited a replacement that then failed its exclusive publish. Only
a genuinely absent endpoint frees the caller to fork.

Owner shutdown had been reverted to stat-then-unlink on the grounds that
a bound inode cannot be recycled. That addressed the wrong failure mode:
the race is a replacement publishing between the two syscalls, which the
identity check cannot see. It claims by rename first, like every other
removal here.

The restore fallback used an overwriting rename, which could swap a
daemon that published while the claim was held for the older entry we
took. Restore is link-only now; if it cannot link and nobody replaced the
name, the claim stays on disk for the sweep rather than clobbering.
Adversarial review round found four defects, two of them in the claim
protocol added by the previous commit.

A failed canonical restore returned 'live-owner' while the daemon was
reachable only through the hidden claim, and the age-gated sweep then
deleted that claim — the sole pathname of a live listener. Restoration
now reports failure explicitly, and the sweep re-links a claim that is a
socket with one link back to the canonical name instead of removing it.

A rejecting liveness probe escaped before either restore path ran,
leaving the canonical name absent and the daemon reachable only through
the claim. The probe is guarded; a rejection is treated as unknown and
the canonical name is always restored.

Two entry kinds occupied the endpoint name without serving it, and both
blocked startup permanently because nothing reclaimed them while the
exclusive publish kept failing with EEXIST. A regular file reports
ENOTSOCK on macOS, and a dangling symlink reports missing through
existsSync because it follows links. Probing now lstats the entry and
classifies both as refused, routing them through the fenced reclaim.

Moves the claim sweep into its own file: it now owns recovery policy,
not just pattern matching, and daemon-endpoint-ownership.ts was at the
line limit.
Second adversarial review round found four defects.

Publication had a fallback for filesystems without hard links: it checked
that the canonical name was absent, then renamed over it. That is
check-then-act with an operation that replaces whatever it finds, so a
daemon publishing in the gap was silently overwritten and stranded on an
unreachable inode. The fallback is gone; publication requires the
exclusive link. That also removes the case where a claim could not be
restored, since publishing now proves the filesystem supports linking.
userData is always local, so this is not a reachable limitation.

Claiming the endpoint reported every rename failure as 'absent',
including EACCES and EIO. That tells the caller the name is free while it
is still occupied, and its exclusive publish then fails with EEXIST. Only
a missing source is absent now; anything else is inconclusive.

Protocol cleanup discarded liveOwnerSurvived from killStaleDaemon, so
Manage Sessions -> Restart forked a replacement onto an endpoint that was
still owned. It now aborts rather than launching a daemon that cannot
publish.

The publish fix is structural: its race is not reachable from a test, so
the added test covers exclusivity rather than the removed fallback.
The rule that decides who may serve on the endpoint needs to classify what is
serving it, but that classifier lived in daemon-health, which already depends on
the ownership module — importing it back would cycle. No behaviour change.

Also records that a non-socket occupying the endpoint reports ENOTSOCK on macOS
and ECONNREFUSED on Linux, so both must be read as "nothing can serve this".
…arty

The endpoint had one rule expressed in many places: a launcher decided another
process was dead and reclaimed its socket name on its behalf. Seven review rounds
against that shape produced twenty-three defects, and every one was the same
interleaving — a third party observing liveness at time T and acting on the
directory entry at time T+1. Rename-claiming made the removal atomic with respect
to the entry, but nothing makes observe-then-act atomic across a process boundary.

Replace the shape with an invariant: only a daemon publishing itself onto the
canonical endpoint may mutate that entry, and only by replacing an entry it has
itself just proven dead. A daemon binds a private name, tries an exclusive link,
and on EEXIST proves the incumbent dead by connecting before replacing it with a
single rename. It then verifies it kept the name.

Two daemons can still race, but the loser is now by construction one that is still
starting and has no sessions — it sees the loss and exits. The catastrophic case
needed the loser to be a long-lived daemon hosting the user's terminals, and the
entry is now only ever replaced by the process that will own the result, before
any session exists.

Measured on darwin/APFS and linux/overlayfs: rename handover exposed the name as
absent in 0 of 6,525 and 0 of 8,004 connect probes; the unlink-then-link shape it
replaces gapped on 200 of 200.

Deletes reclaimDeadDaemonSocketPath, unlinkOwnedDaemonSocketPath, the .c claim
protocol and its sweeper recovery, the reclaim tail of killStaleDaemon, and three
unfenced unlinkSync(socketPath) calls in the launcher. Those last three were plain
check-then-act with no fencing — the original bug's exact shape — reachable on the
pre-CLEAN_DISCONNECT upgrade path. Every prior round was scoped to one module and
so never saw them.

A departing daemon now leaves its endpoint behind deliberately: removing it needs
fencing against a replacement that published meanwhile, and that fencing caused
about half the defects. The dead entry costs nothing and makes the occupied path
the one every start exercises.
@nwparker nwparker changed the title fix(daemon): fence stale cleanup and preserve unprovable ownership fix(daemon): let the publisher replace a dead endpoint, not a third party Aug 7, 2026
nwparker and others added 2 commits August 7, 2026 03:20
Adversarial review of the new publish protocol found three defects, one of which
falsified a claim in the design doc.

The load-bearing one: the rename acted on evidence gathered before the probe, with
nothing rechecked in between. A publisher preempted after proving a dead entry dead
could resume much later and rename over a daemon that had meanwhile published,
started serving and acquired sessions — an established daemon destroyed by a proof
that never described it. That is the original bug reached through a narrow window,
and it contradicted the doc's claim that the loser of a publish race always has zero
sessions. Re-read the entry after probing and start the sequence over when it
changed hands, bounded at three attempts.

That comparison includes birthtime, not just dev+ino. The entry being compared is
one we believe is dead, so its inode can be freed and Linux hands the number
straight back — a replacement landing on the recycled number would compare equal and
license the very rename the check exists to prevent. This is the opposite of the
post-publish check, where dev+ino alone is sound because our own listener holds that
inode open.

Second: a stat failure while verifying the publish returned 'published'. A daemon
whose name had been removed, or whose entry could not be read, was told to serve
something nothing resolves to. Fail closed instead — ENOENT is 'lost', anything else
'inconclusive'. Startup has no sessions to protect, so declining is cheap.

Third: a null identity for the bound socket disabled both the publish verification
and, permanently, the ownership watchdog, which treats a null owner as indeterminate
forever. Require the identity before mutating anything.

The doc now states the residual honestly: the recheck shrinks the window to two
adjacent syscalls rather than closing it, since POSIX has no rename-if-target-is-
inode-X. Closing it fully needs a publication lock, which would reintroduce a
stale-lock problem of exactly the kind this design removes.
Dropping birthtime from the comparison left every test passing. The entry it
compares is one believed dead, so its inode can be freed and Linux hands the number
straight back — dev+ino alone would then compare equal to a replacement and license
the rename the check exists to prevent. Recycling cannot be provoked on demand, so
the identity read is mocked to report the same dev+ino with a later birthtime.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the nwparker/daemon-stale-cleanup-fencing branch from 2a01991 to a94044a Compare August 7, 2026 10:23
nwparker and others added 9 commits August 7, 2026 03:31
… daemon

Three defects found by adversarial review of the redesign, one of them a
user-facing regression this change itself introduced.

killStaleDaemon no longer withholds a fork when the endpoint is merely
unclassifiable, on the reasoning that the publisher is the real guard. It is —
but that guard works by refusing to overwrite what it cannot prove dead, so the
child exits, and the launcher had no path back. A live endpoint whose ownership
record is unusable therefore produced no daemon at all for the whole app run:
existing persistent sessions unadopted, every new terminal on the local provider.
Adopt whatever answers the endpoint after a failed launch instead of giving up.

The socket server had no error handler once startup settled, so a later
operational failure such as a failed accept under fd exhaustion became an
uncaught exception and killed a daemon hosting every terminal on the machine.
That predates this work but the publish window widened it: the listener was
registered with `once`, so a second error during the async probe was unhandled
too. It is now permanent, rejecting before startup settles and logging after.

A server error during publication rejected start() but could not stop work
already in flight, so the daemon went on to publish, write its records and arm
its timers behind a caller that had been told startup failed — and a caller that
responds by launching a replacement is how the split brain comes back. The
publish continuation now re-checks and stands the daemon down.

The sweeper also inferred process death from mtime. A bind name is the only name
its daemon has between listen and publish, and a process stopped by a debugger or
caught in a host suspend is still listening, so an aged bind socket is now asked
whether anything answers before it is removed. Age alone would have destroyed a
live listener's sole reachable name — the defect class this component exists to
remove.

Mutation-verified: sweeping without the liveness check fails 1 test, detaching
the error listener after startup fails 1, and ignoring a startup failure after
publication fails 1. The last one initially passed vacuously because the error
landed before publication was in flight; the test now forces the slow
probe-then-rename path so it lands inside the window.
…nt race

Review of the callers found the publish contract was written but never wired. The
design says an 'occupied' result means another daemon owns the endpoint and the
caller must adopt it. In practice the child threw, exited 1, and the parent turned
that into a generic "exited during startup" — no retry, no adoption. Two app
processes cold-starting together would leave the loser running local
non-persistent PTYs for the rest of its life, beside a perfectly healthy daemon it
should have been talking to. The reason was only recoverable from stderr text.

The child now reports the reason over IPC and the parent adopts the incumbent on
'occupied' rather than reporting a startup failure.

Also fixes a hazard introduced when the server error listener was moved to outlive
bind: it was still a one-shot. A second operational error after startup — a failed
accept under fd exhaustion — was then unhandled, which on a net.Server is an
uncaught exception that would kill a daemon hosting every terminal on the machine.
Make it permanent, and log post-startup errors rather than treating them as startup
failures. A server error raised while publishing is still in flight now stands the
daemon down instead of arming it behind a caller that was already told startup
failed, which would have recreated the split brain.

The sweep no longer removes an aged bind name that still answers, since a daemon
stalled past the age gate would otherwise lose its only pathname.

Every fix here is mutation-verified. Two of the tests were vacuous when first
written — the adoption test passed without the launcher ever forking, and the
operational-error test could not distinguish a permanent handler from a one-shot
until it emitted twice. Both now fail against their mutations.
The smoke awaited both racers to ready-or-exit before identifying the winner, so
the loser had normally exited already and killing it asserted nothing. A live
owner makes the interleaving forced rather than hoped for: a newcomer boots
against a known-live incumbent, must fail to publish, and must leave the owner's
endpoint, reachability and ownership record untouched on its way out.

Verified across real processes: a build that lets a publisher replace an entry
something is still answering fails this phase with "a daemon published onto an
endpoint a live daemon already owned". The previous phase passed that mutant.

The unit test claiming to keep a replacement reachable "after the incumbent
closes" closed the incumbent before the replacement published, so it duplicated
the dead-incumbent case and a late-close regression would pass. Closing is what
makes an incumbent replaceable, so the two cannot be ordered against each other
at this level; the property that made the original bug possible is asserted
directly instead — libuv unlinks the pathname a server bound to, so a daemon
that published by linking a private name must leave the canonical entry intact
when it closes. The ordered version needs the full lifecycle and already exists
in daemon-endpoint-ownership.test.ts.

Also covers the identity publish returns, which callers arm the ownership
watchdog with: an identity that does not describe the published entry makes
every later ownership check meaningless, and nothing compared the two.

Two titles overclaimed. The sweep test said "unreadable runtime dir" but passed a
nonexistent one, covering ENOENT rather than EACCES. The duplicate-launch test
said it refuses a second listener, but what rejects is the exclusive PID record —
it does not prove a second listener was never transiently published, and the
endpoint side is covered elsewhere.
Between listen and publish a bind name is the only name its daemon has, and an
old mtime does not prove the process died — one stopped by a debugger or caught
in a host suspend is still listening. Removing it on age alone would destroy a
live listener's sole reachable name, which is the original defect in different
clothes, so the rule belongs in the design rather than only in the code.
A departing daemon now leaves its entry behind, so EEXIST is the ordinary case
and the liveness probe runs on nearly every start. That probe has a 500ms
timeout, which would be a bad thing to pay at startup, so it was measured rather
than assumed: a dead entry refuses in ~0.02ms p50 and under 1.3ms worst case on
both darwin and linux, and the timeout is never reached. It exists for a
genuinely unresponsive host, where waiting is correct and the outcome is
inconclusive — decline rather than replace.

Co-authored-by: Orca <[email protected]>
Leaving the endpoint entry on disk invites the question of what a hostile local
process could plant at that name. Measured on darwin and linux: link refuses a
symlink with EEXIST, the probe follows it and reports a live target as occupied
rather than clobbering it, and once the target is dead rename replaces the
symlink itself rather than writing through it. That last one is the load-bearing
property — rename does not follow symlinks, so publishing cannot be turned into a
write into an attacker-chosen location.

Co-authored-by: Orca <[email protected]>
The sweep preserved an aged bind name only when the probe returned 'connected'
and unlinked it on every other result — including 'unknown'. A daemon stopped by
a debugger or caught in a host suspend past the one-hour age gate would have its
sole pathname removed on a probe that merely timed out under load.

That is the same mistake this whole design retired, aimed at the bind name
instead of the canonical one: acting on absence of evidence rather than evidence
of absence. The probe module already draws that line — only 'refused' and
'missing' prove death — so use it rather than restating the rule loosely.

The resumed publisher fails rather than splitting the brain, so this is a startup
regression rather than a correctness hole, but it contradicted the stated
invariant and had no test. Mutation-verified: restoring the connected-only check
fails the new test.
A readiness review reported that the child queues its endpoint-unavailable
notification and immediately calls process.exit, so the parent can settle the
launch on the child's exit and discard a notice still in the channel — falling
back to local PTYs beside the daemon it should adopt.

I could not reproduce the failure. A harness forking 300 children per mode, on
both darwin and linux, delivered the notice before exit every time in both the
current shape and the flushed one. The reported 261/500 drop rate did not
reproduce.

Applying the fix anyway: process.send is genuinely asynchronous, the consequence
is a user stranded on non-persistent terminals, and waiting for the flush costs
six lines and nothing at runtime. The wait is bounded so a wedged channel cannot
hold the exit. This is precaution, not a demonstrated repair.

Also documents why the one dead endpoint left behind per protocol generation is
deliberately not swept: removing it means a process deleting an endpoint it does
not own on a liveness judgement about another daemon, which is the pattern this
design removes, and an old-protocol daemon can still be live during an upgrade.
… probes

Startup awaited a sweep that serially probes every aged bind socket, each able to
run to a 500ms timeout, over a directory with no size bound. A hundred
unclassifiable entries would have delayed daemon readiness by roughly fifty
seconds on the one path a user is actually waiting on.

Making the sweep preserve unclassifiable entries — correct, and done a commit ago
— is what turned this from self-limiting into compounding: an entry that never
classifies is now kept and re-probed on every subsequent launch, so each sweep
would be slower than the last.

Two changes. The sweep is no longer awaited, because reclaiming crash debris is
housekeeping and nothing about starting a daemon depends on it; the one-hour age
gate keeps it away from a bind still in flight. And probes are capped per sweep,
with anything deferred reported rather than silently skipped, so the work is
spread across launches instead of growing without bound.

Mutation-verified: removing the cap fails the new test.
nwparker and others added 24 commits August 7, 2026 18:04
…call

The ownership guard retires synchronously, and with nothing left to drain that now
begins shutdown before the reply is written. The client must still receive the
refusal it knows to retry on — a dropped connection there would surface as an
opaque failure rather than a reconnect to the endpoint's real owner. Verified it
does.

Co-authored-by: Orca <[email protected]>
Four rules govern what a daemon does after losing its endpoint, and they were
arrived at one at a time across four commits. Every defect found in this area came
from an interaction between them rather than from any one being wrong, so they are
now stated together: loss is sticky, creation is refused, attach is allowed, and a
drained daemon stands down without waiting for clients that can no longer make it
reachable.

Co-authored-by: Orca <[email protected]>
…ment

Losing the endpoint was only recorded when no retirement was already pending. But
a daemon can be retiring for an unrelated reason — its last authenticated client
dropping while a session still runs — and losing the endpoint is a different fact
about it. Conflating the two meant that in exactly that overlap the loss went
unrecorded, after which a later stream hello found no remembered loss, cleared the
retirement, and put a daemon that demonstrably could not be reached back into
ordinary service: creating sessions again, and no longer standing down when
drained.

Two early returns caused it, one in the watchdog and one in the setter, both
keyed on retirementRequested. The flag is now set first and unconditionally; only
the log line is deduplicated.

Mutation-verified in both places: restoring either early return fails the new test.
…eaders

The watchdog retires on two CONSECUTIVE losses and resets its streak on any
positive reading. But the admission-time check added for the session guard does an
equally authoritative ownership read and returned its answer without touching that
streak. A positive reading taken through that path therefore did not break the run,
so two losses with a demonstrably owned observation between them counted as
consecutive.

The consequence is the false positive I most wanted to avoid: a healthy, reachable
daemon permanently marked as having lost its endpoint, refusing every later session
and standing down once its live work drained. Worse than the bug the guard fixes,
because it needs no race at all — just two transient reads.

Both callers now go through one observation helper that reads ownership and resets
the streak on anything that is not a loss. Mutation-verified both ways: dropping
the reset fails, and resetting on a loss as well fails.

I had checked the setters for false positives and found them sound. I did not
check the streak accounting, which is where it actually was.
…broken

A full-diff review found two things green CI could not.

tests/e2e/daemon-lifecycle-retirement.spec.ts asserted the socket file is gone
after a daemon retires, which is the opposite of the contract this change
establishes. It has been failing on this branch the whole time and nothing said
so: pr.yml deliberately leaves e2e out of `needs`. The same edit was already made
in the boot smoke, daemon-server.test.ts and daemon-idle-shutdown.test.ts; this
one was missed because it lives under tests/e2e. Now asserts unreachability, which
is the property that actually matters. Verified passing, and the two sibling
daemon e2e specs still pass.

The boot smoke's private-bind-name leak check matched entries starting with `.b`,
which has matched nothing since the namespace moved to `.p`. It matters more than
before, because with no sweeper a leaked bind name is never collected. It now
matches what the code generates.

Also adds the assertion that was missing entirely: nothing pinned the stand-down
exit code from a real daemon, so the launcher's adoption of a live incumbent could
have silently stopped working. The handover smoke now asserts it, reading the
expected value from source so the two cannot drift. Mutation-verified — and my
first two attempts at that mutation failed to compile, so the smoke ran against a
stale bundle and appeared to pass; checking the build's exit code is what caught
that.

Documentation corrections from the same review: the bind namespace is `.p` not
`.b`, the claim namespaces are `.swap`/`.hold` not `.cleanup`/`.replace`, and the
"what this deletes" list named three functions that never existed on origin/main —
they were introduced and removed within this branch, so a reader would have
grepped for symbols that never shipped. The released-sweeper rationale for the
namespace moves is restored; an earlier edit of mine had dropped it.

Removes dead code the review found: the unused afterEndpointProbe test hook, which
was also misnamed since it ran before the probe, and a stale mock of the deleted
sweeper.
…before

A final pre-merge review found a blocker, and it is the false-positive class this
design calls worse than the bug it fixes.

The identity recorded at publish was read from the bound socket BEFORE the link or
rename, but it becomes what the ownership watchdog compares the entry against —
and that comparison includes birthtimeMs. Node documents birthtimeMs as sometimes
holding the ctime instead; libuv fills it from st_ctim on Linux kernels without
statx, and where seccomp blocks statx. Measured on both darwin and linux: link and
rename bump ctime while birthtime stays put. So on such a host the recorded value
could never match the entry again.

The consequence is not subtle. The first createOrAttach reads ownership as lost on
a single observation, refuses, and sets the sticky flag; the daemon stands down
permanently, and because the client treats the refusal as "daemon gone" it
respawns into a replacement that does the same thing. A healthy daemon bricks
itself on its first terminal, and the user ends up worse off than on main.

It is invisible on APFS and on ubuntu CI, where statx is present — which is also
why mutation-testing the publish suite could not have surfaced it.

The fix is to record the reading taken after publishing. dev+ino still bind it to
our own inode, so no strength is lost. A test simulates the ctime fallback by
reporting ctime as birthtime and asserts the watchdog still recognises the
endpoint; it fails against the previous code.

Also corrects the comment that made the birthtime term look free everywhere — it
claimed the field is 0 where unavailable, when ctime is the other documented
fallback and the dangerous one — and documents why the two loss detectors use
different evidence bars.
…d-rolling three

The blocker fixed in the previous commit hid in a seam: three hand-rolled
comparisons of the same type, under three different implicit rules, in one file.
Nothing at any call site said which rule applied or why, so using the wrong one
looked like a typo rather than a permanent false positive.

There are exactly two rules, and they now say so:

  isSameInode            — dev+ino. For readings that straddle a link or rename,
                           or where the inode is held open so its number cannot be
                           recycled.
  isSameInodeIncarnation — dev+ino+birthtime. For readings where the inode may
                           have been freed and Linux handed the number straight
                           back, and nothing between them mutates it.

The shared docblock says once, in one place, why birthtimeMs cannot be trusted
across a link, rename or unlink: Node documents it as sometimes holding the ctime,
and those syscalls bump ctime. That is the fact the blocker turned on, and it was
previously stated only where it did not matter.

Each of the three call sites now picks a named rule with a one-line reason. All
three are mutation-verified: swapping any of them to the other rule fails a test.
The watchdog's use of the incarnation rule had no coverage at all, so a test now
pins it — inode-only there would report a recycled replacement as still ours and
keep serving sessions on an endpoint the daemon no longer owns.
…ing permissions

A per-test audit of the publish suite found one robustness problem: the
fail-closed verification test induced EACCES by removing search permission from
the directory. That induces nothing when the suite runs as root, so the test would
pass without ever reaching the branch it names — the exact shape of the vacuous
tests found earlier in this work.

Injects the stat failure directly, and only after publication, so the branch is
reached deterministically regardless of the executing user. Still
mutation-verified: collapsing the non-ENOENT case to 'lost' fails it.

The audit otherwise found all 19 tests sound, with none weak or vacuous, which
independently corroborates the twelve-mutation sweep run against the same file.
…ation

A review of the identity-rule consolidation found the watchdog and admission guard
using the wrong rule, and it is the same false-loss hazard as the blocker two
commits ago rather than a style point.

The identity they compare against is this daemon's own bound socket, and its
listener is open whenever either runs — the watchdog returns early once shutdown
starts, and the identity is only set after a successful publish. So the kernel
cannot free that inode or hand its number to anything else, which means recycling,
the one thing birth time guards against there, cannot happen. Comparing birth time
bought nothing and cost something real: birthtimeMs may hold the ctime, and any
ctime bump on our inode would then report a loss that never occurred. That loss is
sticky, refuses every later session, and retires a daemon that is serving fine.

My comment claiming a replacement could land on that recycled inode was simply
false, and it contradicted the rule it sat next to.

The test I added an hour ago asserted the wrong property — that a differing birth
time means lost — so it is replaced by the two that are actually true: ownership
survives a stale birth time, and a name resolving to a different inode is lost.
Both mutation-verified, including that restoring the incarnation rule fails.

Three identity comparisons, three rounds, three different mistakes in the same
place. The named rules make the choice explicit; this commit makes the third
choice correct.
A follow-up audit of the identity rules found three comment claims too absolute,
and comment accuracy in this file has already cost two real defects.

The type doc called birthtimeMs "not redundant" as a flat property of endpoint
identity. It is not: where a live listener holds the inode open, its number cannot
be recycled and dev+ino is already decisive, so comparing birth time there adds
only risk. The type now says the field is carried but that the two rules decide
when it is wanted.

The rules' shared doc said birth time is meaningful "between two readings with no
such syscall between them", naming only link, rename and unlink — this code's own
operations. If the field is really ctime then any metadata change moves it,
including a chmod or a hard link taken by an unrelated process. So the honest
statement is that it is only worth comparing across a short interval this code
fully controls, and never across one it does not.

And the continuity check's doc claimed the field "is stable whatever it holds"
between its two readings. It is stable as far as this code is concerned; another
process can still touch the inode. That is survivable there because the cost is a
single retry — which is precisely the argument for why the same comparison is
wrong at the ownership check, where being wrong retires a daemon that is serving.
The comment now says that rather than implying the interval is inviolable.

No behaviour change.
…seconds

Two findings from a fourth pass over the identity rules.

The incarnation rule compared a birth time that had been rounded to milliseconds —
the identity type stored it as a Number of ms, discarding what the bigint stat
already had. Linux can recycle an inode number well inside a millisecond, so two
different incarnations could compare equal, and the continuity fence would rename
over a replacement it never proved dead. That is the one thing the rule exists to
catch, so its name and its docblock were both promising something the code did not
deliver. The identity now carries birthtimeNs and compares it whole.

Second: the ownership read is only sound while this daemon's listener holds the
inode open, and the watchdog guarded that with `shutdownPromise`. Two routes —
the idle sweep and the shutdown RPC — close the server first and assign that
promise later, after deferring a reply, leaving a window where the listener is
gone but the recorded identity is not. Nothing acts on the answer in that window,
but the rule's precondition genuinely did not hold, so the read now declines
unless the daemon is running.

I had traced this chain myself and concluded it held on every reachable path. I
checked shutdown() and missed both of these, which is the second time my own
reasoning about this exact invariant has been wrong.

Both mutation-verified: rounding the comparison back to milliseconds fails the new
sub-millisecond test.
… its real limit

Two things found while checking the nanosecond switch, one a latent hazard and one
a claim that was still too strong.

An identity without a birth time compared equal to another without one, because
undefined === undefined. That would have silently downgraded the incarnation rule
back to inode-only — precisely the failure it exists to prevent, and silently is
the worst way for it to happen. Measured: birthtimeNs is a bigint on darwin and
linux for sockets, files, directories and dangling symlinks, so this is a guard
against a platform I have not seen rather than one I have. It refuses to match
instead, which costs a retry at the single call site that uses the rule.

The larger correction is to the claim. Nanoseconds narrow the same-incarnation
collision window; they do not close it. Measured on overlayfs, entries created at
visibly different moments report an identical birth time — filesystem granularity
is often coarser than the field. So the rule makes a collision much less likely,
not impossible, and the doc now says so. The protocol does not rest on it alone:
the exclusive link and the post-publish verification still stand, and a collision
here costs a missed retry rather than a lost endpoint.
…on token

My previous guard rejected a birth time that was not a bigint, which is the case I
had measured. It missed the one that actually happens: a filesystem without a birth
time reports the epoch, and 0n is a perfectly good bigint. Two entries both
reporting 0n therefore still compared equal, which is worse than not comparing at
all — it looks like proof of continuity while proving nothing.

Concretely: the dead entry is removed during the probe, a live publisher takes the
recycled dev+ino, both readings compare equal, and the continuity fence authorizes
renaming over a daemon it never proved dead. Neither the earlier failed link nor
the post-publish check repairs that, because both only establish who won.

Zero now counts as absent, alongside a missing field.

Also de-flakes the sub-millisecond test. It fabricated the second timestamp with
+1n, which crosses the boundary whenever the real remainder is 999999n, so the
assertion depended on when the socket happened to be created. It now steps toward
the middle of the millisecond. Verified stable over repeated runs.
…ting its birth time

The continuity fence had one job: do not rename over a replacement that took the
name after the death proof. Its inode number can be recycled straight back from the
entry we proved dead, so dev+ino alone cannot separate them, and the fence used the
file's birth time as the tiebreaker.

That field cannot carry it. Node documents it as sometimes holding the ctime;
filesystems without a birth time report the epoch; and granularity is routinely
coarser than the events it must separate — measured on overlayfs, entries created
at visibly different moments report an identical birth time. I patched around
those three times in three rounds: milliseconds to nanoseconds, then a non-bigint
guard, then an epoch guard. Each patch was correct and each revealed the next hole,
which is the signal that the approach was wrong rather than incomplete.

Whether something is serving the name is the property that actually matters, and
connecting answers it directly. So the fence now probes once more immediately
before the rename, and the identity type carries only dev+ino. One comparison rule
instead of two, no unreliable metadata, and the guard tests the thing it cares
about rather than a proxy for it.

Cost is one extra connect on the occupied path, measured at ~0.02ms against a dead
entry; the 500ms budget is only ever paid by an unresponsive host, where declining
is the right answer anyway.

Mutation-verified: removing the second probe fails a test that stages a live
replacement the identity check cannot distinguish. Two tests that pinned birth-time
behaviour are gone, since the behaviour is gone.
The residual-risk section still described the old sequence, and the commit that
introduced the pre-rename probe risked reading as though it closed the race. It
does not. The gap between the last check and the rename is the same single syscall
either way.

What changed is that the check inside that gap became sound: the birth-time
comparison could fail to notice a replacement that had already arrived, because the
field is unreliable, whereas a probe cannot, because it asks whether anything is
serving rather than inferring it. The residual is now the one-syscall preemption
alone, rather than that plus an unknown rate of missed detections.

Also records the cost honestly: the second probe runs only after the first proved
the entry dead, and a dead endpoint refuses immediately, so the 500ms budget is not
doubled on an ordinary start.

Co-authored-by: Orca <[email protected]>
… one

The probe added before the rename mapped every non-dead result to 'occupied',
including 'unknown'. A timeout or an EPERM there proves no live incumbent, but it
would report one — and 'occupied' is the outcome that exits with the stand-down
code and sends the launcher off to adopt an incumbent that may not exist. The
first probe already splits this three ways; the second now does the same, so a
probe that establishes nothing declines instead of inventing an owner.

Mutation-verified: collapsing the non-dead cases back to 'occupied' fails the new
test, which proves the entry dead on the first ask and unclassifiable on the second.

Also clears claims left stale by dropping the birth time a commit ago. The type
doc, two code comments and a doc paragraph still described an identity that
included it. And step 4 of the contract read as though the second probe closed the
replacement race; it does not, and now says so, pointing at the section that
states precisely what it does and does not buy.
…proves death

Mutation-testing the four classification branches across both probes found three
pinned and one not: removing the FIRST probe's unknown-guard changed nothing any
test could see.

That is not a defect, and the reason is worth recording. Since the second probe
re-establishes death immediately before the rename, the first guard is no longer
what makes replacing safe. What it does is keep the protocol conservative: without
it, an endpoint that could not be classified at all would still be replaced on the
strength of one later reading. Declining on any doubt is the contract, so it is
now pinned by a test that returns unknown first and refused second, and asserts the
entry is left alone.

All four branches — connected and unknown, at each probe — now fail a mutation.
Three of the four, plus why the fourth is not one.

Two JSDoc blocks described the wrong function. "Replaces an occupied endpoint
name…" sat above probeEndpointSafely rather than replaceProvenDeadEndpoint, and
the link-unsupported explanation landed on readDaemonEndpointEntryIdentity rather
than isLinkUnsupportedError. Cosmetic anywhere else; in this file it is not.
Comments here have been trusted and later found false three times, and each cost a
round to unpick, so a block describing the wrong function is exactly the kind of
thing that misleads the next reader.

The occupied-adoption path called holdDaemonAdoptionLease without pidPath, so
reconcileDaemonPidOwnership no-opped there. Every other adoption passes it. The
repair is fail-open, so this was an inconsistency rather than a bug, but it meant
the one incumbent adopted through that path never had its PID record checked
against the identity it reports over hello.

Retiring for a lost endpoint clears the identity the ownership watch compares
against, so every later tick early-returned. The interval is unref'd and the
daemon is standing down, so this was only pointless work — the watch now stops
with the retirement.

Not changed: the reachability test harness living under src/main. That is the
repo's convention, not a deviation from it — seven other *-test-harness and
*test-fixtures files sit under src/main, and 98 test files sit in src/main/daemon
itself.
The class docblock described all three reasons as 'the endpoint belongs to someone
else', which is true only of 'occupied'. For 'lost' and 'inconclusive' nothing was
proven to hold the name, and the caller must decline rather than adopt something
that may not be there — daemon-entry exits 1 rather than the stand-down code, and
the launcher adopts only when its own probe connects.

Worth the sentence because that exact generalisation — an inconclusive result
described as a live owner — was a defect an earlier round had to unpick. The
comment now states the distinction instead of leaving it to be inferred.

Co-authored-by: Orca <[email protected]>
The mock's kill() was a no-op and its onExit callback was never invoked, so
tearing down a server that still held a session waited the full
IMMEDIATE_KILL_PHYSICAL_EXIT_TIMEOUT_MS for a physical exit that could never
arrive. Four tests paid 8s each.

Wiring kill/forceKill to the registered onExit matches both a real subprocess
and the convention in daemon-idle-shutdown.test.ts, and takes the file from
32.6s to 0.7s. Verified still load-bearing: neutering the createOrAttach
ownership guard fails 3 of these tests.
daemon-endpoint-ownership.ts carried more comment lines than code (176:134) and
daemon-server.ts was at 105%, both against AGENTS.md's "be concise, 1 line if
possible". Much of it restated rationale the linked design doc already covers
at length.

Trimmed to 115 and 97, keeping the non-obvious why on every subtle branch and
leaving the essays to docs/reference/daemon-endpoint-ownership.md. Verified
comment-only: stripping comments from both files before and after yields
identical text.
daemon-endpoint-ownership.ts carried more comment lines than code (176:134) and
daemon-server.ts was at 105%, much of it restating the design doc these files
already link. AGENTS.md asks for brief, non-obvious notes — one line where
possible — so the essays move to docs/reference/daemon-endpoint-ownership.md
and what stays is the non-obvious why.

Comments 383 -> 302 across the production diff; not one line of logic changed,
verified by diffing both files with comments stripped.
The 480-line reference doc and the root AGENTS.md entry both loaded for every
agent on every task, to state a rule that only matters when touching the
daemon socket. Replaced by src/main/daemon/AGENTS.md, which loads only when
working in that directory — the convention tests/e2e/AGENTS.md already sets.

What survives is the invariant, the protocol, the traps that each cost a
defect (never collapse "can't tell" into "dead", no birthtime identity, no
sweeper, namespaces out of released builds' patterns) and the residual risk.
The long-form alternatives analysis is dropped.

Comments trimmed further in both large files, 302 -> 243 across the production
diff; AGENTS.md asks for brief non-obvious notes and now holds the rationale
they were duplicating. Verified comment-only: stripping comments from both
files before and after yields identical text.
Every endpoint test is skipIf(win32), and PR CI runs the suite only on
ubuntu-latest — the sole Windows job packages, it does not test. So the win32
branches of the publish protocol had no coverage on any platform.

Stubs process.platform, as ~10 suites already do, to assert the mechanism is
inert on named pipes: publish short-circuits without probing or touching the
filesystem (even when the canonical name is occupied), identity reads null,
and ownership never reports 'lost' — which is what keeps the watchdog and the
session guard from ever retiring a daemon on Windows.

Verified load-bearing: removing the win32 short-circuit fails 2, and dropping
either win32 guard on the identity/ownership reads fails 1 each.
@nwparker
nwparker merged commit bba32bd into stablyai:main Aug 8, 2026
52 checks passed
nwparker added a commit that referenced this pull request Aug 8, 2026
Three guards in daemon-health.test.ts skipped tests that assert PID-record and
start-time logic. The file's daemonTestSocketPath already returns a real named
pipe on win32, so none of them needed a Unix socket — the skips cost coverage
for nothing.

Verified on a Windows host: the file goes from 29 passed / 4 skipped to
32 passed / 1 skipped, restoring Windows coverage of killStaleDaemon's
ownership decisions, which #12882 changed.

The fourth guard stays: that test spawns a real child and binds a filesystem
socket path, which fails with listen EACCES on Windows.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…arty (stablyai#12882)

Terminals froze app-wide several times daily, needing a manual pkill. libuv
unlinks the pathname a server bound to when it closes, with no ownership check,
so a departing daemon deleted whichever socket then sat at the canonical path —
including a live replacement's. The replacement kept hosting PTYs no client
could reach.

stablyai#12709 fixed that mechanism; this replaces the shape around it. Two invariants:
only a daemon publishing itself onto the canonical endpoint may mutate that
entry, and only by replacing one it has itself just proven dead; and no actor
removes a name it did not create.

Publish binds a private name, takes the canonical one with an exclusive link,
and on EEXIST proves the incumbent dead by connecting before replacing it in a
single rename. Only 'connected' means occupied and only refused/missing prove
death — a timeout proves nothing and declines. Deletes the claim sweeper, the
reclaim tail of killStaleDaemon, and three unfenced unlinkSync(socketPath)
calls in the launcher.

Measured: rename exposed no gap across 6,525 darwin / 8,004 linux probes of a
live handover, where unlink-then-link gapped on 200 of 200.

Verified on all three platforms: full suite on macOS and Linux, and daemon
restart e2e on a real windows-2022 host. Contract in src/main/daemon/AGENTS.md.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ai#13154)

Three guards in daemon-health.test.ts skipped tests that assert PID-record and
start-time logic. The file's daemonTestSocketPath already returns a real named
pipe on win32, so none of them needed a Unix socket — the skips cost coverage
for nothing.

Verified on a Windows host: the file goes from 29 passed / 4 skipped to
32 passed / 1 skipped, restoring Windows coverage of killStaleDaemon's
ownership decisions, which stablyai#12882 changed.

The fourth guard stays: that test spawns a real child and binds a filesystem
socket path, which fails with listen EACCES on Windows.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant