# How daemon-management Handles Process Supervision in Magnitude: Architecture and Import Privileges

> Discover how Magnitude's daemon-management handles process supervision with its layered stack and learn which privileged components can import it.

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

---

**daemon-management in Magnitude implements a private, layered process-supervision stack with strict import controls that restrict access to privileged bootstrap components only.**

The **daemon-management** package is the sole authority for the lifecycle of the ACN (the local inference daemon) in the Magnitude codebase. It provides deterministic, typed process coordination through a tightly-coupled set of abstractions that guarantee safe startup, shutdown, and ownership tracking. This article examines the complete supervision architecture and explains which components are permitted to import this privileged package.

## The Five-Layer Process Supervision Stack

At the core of **daemon-management process supervision** are five cooperating systems that isolate OS-level concerns from the rest of the application.

### Owner Bookkeeping with AcnOwnerStore

The `AcnOwnerStore` maintains a **single source of truth** for daemon identity. It persists one owner record containing:

- PID of the running daemon
- Process-start identity
- Health port
- Revision of the running daemon

This SQLite-backed store guarantees that every supervision operation references the exact same process, preventing race conditions and stale references.

### Graceful Shutdown via AcnDaemonShutdownSupervisor

The `AcnDaemonShutdownSupervisor` in [`src/acn-jit/acn-daemon-shutdown-supervisor.ts`](https://github.com/magnitudedev/magnitude/blob/main/src/acn-jit/acn-daemon-shutdown-supervisor.ts) implements safe termination through a **re-validated, serialized sequence**:

1. Re-check the owner record before each signal
2. Send graceful HTTP `/shutdown` request
3. Wait for process group exit
4. Escalate to **TERM → KILL** if needed

A semaphore serializes all shutdown attempts to prevent concurrent operations. The supervisor guarantees that only the daemon identified by the current owner record receives signals, returning either success or a typed `AcnDaemonShutdownFailed` error.

### Candidate Launch FSM in AcnCandidateLaunchSupervisor

The `AcnCandidateLaunchSupervisor` in [`src/acn-jit/acn-candidate-launch-supervisor.ts`](https://github.com/magnitudedev/magnitude/blob/main/src/acn-jit/acn-candidate-launch-supervisor.ts) owns the **"spawn → admit → ready" state machine** for new daemon candidates:

- Creates the process
- Monitors health
- Commits the owner row only after admission

This ensures at most one candidate launches per ensure operation, prevents overwriting newer owners, and surfaces failures as typed `FailCandidate` errors.

### Orchestration by AcnEnsuranceCoordinator

The `AcnEnsuranceCoordinator` serves as the **deterministic decision engine**. It consults `AcnConvergenceDecider` and delegates to the shutdown or launch supervisors, providing a deadline-bounded path from request to either a ready instance or typed failure. This is the internal entry point consumed by the public `MagnitudeServiceStarter`.

### Platform-Specific Service Installation

The [`service.ts`](https://github.com/magnitudedev/magnitude/blob/main/service.ts) module renders and manages OS service configurations:

| Platform | Mechanism | Commands |
|----------|-----------|----------|
| macOS | LaunchAgents | `launchctl` |
| Linux | systemd units | `systemctl` |
| Windows | Scheduled tasks | `schtasks` |

Functions like `installService`, `startInstalledService`, and `uninstallService` allow the daemon to run as a long-running OS service while the same supervision logic handles ad-hoc JIT launches.

## Privileged Import Restrictions

**daemon-management import privileges** are strictly controlled. The package is **private and internal**—no client-side code may reference its supervisors or stores directly.

### Who May Import daemon-management

Only **privileged host composition roots** can import `@magnitudedev/daemon-management`:

- **CLI bootstrap**
- **Desktop main process**
- **Development-server harness**

### Who Is Prohibited

Ordinary UI commands, web client code, and CLI commands that run after bootstrap must not depend on `daemon-management`. These components interact with the daemon through the abstracted `MagnitudeServiceStarter` only.

This architectural boundary is documented in [`AGENTS.md`](https://github.com/magnitudedev/magnitude/blob/main/AGENTS.md) at the project root and reinforced in [`cli/AGENTS.md`](https://github.com/magnitudedev/magnitude/blob/main/cli/AGENTS.md), ensuring clear separation between **process-level authority** and **client-level RPC usage**.

## Practical Code Examples

### Creating a Service Starter for SDK Consumption

```typescript
import { makeServiceStarter } from "@magnitudedev/daemon-management/src/service-starter";
import { AcnInstanceManager } from "@magnitudedev/daemon-management/src/acn-jit/acn-instance-manager";

const manager: AcnInstanceManager = /* … obtain manager … */;
export const magnitudeServiceStarter = makeServiceStarter(manager);

```

### Graceful Daemon Shutdown

```typescript
import { AcnDaemonShutdownSupervisor } from "@magnitudedev/daemon-management/src/acn-jit/acn-daemon-shutdown-supervisor";
import { Effect } from "effect";

const shutdownSupervisor = /* injected via Context */;
const owner = /* fetched from AcnOwnerStore */;
const reason = { code: "UserRequested", message: "User asked to stop" };

const shutdownEffect = shutdownSupervisor.shutdown(owner, reason);
Effect.runPromise(shutdownEffect).then(
  outcome => console.log("Shutdown outcome:", outcome),
  err => console.error("Failed to shutdown:", err)
);

```

### Installing and Starting the Service (Linux)

```typescript
import { startServiceManager } from "@magnitudedev/daemon-management/src/service";
import { Effect, Option } from "effect";

Effect.runPromise(startServiceManager())
  .then(() => console.log("Service started"))
  .catch(err => console.error("Failed to start service:", err));

```

### Querying Service Status

```typescript
import { serviceStatus } from "@magnitudedev/daemon-management/src/service";

Effect.runPromise(serviceStatus).then(status => {
  console.log("Service status:", status);
});

```

## Key Source Files

| File | Purpose |
|------|---------|
| [`packages/daemon-management/src/service.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service.ts) | Central API for service installation, startup, stop, and status queries |
| [`packages/daemon-management/src/acn-jit/acn-daemon-shutdown-supervisor.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/acn-jit/acn-daemon-shutdown-supervisor.ts) | Re-validated, serialized shutdown of exact daemon process |
| [`packages/daemon-management/src/acn-jit/acn-candidate-launch-supervisor.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/acn-jit/acn-candidate-launch-supervisor.ts) | FSM-driven spawn and admission of daemon candidates |
| [`packages/daemon-management/src/acn-jit/acn-ensurance-coordinator.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/acn-jit/acn-ensurance-coordinator.ts) | Decision coordination between shutdown and launch paths |
| [`packages/daemon-management/src/service-starter.ts`](https://github.com/magnitudedev/magnitude/blob/main/packages/daemon-management/src/service-starter.ts) | Public `MagnitudeServiceStarter` for SDK consumption |
| [`AGENTS.md`](https://github.com/magnitudedev/magnitude/blob/main/AGENTS.md) | Documents privileged import rules |
| [`design/acn/lifecycle/jit-spawning.md`](https://github.com/magnitudedev/magnitude/blob/main/design/acn/lifecycle/jit-spawning.md) | Full supervision architecture specification |

## Summary

- **daemon-management** is the exclusive owner of ACN lifecycle in Magnitude through five cooperating layers: owner store, shutdown supervisor, launch supervisor, ensurance coordinator, and service installers.
- All supervision operations are **typed, deterministic, and deadline-bounded**, with SQLite-backed ownership preventing race conditions.
- **Import privileges are restricted** to privileged bootstrap roots only; client code uses the abstracted `MagnitudeServiceStarter` interface.
- The architecture enforces clear separation between **process authority** (who can start/stop daemons) and **client capability** (who can request daemon services).

## Frequently Asked Questions

### What happens if two components try to shut down the daemon simultaneously?

The `AcnDaemonShutdownSupervisor` uses a **semaphore to serialize all shutdown attempts**. Only one shutdown operation executes at a time; concurrent requests queue and execute sequentially. This prevents signal storms and ensures each shutdown validates against the current owner record before proceeding.

### Can I use daemon-management in my Magnitude plugin or extension?

**No.** According to [`AGENTS.md`](https://github.com/magnitudedev/magnitude/blob/main/AGENTS.md) and [`cli/AGENTS.md`](https://github.com/magnitudedev/magnitude/blob/main/cli/AGENTS.md), only the CLI bootstrap, desktop main process, and development-server harness may import `daemon-management`. Plugins and extensions must interact with the daemon through the SDK's `MagnitudeServiceStarter` or higher-level APIs.

### How does the candidate launch supervisor prevent launching duplicate daemons?

The `AcnCandidateLaunchSupervisor` implements a **finite state machine with admission control**. It verifies no existing candidate is in flight before spawning, monitors health before committing the owner record, and refuses to overwrite newer owners. Failures surface as typed `FailCandidate` errors rather than silent corruption.

### Why does Magnitude use SQLite for owner tracking instead of in-memory state?

**SQLite provides durability across process crashes and restarts.** An in-memory store would lose track of daemon PIDs if the supervising process restarted, potentially orphaning daemon processes. The SQLite-backed `AcnOwnerStore` ensures the supervisor always knows which process it actually owns, regardless of its own restart history.