fix(daemon): automatically recover failed daemons with OS-managed ownership #525
<!-- clawsweeper-pr-ack:opened item=525 -->
🦞👀
ClawSweeper picked this up.
Pull request received. I will update this pull request when review starts.
<!-- clawsweeper-review-progress:start -->
ClawSweeper review complete
ClawSweeper finished reviewing this revision. The review result is being finalized.
View the workflow run.
<!-- clawsweeper-review-progress:end -->
<!-- codex-pull-request-review-summary -->
<!-- codex-review-state:v1 {"code_review":{"commit_sha":"e897305b626ea479cb350af960a511479ff8a6c7","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} -->
<details>
<summary><strong>Codex Review Summary</strong>: ✅ Completed</summary>
This comment shows the latest Codex review activity on this pull request.
| Review | Status | Commit | Review trigger |
| --- | --- | --- | --- |
| 📝 Code Review | ✅ Completed <relative-time datetime="2026-11-28T10:36:24.312704Z">2026-11-28T10:36:24.312704Z</relative-time> | e897305 | Draft marked ready |
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.
</details>
</details>
Codex review: needs real behavior proof before merge.
What this changes
Adds an explicit daemon recovery command that archives verified prior-boot metadata on Linux and macOS.
Example: Linux metadata records boot UUID 22222222-2222-4222-8222-222222222222, while the current kernel reports 11111111-1111-4111-1111-111111111111 and the daemon socket refuses connections.
Review scores
| Measure | Result | What it means |
|---|---|---|
| Overall readiness | 🧂 unranked krab (1/6) | The focused implementation has no definite introduced bug, but automated coverage does not satisfy the required real-behavior proof gate. |
| Proof confidence | 🧂 unranked krab (1/6) | Real behavior proof is necessary before merge. See [Before merge](#before-merge). |
| Patch quality | 🐚 platinum hermit (4/6) | No actionable review findings were identified. |
Product
Kind: Feature · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: After a reboot, keep-alive calls can remain unavailable because stale daemon ownership metadata blocks replacement and no supported command clears it.
Reason: The operation provides useful future recovery for boot-aware daemons, but cannot recover older metadata such as the reported installation's state; its supported ownership contract remains an owner choice.
Merge readiness
⛔ Blocked before merge - 2 items remain
Keep open: this PR provides meaningful recovery absent from main, but the proposed recovery contract needs an owner decision.
Reviewed head: 394f080343471503f48601c7eb7dbbc0cebb2ad2
Owner decision: Required. See [Decision needed](#decision-needed).
Decision needed
Before merge
@clawsweeper re-review. The PR author or someone with repository write access can request it.Findings
None.
Tests
<details>
<summary><strong>Agent review details</strong></summary>
How this fits together
The single-user daemon retains MCP transports across CLI invocations; recovery checks kernel boot identity, authenticated socket availability, and persisted ownership metadata before allowing subsequent startup.
flowchart TD
A[Daemon recover command] --> B[Private directory and artifact checks]
B --> C[Existing singleton lock]
C --> D[Authenticated socket probe]
D --> E[Compare recorded and current boot UUID]
E --> F[Remove stale socket and archive metadata]
F --> G[Later explicit daemon startup]
Technical review
Best possible solution:
Land an owner-approved boot-backed recovery operation within the existing daemon ownership boundary, preserving ambiguous state and never replaying interrupted requests.
Do we have a high-confidence way to reproduce the issue?
Current-main source establishes the blocked-start path with existing metadata, an absent recorded PID, and an unavailable socket; the contributor also reports a base SIGKILL reproduction, but this review ran no target code.
Is this the best way to solve the issue?
Boot evidence is a focused way to distinguish reboot retirement from ambiguous same-boot crashes, and the implementation keeps the existing safety checks rather than weakening automatic startup.
AGENTS.md: found and applied where relevant.
Codex review notes: model internal, reasoning medium; reviewed against aa8d0c5ac6cd.
Provenance checked
Unexpected daemon exit and replacement refusal keeps the original intent (95edea12d715a1cc406e756832211397eb8702b6: The singleton broker change in https://github.com/openclaw/mcporter/pull/346 requires verified transport retirement and forbids replay of uncertain operations.)Testing
Proof path: in-process harness.
Security
None.
Evidence
What I checked:
src/daemon/client.ts:249, aa8d0c5ac6cd)src/daemon/recovery.ts:28, 394f08034347)src/daemon/host.ts:201, 95edea12d715)tests/daemon-recovery.integration.test.ts:20, 394f08034347)src/daemon/recovery.ts:68, 394f08034347)Likely related people:
src/daemon/client.ts)src/cli/daemon-command.ts)Preflight source
Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.
Review metrics
| Metric | Value | Why it matters |
|---|---|---|
| Patch distribution | Production +150/-4; tests +380/-1; documentation +22 | Most growth covers recovery refusal cases and real CLI lifecycle integration; the production change reuses existing locking and authentication. |
Root-cause cluster
Relationship: fixed_by_candidate
Canonical: https://github.com/openclaw/mcporter/issues/491
Summary: This PR is a constrained candidate implementation for the linked stale-singleton recovery request.
Members:
canonical: https://github.com/openclaw/mcporter/issues/491 - The report describes the same persisted metadata refusal and explicitly asks about boot identity or a supported recovery command.Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.
Labels
Label changes:
rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.Label justifications:
rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.Rating scale
6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.
Workflow
ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.
</details>
_Reviewed November 26, 2026, 12:18 PM ET / 17:18 UTC._
<!-- clawsweeper-verdict:needs-human item=525 sha=394f080343471503f48601c7eb7dbbc0cebb2ad2 confidence=high updated_at=2026-11-26T17:15:22Z reviewed_at=2026-11-26T17:18:34.063Z lease_owner=github-run-45865980263-1 lease_comment_id=7198709792 source_revision=53be355b38aaaed9f3fd19bab9bf7b5aeb514e1082b3cadf1a335ac11791f01c hold=blocked findings=0 -->
<!-- clawsweeper-review-state:blocked item=525 sha=394f080343471503f48601c7eb7dbbc0cebb2ad2 v=1 -->
<!-- clawsweeper-review-version item=525 reviewed_at=2026-11-26T17:18:34.063Z sha=394f080343471503f48601c7eb7dbbc0cebb2ad2 source_revision=53be355b38aaaed9f3fd19bab9bf7b5aeb514e1082b3cadf1a335ac11791f01c lease_owner=github-run-45865980263-1 lease_comment_id=7198709792 v=1 -->
<!-- clawsweeper-review item=525 -->
<!-- codex-review-receipt:v1 -->
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e897305b62
<details> <summary>ℹ️ About Codex in GitHub</summary>
<br/>
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
</details>
<sub><sub>!P1 Badge</sub></sub> Preserve startup-only TLS settings in managed workers
On Linux/macOS, startService supplies the worker only this whitelist; the rest of the caller environment is copied by receiveBootstrap only after Node has started. With a remote HTTPS MCP/OAuth endpoint using a private CA, a caller started with NODE_EXTRA_CA_CERTS therefore succeeds outside daemon mode but the managed daemon still uses the default trust store (node --help explicitly describes this variable as “Only read once during process startup”), so all keep-alive requests fail TLS. Pass startup-consumed Node/TLS variables into the initial service environment while continuing to exclude vault secrets.
Useful? React with 👍 / 👎.
<!-- codex-code-review-finding:v1 -->
fixed
stone-w4tch3r
I encountered different problems with mcporter daemon mode, and wanted to address one of them: issues with recovery after errors. This problem consists of 1) proper resources cleanup after previous attempt 2) smart daemon restart 3) handling of edge cases in which we still can't recover.
I audited current architecture and introduced a little bit more advanced child and resource management using OS specific process management tools (systemd, launchd, Job Objects).
Tested everything on virtual machines on all three supported operation systems.I hope this will work for users too.
So this PR is not blindly AI generated slop. I am software engineered and controlled every important decision and step.
Text below is AI generated (codex + gpt-6.2-sol medium)
---
A crashed or frozen daemon can leave subsequent keep-alive calls blocked on stale ownership. The next client now elects one recovery coordinator, retires the verified generation and starts a replacement. An operation that may already have been sent is returned as an unknown outcome and is never replayed automatically.
Process ownership is established before readiness:
systemd --userservice withKillMode=control-groupandRestart=no.No Guardian or persistent helper process is added. Recovery uses a separate cross-process lock, generation fencing, authenticated readiness, two attempts per procedure and a shared three-start/60-second budget. Sessions are rebuilt lazily from each client's resolved definitions. There is no operation journal or post-recovery notification scheme.
Managed startup transfers the caller environment through the existing authenticated endpoint before runtime initialization. Vault passwords stay out of service files, arguments, lifecycle metadata and ordinary MCP-child environments. OAuth authorization URLs travel to the initiating client over its current RPC; the client invokes the OS opener while callback/state/PKCE/token handling stays in the daemon. Foreground preserves output, cancellation and generation-specific exit status, including normal Windows Job retirement.
Native prebuilds are installed through pnpm supportedArchitectures and staged from the pinned Koffi packages. The lockfile and standard registry/offline cache settings handle acquisition and integrity. Published npm installation needs no lifecycle scripts or compiler. Rolldown/Bun bundles embed verified native bytes and use a private content-addressed cache. The official macOS packager signs Darwin addons before embedding them with the executable's Team ID; release verification now exercises a real managed daemon and cleans up failed smoke runs.
Compatibility and limits:
Daemon/runtime validation at
5f96af0a49860b0bb0972bade6a5e4f29c764cde(daemon/recovery behavior is unchanged by the packaging and help-text follow-ups):pnpm check; full macOS suite: 2,507 passed, 27 skipped across 268 passed/5 skipped test files.--ignore-scriptsnpm installs. Ten independent cold native extractions pass. A 1,500-observation process-churn stress reproduced stale-parent failures before the correction and returned zero errors afterward.The temporary acceptance harness and reports stay outside the PR. Full Windows/Linux suites, Windows interactive-console Ctrl+C, older macOS versions, a physical Windows x64 host and an official Developer ID/notarized release were not qualified. Windows x64 ran in emulation on ARM64. No real provider credentials, production configuration or host network settings were changed.
Related: #491. The original daemon exit cause in that issue remains unknown.
Packaging validation at
6a7e16d0293307a12e9dc9eff92f3aa015655fba:pnpm checkpassed. Full macOS suite passed: 2,511 tests passed, 27 skipped across 269 passed/5 skipped files, using official Bun 1.4.4 andpnpm test --maxWorkers=1 --testTimeout=90000.Help-text verification at
e897305:pnpm checkpassed,pnpm test --filter daemon-cli-commandpassed all 42 tests, and builtdaemon --helpincludes the(debug only)foreground marker.The previous rebuilt artifacts each passed cold/warm operation, interrupted-side-effect/no-replay, crash/freeze recovery, foreground crash/clean exit, owned-descendant cleanup, and standalone-to-generated execution/recovery. The current builds reproduce those exact bytes; the full runtime acceptance matrix was not repeated for this packaging-only change. Official Developer ID signing/notarization and Authenticode remain outside local verification.
GitHub CI/CodeQL for fork contributions require maintainer workflow approval. This PR remains draft.