← Back to Pull requests

fix(daemon): automatically recover failed daemons with OS-managed ownership #525

Open
stone-w4tch3r opened this pull request with 3798 lines diff across 53 files
View on GitHub
stone-w4tch3r stone-w4tch3r commented on Nov 26, 2026 17:00 UTC
Author

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:

  • Linux runs a transient systemd --user service with KillMode=control-group and Restart=no.

  • macOS runs a private launchd job. Remaining process-group members are checked against kernel coalition membership and PID versions before escalation; older systems without safe signalling can complete cooperative cleanup or return a bounded manual-retirement diagnostic.

  • Windows calls Win32 through Koffi 3.3.8. The daemon holds the sole non-inherited, current-user-only kill-on-close Job handle, with no breakaway. Toolhelp snapshots, process handles, SID and exact creation times replace WMI process queries. Stale parent-PID links are excluded from ownership traversal without discarding independently requested process identities.
  • 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:

  • Linux daemon/keep-alive mode requires a functioning systemd user manager. Ordinary short-lived commands remain available without it.

  • Upgrade all invoking clients/generated bundles together; drain incompatible legacy owners with their original client first.

  • Deliberate POSIX process-group escape remains outside containment. Unverified ownership and exhausted startup budgets fail explicitly.

  • This handles daemon failure; it does not add retry semantics for a failed MCP server.
  • 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.

  • Focused final suites: Linux 52 passed; Windows 55 passed and 1 skipped.

  • Packed npm OAuth/vault migration/rollback gate and release contract tests, including failed-status cleanup.

  • SHA-256 receipt matched 917 source/build/manifest files across macOS 26.7.1 arm64, Ubuntu 24.04.3 arm64/systemd 255, and Windows ARM64 25H2 with x64 and native ARM64 Node 24.15.0.

  • Live core acceptance holds eight stdio plus two external local HTTP MCPs. It covers concurrent cold opens, warm reuse, crash/freeze, one replacement across four CLI clients, persistent API/generated-definition restoration, no replay after a side effect, late TERM-resistant descendants, complete managed cleanup and preservation of external HTTP/browser-sentinel processes. Linux uses ten independent API clients in one process for its 1 GiB VM; macOS/Windows use ten CLI processes.

  • Additional live runs cover restart budgets, interrupted bootstrap, POSIX foreground SIGINT, Windows foreground crash/clean exit, unavailable systemd with successful ordinary calls, and synthetic OAuth plus encrypted-vault recovery on all three OSes.

  • Relocated CJS/ESM/Bun bundles and standalone-to-generated keep-alive executables pass on macOS arm64 and Windows x64/ARM64. Windows uses clean --ignore-scripts npm 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 check passed. Full macOS suite passed: 2,511 tests passed, 27 skipped across 269 passed/5 skipped files, using official Bun 1.4.4 and pnpm test --maxWorkers=1 --testTimeout=90000.

  • Four new regression cases compare staged Windows/macOS x64/ARM64 addon bytes with their installed packages. The changed preparation script also passed live Windows and Ubuntu probes after normal and offline pnpm 10.34.6 installs; each probe verified all four addons and the bundled cache loader.

  • Clean-built npm/Node plus all five Bun standalone targets: macOS arm64/x64, Windows x64/ARM64, Linux ARM64. The npm tarball and all five executables are byte-for-byte identical to the previously accepted artifacts. Their sizes are unchanged. Both rebuilt macOS targets passed the macOS 13.0 deployment gate and strict ad-hoc signature verification.

  • Astra code review found no outstanding findings. The release guide now retains only the addon-signing and executable-smoke requirements; archive fetching, bespoke integrity pins, tar parsing and the separate build-time archive cache are removed.
  • Help-text verification at e897305: pnpm check passed, pnpm test --filter daemon-cli-command passed all 42 tests, and built daemon --help includes 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.

    Diff: 3798 lines (+3452 / -346) across 53 files Reviewer: stone-w4tch3r Review duration: 7876m
    All Vouch review confidence checks passed
    Residual risk 0.23 = Change Risk (0.86) × (1 − Review Confidence (0.74)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.86 · 3798 lines diff across 53 files
    0.86
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.65 · 5 substantive comment(s)
    0.65
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    73%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Self Review self_review
    0.140
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    7 items
    clawsweeper[bot] clawsweeper[bot] commented on Nov 26, 2026 17:00 UTC
    Bot

    <!-- 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 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 26, 2026 17:00 UTC
    Bot

    <!-- 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

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • 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>

    clawsweeper[bot] clawsweeper[bot] commented on Nov 26, 2026 17:19 UTC
    Bot

    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.

  • Before: Daemon startup remains blocked, requiring manual handling of internal files.

  • After: mcporter daemon recover removes the stale socket and archives metadata; a subsequent explicit start can create a daemon.
  • 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

  • Question: Should a differing same-platform kernel boot UUID authorize explicit recovery while legacy metadata, same-boot crashes, and unsupported platforms remain refused?

  • Recommendation: Accept the narrow recovery contract: Approve explicit Linux/macOS prior-boot recovery with the documented legacy and same-boot exclusions.

  • Why: This introduces a supported ownership-recovery command and persisted boot evidence; neither this PR nor its linked issue records maintainer approval of that contract.
  • Before merge

  • Add real behavior proof - After-fix recovery is supported only by automated tests; the reported manual run reproduces the base failure. The contributor must supply terminal output or a linked artifact exercising recovery through the shipped CLI, with IPs, keys, phone numbers, and non-public endpoints redacted. Persisted user.json gains bootIdentity and recovery archives that file, but fresh-install and latest-stable upgrade behavior have no supplied runtime evidence. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.

  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.
  • Findings

    None.

    Tests

  • Missing end-to-end proof: Provide a redacted shipped-CLI recovery capture showing preserved metadata and successful subsequent startup, identify any synthetic boot transition, and include a latest-stable upgrade run preserving existing settings and legacy metadata.
  • <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:

  • Current main still blocks stale singleton state: The default branch is main. Its client refuses replacement when metadata names an absent PID, and its host independently refuses existing metadata under the singleton lock; migration handles legacy per-config metadata rather than recovering user.json. (src/daemon/client.ts:249, aa8d0c5ac6cd)

  • Introduced recovery boundary: The pinned introduced diff adds recovery using the existing metadata lock, authenticated status probe, compatible boot evidence, socket unlink, and metadata rename; it neither signals processes nor launches a replacement. (src/daemon/recovery.ts:28, 394f08034347)

  • Linked request and direction: https://github.com/openclaw/mcporter/issues/491 reports blocked recovery on macOS with version 0.13.13 and proposes boot identity as possible evidence. Its discussion contains an automated review, with no recorded maintainer acceptance of this PR's contract.

  • Intentional retirement policy: The merged, maintainer-authored https://github.com/openclaw/mcporter/pull/346 established ownership verification and no replay. Its commit patch introduces both stale-state refusals. Some older local blobs were unavailable; the REST commit patch verified the relevant introduction. (src/daemon/host.ts:201, 95edea12d715)

  • Automated recovery coverage: The integration test invokes dist/cli.js, substitutes synthetic prior-boot metadata after verified process retirement, checks archival, and starts a new generation; separate cases preserve same-boot state with and without surviving descendants. (tests/daemon-recovery.integration.test.ts:20, 394f08034347)

  • Existing-state compatibility boundary: bootIdentity is added to persisted user.json through host status. Recovery explicitly rejects older metadata without it; the corresponding unit test preserves that metadata, but no latest-stable upgrade run is supplied. (src/daemon/recovery.ts:68, 394f08034347)
  • Likely related people:

  • Peter Steinberger: Raw commit 95edea12d715a1cc406e756832211397eb8702b6 adds src/daemon/client.ts:213 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 95edea12d715; files: src/daemon/client.ts)

  • HengYangDS: Raw commit 7416aedef7a663a0901fc38a60088ca6edaaf229 adds src/cli/daemon-command.ts:30 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 7416aedef7a6; files: 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:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.

  • add 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 -->

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Nov 28, 2026 10:36 UTC
    Reviewer

    <!-- 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

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • 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>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Nov 28, 2026 10:36 UTC
    Code Review
    src/daemon/service-manager.ts:1
    @@ -0,0 +1,354 @@
    +import { execFile } from 'node:child_process';
    +import { promisify } from 'node:util';
    +import fs from 'node:fs/promises';
    +import { createHash } from 'node:crypto';
    +import path from 'node:path';
    +import { processInventory } from './process-retirement.js';
    +import { daemonRunDir } from './paths.js';
    +import { isGeneration, type ManagedOwner } from './lifecycle-state.js';
    +
    +const exec = promisify(execFile);
    +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
    +export interface ServiceReference {
    +  kind: 'systemd' | 'launchd';
    +  name: string;
    +  domain?: string;
    +}
    +export function serviceReference(generation: string, platform = process.platform): ServiceReference {
    +  if (!isGeneration(generation)) throw new Error('Invalid daemon generation.');
    +  const namespace = createHash('sha256').update(daemonRunDir()).digest('hex').slice(0, 16);
    +  if (platform === 'linux') return { kind: 'systemd', name: `mcporter-${namespace}-${generation}.service` };
    +  if (platform === 'darwin')
    +    return {
    +      kind: 'launchd',
    +      name: `com.mcporter.${namespace}.${generation}`,
    +      domain: `gui/${process.getuid?.() ?? 0}`,
    +    };
    +  throw new Error('Managed daemon requires systemd --user, launchd, or Windows Job Objects.');
    +}
    +export async function resolveServiceReference(generation: string): Promise<ServiceReference> {
    +  const ref = serviceReference(generation);
    +  if (ref.kind === 'launchd') {
    +    try {
    +      await exec('launchctl', ['print', ref.domain!], { timeout: 3000 });
    +    } catch {
    +      ref.domain = `user/${process.getuid?.() ?? 0}`;
    +      await exec('launchctl', ['print', ref.domain], { timeout: 3000 });
    +    }
    +  }
    +  return ref;
    +}
    +export const generationOutputPath = (generation: string) => path.join(daemonRunDir(), `output-${generation}.log`);
    +export const generationExitPath = (generation: string) => path.join(daemonRunDir(), `exit-${generation}.json`);
    +const plistPath = (generation: string) => path.join(daemonRunDir(), `service-${generation}.plist`);
    +const target = (ref: ServiceReference) => `${ref.domain}/${ref.name}`;
    +function verified(owner: ManagedOwner): ServiceReference {
    +  const expected = serviceReference(owner.generation);
    +  if (expected.kind === 'launchd' && owner.service?.domain === `user/${process.getuid?.() ?? 0}`)
    +    expected.domain = owner.service.domain;
    +  if (
    +    owner.service?.kind !== expected.kind ||
    +    owner.service.name !== expected.name ||
    +    owner.service.domain !== expected.domain
    +  )
    +    throw new Error('Unverified daemon service reference.');
    +  return expected;
    +}
    +function escapeXml(value: string): string {
    +  return value.replace(
    +    /[<>&"']/g,
    +    (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;' })[c]!
    +  );
    +}
    +export function launchdPlist(
    +  ref: ServiceReference,
    +  command: string,
    +  args: readonly string[],
    +  env: NodeJS.ProcessEnv,
    +  output: string
    +): string {
    +  return `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>${escapeXml(ref.name)}</string><key>ProgramArguments</key><array>${[command, ...args].map((v) => `<string>${escapeXml(v)}</string>`).join('')}</array><key>EnvironmentVariables</key><dict>${Object.entries(
    +    env
    +  )
    +    .filter(([, v]) => v !== undefined)
    +    .map(([k, v]) => `<key>${escapeXml(k)}</key><string>${escapeXml(v!)}</string>`)
    +    .join(
    +      ''
    +    )}</dict><key>WorkingDirectory</key><string>${escapeXml(daemonRunDir())}</string><key>RunAtLoad</key><true/><key>KeepAlive</key><false/><key>AbandonProcessGroup</key><false/><key>ExitTimeOut</key><integer>2</integer><key>StandardOutPath</key><string>${escapeXml(output)}</string><key>StandardErrorPath</key><string>${escapeXml(output)}</string></dict></plist>`;
    +}
    +export function serviceEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
    +  const allowed = [

    <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 -->

    stone-w4tch3r stone-w4tch3r commented on code on Nov 30, 2026 07:25 UTC
    Code Review
    src/daemon/service-manager.ts:1
    @@ -0,0 +1,354 @@
    +import { execFile } from 'node:child_process';
    +import { promisify } from 'node:util';
    +import fs from 'node:fs/promises';
    +import { createHash } from 'node:crypto';
    +import path from 'node:path';
    +import { processInventory } from './process-retirement.js';
    +import { daemonRunDir } from './paths.js';
    +import { isGeneration, type ManagedOwner } from './lifecycle-state.js';
    +
    +const exec = promisify(execFile);
    +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
    +export interface ServiceReference {
    +  kind: 'systemd' | 'launchd';
    +  name: string;
    +  domain?: string;
    +}
    +export function serviceReference(generation: string, platform = process.platform): ServiceReference {
    +  if (!isGeneration(generation)) throw new Error('Invalid daemon generation.');
    +  const namespace = createHash('sha256').update(daemonRunDir()).digest('hex').slice(0, 16);
    +  if (platform === 'linux') return { kind: 'systemd', name: `mcporter-${namespace}-${generation}.service` };
    +  if (platform === 'darwin')
    +    return {
    +      kind: 'launchd',
    +      name: `com.mcporter.${namespace}.${generation}`,
    +      domain: `gui/${process.getuid?.() ?? 0}`,
    +    };
    +  throw new Error('Managed daemon requires systemd --user, launchd, or Windows Job Objects.');
    +}
    +export async function resolveServiceReference(generation: string): Promise<ServiceReference> {
    +  const ref = serviceReference(generation);
    +  if (ref.kind === 'launchd') {
    +    try {
    +      await exec('launchctl', ['print', ref.domain!], { timeout: 3000 });
    +    } catch {
    +      ref.domain = `user/${process.getuid?.() ?? 0}`;
    +      await exec('launchctl', ['print', ref.domain], { timeout: 3000 });
    +    }
    +  }
    +  return ref;
    +}
    +export const generationOutputPath = (generation: string) => path.join(daemonRunDir(), `output-${generation}.log`);
    +export const generationExitPath = (generation: string) => path.join(daemonRunDir(), `exit-${generation}.json`);
    +const plistPath = (generation: string) => path.join(daemonRunDir(), `service-${generation}.plist`);
    +const target = (ref: ServiceReference) => `${ref.domain}/${ref.name}`;
    +function verified(owner: ManagedOwner): ServiceReference {
    +  const expected = serviceReference(owner.generation);
    +  if (expected.kind === 'launchd' && owner.service?.domain === `user/${process.getuid?.() ?? 0}`)
    +    expected.domain = owner.service.domain;
    +  if (
    +    owner.service?.kind !== expected.kind ||
    +    owner.service.name !== expected.name ||
    +    owner.service.domain !== expected.domain
    +  )
    +    throw new Error('Unverified daemon service reference.');
    +  return expected;
    +}
    +function escapeXml(value: string): string {
    +  return value.replace(
    +    /[<>&"']/g,
    +    (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&apos;' })[c]!
    +  );
    +}
    +export function launchdPlist(
    +  ref: ServiceReference,
    +  command: string,
    +  args: readonly string[],
    +  env: NodeJS.ProcessEnv,
    +  output: string
    +): string {
    +  return `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>${escapeXml(ref.name)}</string><key>ProgramArguments</key><array>${[command, ...args].map((v) => `<string>${escapeXml(v)}</string>`).join('')}</array><key>EnvironmentVariables</key><dict>${Object.entries(
    +    env
    +  )
    +    .filter(([, v]) => v !== undefined)
    +    .map(([k, v]) => `<key>${escapeXml(k)}</key><string>${escapeXml(v!)}</string>`)
    +    .join(
    +      ''
    +    )}</dict><key>WorkingDirectory</key><string>${escapeXml(daemonRunDir())}</string><key>RunAtLoad</key><true/><key>KeepAlive</key><false/><key>AbandonProcessGroup</key><false/><key>ExitTimeOut</key><integer>2</integer><key>StandardOutPath</key><string>${escapeXml(output)}</string><key>StandardErrorPath</key><string>${escapeXml(output)}</string></dict></plist>`;
    +}
    +export function serviceEnvironment(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
    +  const allowed = [

    fixed

    Reviewers
    Assignees
    stone-w4tch3r stone-w4tch3r
    Labels
    risk: low confidence: 73.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 85.5% (HIGH) · Higher = larger blast radius
    85.5%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 73.6% · Lower = rushed or shallow review
    73.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.6% · Safe to merge
    22.6%