Skip to content

fix(gateway): restart inside a marker-less LaunchAgent no longer kills its caller - #139628

Merged
steipete merged 1 commit into
mainfrom
steipete/launchd-ancestry-in-service
Sep 6, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/launchd-ancestry-in-service

Conversation

@steipete

@steipete steipete commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Related: #139393

What Problem This Solves

Fixes an issue where operators running openclaw gateway restart from inside a macOS LaunchAgent defined by a hand-written plist (one that sets OPENCLAW_LAUNCHD_LABEL but neither OPENCLAW_SERVICE_MARKER/OPENCLAW_SERVICE_KIND nor launchd's LAUNCH_JOB_LABEL/LAUNCH_JOB_NAME/XPC_SERVICE_NAME), including from an agent's shell command, would have the CLI run launchctl kickstart -k synchronously and kill its own caller; KeepAlive then relaunched the gateway with the restart command's outcome lost. gateway stop, install, and uninstall from the same position were likewise not refused. This is the tradeoff ClawSweeper flagged on #139393, which had removed the configured-label-only fallback because the detached update helper's recovery CLI inherited that label and was misdetected as in-service.

Why This Change Was Made

In-service identity now has a second signal: the new async isCurrentProcessInsideLaunchdService keeps the environment check as the fast path, then reads the PID launchd reports for the job (the same launchctl print probe readLaunchAgentRuntime is built on) and treats the caller as inside the service when that PID is in getSelfAndAncestorPidsSync(), the way the update CLI's ancestry block already works. Restart (after the system-LaunchDaemon ownership assertion), stop, maintenance park, and the install/uninstall guard use it. The ancestry walk only runs once a running PID is known. The detached update helper's recovery command inherits OPENCLAW_LAUNCHD_LABEL but is reparented to launchd once the gateway exits, so no running gateway PID is in its ancestry and it stays on the synchronous path. The update-job label check intentionally keeps the env-only rule. No new config, option, or retry; production delta is +28 lines.

User Impact

Restart from inside any managed LaunchAgent, marker-less or not, hands off to the detached helper instead of killing itself; stop, install, and uninstall refuse with the existing "run this command from an external shell" guidance. Managed-update recovery after a failed update is unchanged and still restores the service synchronously with health proof. One extra read-only launchctl print runs before these lifecycle commands. docs/cli/gateway.md documents the macOS behavior.

Evidence

  • pnpm test src/daemon/launchd.test.ts src/daemon/launchd-current-service.test.ts src/infra/update-managed-service-handoff-lifecycle.test.ts: launchd 180 passed (8 new ancestry-guard cases: restart handoff vs synchronous, stop refusal with and without --disable, park, install/uninstall refusal, legacy-label candidate, KeepAlive-relaunched service during helper recovery), current-service 4 passed, lifecycle 137 passed in the worker run. Two later lifecycle runs each dropped one variant of "transfers update ownership before CLI disconnect" at its 1 s vi.waitFor under host load averages of 150-250; the failing variant alternated (systemd, then launchd), that helper imports none of the changed modules, and a focused rerun of all four variants passed.
  • Fail-without-fix: with the detector reduced to the env-only check, all 8 new cases fail for the intended reason (no handoff scheduled, no refusal, ancestry never consulted).
  • The lifecycle recovery fixture now runs the real combined detector against the rig's fake launchctl and still reports recoveryInsideService: false with service-restore exit 0 ("restores launchd through a synchronous installed-CLI restart when the helper inherits only the configured label").
  • Sibling suites: update-command-service integration 94 passed (its module mock gained the new export), handoff command/restart-handoff/launchd-recovery/install-helpers/lifecycle 141 passed, update-cli/run.option-collisions/infra-runtime/gateway-processes 495 passed.
  • node scripts/check-changed.mjs: 37 stages passed including lint and both typecheck lanes; oxfmt, docs format check, and git diff --check clean. Codex autoreview (P0/P1): scoped-clean.

…s its caller

PR #139393 removed the configured-label-only fallback from launchd in-service
detection so the detached update helper's recovery CLI stops being misdetected
as running inside the LaunchAgent. That left a hand-written plist that sets
OPENCLAW_LAUNCHD_LABEL but neither the service marker nor launchd's own label
variables undetected, so `openclaw gateway restart` from inside such a service
ran `launchctl kickstart -k` synchronously and killed its caller.

Add a process-ancestry fallback: isCurrentProcessInsideLaunchdService keeps
the env check as the fast path, then asks launchd for the job's PID and treats
the caller as in-service when that PID is in its ancestry. Restart, stop,
maintenance park, install, and uninstall use it. The recovery CLI inherits the
label but is reparented to launchd after the gateway exits, so it stays on the
synchronous path.

Related: #139393
@clawsweeper

clawsweeper Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@steipete
steipete marked this pull request as ready for review September 6, 2026 02:17
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime cli CLI command changes size: M maintainer Maintainer-authored PR labels Sep 6, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 6, 2026
@clawsweeper

clawsweeper Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 5, 2026, 10:23 PM ET / September 6, 2026, 02:23 UTC.

ClawSweeper review

What this changes

Detect LaunchAgent membership through process ancestry so macOS lifecycle commands safely hand off restarts or refuse operations that would kill their caller.

Merge readiness

✅ Ready for maintainer review

The fix remains useful: inspected main still misses marker-less LaunchAgent ancestry. No actionable introduced defect was found, and the related merged recovery fix addresses a different side of the same detection boundary.

Priority: P2
Reviewed head: c9a6d2f435fbaf133b7da845b5dfe3a9fdbe492b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful regression coverage and no blocking finding; native behavior was not independently exercised.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied repository state identifies a member-authored PR, so the external-contributor gate does not apply. Evidence exercises the combined detector through mocked launchctl and recovery fixtures; it does not demonstrate native marker-less LaunchAgent behavior.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied repository state identifies a member-authored PR, so the external-contributor gate does not apply. Evidence exercises the combined detector through mocked launchctl and recovery fixtures; it does not demonstrate native marker-less LaunchAgent behavior.
Evidence reviewed 5 items Current main still lacks ancestry detection: The fetched main revision contains only environment-based service membership detection; the configured label alone remains insufficient.
Shared detection and lifecycle routing: The new detector preserves the environment fast path, requires a running launchd job with a PID, and compares it with the existing ancestor walker. Restart uses the existing detached handoff; stop and installation guards await detection before mutation.
Recovery compatibility coverage: Introduced tests cover marker-less descendants, external callers, destructive-operation refusal, maintenance parking, and synchronous recovery after KeepAlive relaunch. The supplied body reports fail-without-fix validation; these are supplemental tests, not native launchd proof.
Findings None None.
Security None None.

How this fits together

The macOS service manager translates Gateway lifecycle commands into launchctl operations. Identifying commands running inside the managed service determines whether restart must use a detached helper and whether destructive operations must be refused.

flowchart TD
  A[Gateway lifecycle command] --> B[Check service environment]
  B -->|No match| C[Read launchd PID and caller ancestry]
  B -->|Match| D[Inside managed service]
  C -->|Ancestor matches| D
  C -->|No match| E[Normal service operation]
  D --> F[Detached restart or mutation refusal]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +28, Tests +244, Docs +2. Total +274 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 4 43 15 +28
Tests 3 266 22 +244
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 311 37 +274

Review metrics

None.

Technical review

Best possible solution:

Keep one shared membership detector that protects in-service callers while preserving synchronous recovery for detached update helpers.

Do we have a high-confidence way to reproduce the issue?

Yes, from source: a marker-less descendant misses main's environment-only check and reaches synchronous kickstart. Native macOS reproduction was not executed in this review.

Is this the best way to solve the issue?

Yes. Reusing the existing launchd probe, ancestry walker, and detached helper repairs detection without restoring the configured-label false positive.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 41fba39c40aa.

Labels

Label changes:

  • add P2: Repairs a concrete macOS lifecycle failure limited to LaunchAgents missing service identity markers.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied repository state identifies a member-authored PR, so the external-contributor gate does not apply. Evidence exercises the combined detector through mocked launchctl and recovery fixtures; it does not demonstrate native marker-less LaunchAgent behavior.

Label justifications:

  • P2: Repairs a concrete macOS lifecycle failure limited to LaunchAgents missing service identity markers.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied repository state identifies a member-authored PR, so the external-contributor gate does not apply. Evidence exercises the combined detector through mocked launchctl and recovery fixtures; it does not demonstrate native marker-less LaunchAgent behavior.

Evidence

What I checked:

  • Current main still lacks ancestry detection: The fetched main revision contains only environment-based service membership detection; the configured label alone remains insufficient. (src/daemon/launchd-current-service.ts:5, 41fba39c40aa)
  • Shared detection and lifecycle routing: The new detector preserves the environment fast path, requires a running launchd job with a PID, and compares it with the existing ancestor walker. Restart uses the existing detached handoff; stop and installation guards await detection before mutation. (src/daemon/launchd-current-service.ts:43, c9a6d2f435fb)
  • Recovery compatibility coverage: Introduced tests cover marker-less descendants, external callers, destructive-operation refusal, maintenance parking, and synchronous recovery after KeepAlive relaunch. The supplied body reports fail-without-fix validation; these are supplemental tests, not native launchd proof. (src/daemon/launchd.test.ts:3984, c9a6d2f435fb)
  • Related merged work and routing history: Provided GitHub context confirms fix(update): report launchd service recovery correctly after a failed update #139393 merged. It deliberately removed configured-label-only detection to preserve detached update recovery; this PR retains that distinction. Main history records Peter Steinberger's work on that detector and earlier refactors. (src/daemon/launchd-current-service.ts, 31fddf425feb)
  • Inspection limits: Current source and introduced hunks were inspected without executing target code. Live GitHub reads failed to connect, and unavailable historical blobs prevented exact-line blame and release-source verification; no shipped-fix or introducing-author claim is made.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@steipete
steipete merged commit 80a8985 into main Sep 6, 2026
246 checks passed
@steipete
steipete deleted the steipete/launchd-ancestry-in-service branch September 6, 2026 02:31
@steipete

steipete commented Sep 6, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit to ylcn91/openclaw that referenced this pull request Sep 6, 2026
* origin/main:
  fix(ci): rebalance services test roots below the memory bound (openclaw#139645)
  fix(backup): exclude shared workspace files from state-only archives (openclaw#139598)
  fix(config): preserve plugin secret references in Settings saves (openclaw#139536)
  fix(ui): retain real-Gateway browser proof across reruns (openclaw#134274)
  fix(browser): preserve node filenames in proxy media (openclaw#139559)
  fix(qa): give hot-reload maintenance proofs their own budgets (openclaw#139580)
  fix(streaming): preserve assistant items and settled output (openclaw#139507)
  fix(android): reconnect secondary gateways after rapid lifecycle changes (openclaw#139319)
  fix(gateway): restart inside a marker-less LaunchAgent no longer kills its caller (openclaw#139628)
vincentkoc added a commit that referenced this pull request Sep 6, 2026
* commit 'ef5972108dc690725717613cb0c1bdaaf910c8de':
  fix(browser): preserve node filenames in proxy media (#139559)
  fix(qa): give hot-reload maintenance proofs their own budgets (#139580)
  fix(streaming): preserve assistant items and settled output (#139507)
  fix(android): reconnect secondary gateways after rapid lifecycle changes (#139319)
  fix(gateway): restart inside a marker-less LaunchAgent no longer kills its caller (#139628)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 6, 2026
…s its caller (openclaw#139628)

PR openclaw#139393 removed the configured-label-only fallback from launchd in-service
detection so the detached update helper's recovery CLI stops being misdetected
as running inside the LaunchAgent. That left a hand-written plist that sets
OPENCLAW_LAUNCHD_LABEL but neither the service marker nor launchd's own label
variables undetected, so `openclaw gateway restart` from inside such a service
ran `launchctl kickstart -k` synchronously and killed its caller.

Add a process-ancestry fallback: isCurrentProcessInsideLaunchdService keeps
the env check as the fast path, then asks launchd for the job's PID and treats
the caller as in-service when that PID is in its ancestry. Restart, stop,
maintenance park, install, and uninstall use it. The recovery CLI inherits the
label but is reparented to launchd after the gateway exits, so it stays on the
synchronous path.

Related: openclaw#139393
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant