# How the daemon-management Package Supervises Processes in Magnitude

> Discover how the daemon-management package supervises processes in Magnitude. Learn how it unifies init systems for macOS, Linux, and Windows using Effect-TS for robust ACN service orchestration.

- Repository: [Magnitude/magnitude](https://github.com/magnitudedev/magnitude)
- Tags: internals
- Published: 2026-09-08

---

**The `daemon-management` package orchestrates the lifecycle of the Magnitude ACN (Agent Client Node) service across macOS, Linux, and Windows by abstracting platform-specific init systems into a unified Effect-TS based interface.**

The `daemon-management` package in the [magnitudedev/magnitude](https://github.com/magnitudedev/magnitude) repository provides the centralized supervision layer responsible for installing, starting, monitoring, and stopping the Magnitude daemon. It ensures a single, persistent agent runs reliably by handling the transition from temporary just-in-time (JIT) processes to permanent system services.

## Core Supervision Flow

The supervision logic is implemented primarily in [[`packages/daemon-management/src/service.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts)](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts). The process follows a strict sequence to guarantee the daemon is correctly installed, healthy, and ready to accept connections.

### 1. Binary Resolution

**`resolveServiceCommand`** ([`service.ts#L39`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts#L39)) determines the exact binary path and version to launch. It checks the `ManagedServiceHost` for a custom launch command; if none is provided, it delegates to `resolveBinaryCommand` to fetch the appropriate binary for the current platform.

### 2. Platform-Specific Unit Generation

The package renders OS-specific service definitions based on the detected platform:

- **macOS**: **`renderMacServerService`** ([`service.ts#L59`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts#L59)) generates a `.plist` launch agent file.
- **Linux**: **`renderLinuxServerService`** ([`service.ts#L73`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts#L73)) generates a `systemd` user unit file.
- **Windows**: **`renderWindowsServerCommand`** builds the scheduled task command line for `schtasks`.

### 3. Installation and Activation

**`installAndStartService`** ([`service.ts#L88`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts#L88)) writes the generated unit file to the system-specific location (e.g., `~/Library/LaunchAgents`, `~/.config/systemd/user`, or the Windows Task Scheduler) and marks it as enabled. It then immediately launches the service using the native control command (`launchctl bootstrap`, `systemctl --user start`, or `schtasks /Run`).

### 4. Health Probing and Readiness

Once started, the package validates the daemon's state through a tiered health check system:

- **`probeHealth`** ([`service.ts#L65`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts#L65)) executes an HTTP GET request to `${MAGNITUDE_SERVICE_ORIGIN}/health` and decodes the response against the ACN protocol schema.
- **`probeReady`** verifies that the daemon's revision matches the current CLI version and that its internal state is `Ready`.
- **`awaitReady`** ([`service.ts#L84`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts#L84)) implements a retry loop, calling `probeReady` every 250 milliseconds for up to one minute until the service reports readiness.

### 5. JIT Process Cleanup

Before installing the persistent service, **`stopLocalAcn`** ([`service.ts#L17`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts#L17)) terminates any locally spawned JIT ACN processes. This prevents port conflicts and ensures only one daemon instance holds the fixed service port.

### 6. Orchestration Entry Point

**`startServiceManager`** ([`service.ts#L95`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts#L95)) acts as the high-level coordinator. It executes the full sequence: resolving the command, checking if an existing service matches the current release via `managedServiceIsCurrent`, stopping local JIT instances, and invoking `installAndStartService`. All errors are wrapped in the `ServerServiceError` type for consistent handling.

## Platform-Specific Supervision Details

The `daemon-management` package adapts its supervision strategy to leverage each operating system's native service manager.

### macOS via launchctl

On macOS, the package creates a launch agent at `~/Library/LaunchAgents/dev.magnitude.acn.plist`. The generated plist includes a `KeepAlive` flag that instructs `launchctl` to restart the daemon automatically if it exits unexpectedly, ensuring high availability without manual intervention.

### Linux via systemd

For Linux systems, the package generates a user-level systemd unit file at `~/.config/systemd/user/magnitude.service`. The unit configuration sets `Restart=on-failure` and directs stdout and stderr to the Magnitude-specific log directory, allowing standard journalctl inspection of daemon output.

### Windows via schtasks

On Windows, the package registers a scheduled task named **MagnitudeInference** using `schtasks`. The task command line is constructed by `renderWindowsServerCommand`, and a PowerShell configuration script (`WINDOWS_RESTART_POLICY_SCRIPT`) applies an aggressive restart policy to the task, ensuring the daemon respawns after crashes.

## Implementation with Effect-TS

All supervision operations are built on **Effect-TS** primitives (`Effect.gen`, `Effect.flatMap`, `Effect.retry`). This functional approach makes the supervision workflow composable, cancellable, and resilient to transient failures. Retry policies, error handling, and resource management are handled declaratively, allowing the complex multi-step installation process to fail gracefully and report specific error contexts.

## Practical Usage Examples

```typescript
import { startServiceManager, serviceStatus, stopService } from "@magnitudedev/daemon-management"
import { Effect } from "effect"

// Install and start the persistent Magnitude daemon
Effect.runPromise(startServiceManager())

// Check if the daemon is running and ready
Effect.runPromise(serviceStatus).then(status => {
  console.log("Daemon status:", status)
})

// Stop the persistent service and any local JIT instances
Effect.runPromise(stopService())

```

## Key Source Files

- **[[`packages/daemon-management/src/service.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts)](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts)**: Core supervision implementation including installation, health checks, and orchestration.
- **`packages/daemon-management/src/acn-jit/*`**: Helpers for managing just-in-time (JIT) ACN processes before persistent installation.
- **[`packages/daemon-management/src/binary.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/binary.ts)**: Logic for acquiring the correct binary version and emitting acquisition events.
- **[`packages/daemon-management/src/version.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/version.ts)**: Defines the current daemon target (`DAEMON_TARGET`) and version constants.
- **[`packages/daemon-management/src/errors.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/errors.ts)**: Typed error definitions including `ServerServiceError` and `AcnAdministrationFailed`.

## Summary

- The `daemon-management` package provides a unified abstraction over **macOS `launchctl`**, **Linux `systemd`**, and **Windows `schtasks`**.
- **`startServiceManager`** in [`service.ts`](https://github.com/magnitudedev/magnitude/blob/main/service.ts) is the primary entry point for orchestrating daemon installation and startup.
- Health verification via **`probeReady`** and **`awaitReady`** ensures the daemon is running and version-compatible before the CLI proceeds.
- The package manages the transition from **JIT processes** to persistent system services, ensuring no port conflicts occur.
- Built on **Effect-TS**, the supervision system offers composable, failure-resistant process management with structured error reporting.

## Frequently Asked Questions

### What happens if the Magnitude daemon crashes on macOS?

The `KeepAlive` flag in the generated `.plist` file (created by `renderMacServerService`) instructs `launchctl` to restart the service automatically if it exits unexpectedly. This ensures the daemon remains available without requiring manual intervention after a crash.

### How does the package prevent multiple ACN instances from running simultaneously?

Before installing a persistent service, the `stopLocalAcn` function terminates any locally spawned JIT processes. This cleanup guarantees that only one daemon instance—either the JIT version for temporary use or the persistent system service—holds the fixed network port at any given time.

### Can I specify a custom binary path instead of using the auto-resolved one?

Yes. The `resolveServiceCommand` function checks the `ManagedServiceHost` interface for a custom launch command. If provided, the package bypasses the default `resolveBinaryCommand` logic and uses your specified binary path and arguments for the service installation.

### What is the timeout for waiting for the service to become ready?

The `awaitReady` function implements a spaced-retry schedule that polls every 250 milliseconds for approximately one minute. If the daemon does not report a `Ready` state within this window, the operation fails with a timeout error wrapped in `ServerServiceError`.