# Daemon attachment and local startup Albedo's API connection and its local process launcher have separate jobs. A client can attach to a supplied endpoint without reading local installation files, starting a process, or replacing one. The [localdaemon package](../cli/internal/localdaemon/lifecycle.go) owns discovery and launch. The [API adapter](../cli/internal/daemon/server.go) owns attachment and compatibility checks. [HTTP API behavior](http-api-design.md) defines the public operations. ## Connection flow 1. `Discover` reads the local record and probes its authenticated `/server` resource. It reports absence, a proven stale record, or a running daemon. Invalid records, authentication failures, unreachable endpoints, and unhealthy daemons return actionable errors. A failed health check does not authorize another launch. 2. `Attach` validates the protocol and required capabilities, then returns an API connection. Build identity is update information. A different build with the required API remains usable. 3. The ordinary interactive CLI offers to restart a running daemon when the candidate build may differ from the running one: the content digests decide when both sides hashed their code trees, the build labels otherwise, and an unprovable comparison keeps the offer. Proven sameness attaches without asking. Keeping the daemon is the default. The prompt warns that restarting interrupts active work across sessions. Scripts keep a compatible daemon and report incompatibility instead of replacing it. 4. `Launch` starts a local daemon only under the application's policy. Concurrent launchers coordinate through a persistent advisory `launcher.lock`. The daemon's storage lock remains the authority for home ownership. 5. `Upgrade` requires the exact snapshot approved by the caller. It validates the replacement executable before stopping anything, rechecks the approved target, drains the supported daemon, and launches its replacement. If the target changed, the caller must obtain fresh approval. Unknown protocols cannot authorize shutdown. `albedo daemon --stop` inspects the existing daemon without prompting or starting one. An absent or stale daemon needs no shutdown. Discovery failures are reported. Its Python kernels keep running for the next daemon to attach to. `--kernels` ends them as well, after each session saves its variables. SIGTERM to the PID in `daemon.json` runs the same shutdown as `albedo daemon --stop`: it interrupts turns and cells, stops shell commands, and keeps Python kernels for reconnection. Repeated SIGTERMs do not restart shutdown. The daemon bounds the drain and has a fallback VM stop. Those deadlines do not guarantee that every external effect has stopped. Early in startup, SIGTERM can bypass the drain or be lost. Service managers that also kill the kernel processes prevent reconnection. A protocol 2 daemon has no `/server` resource. When that route returns 404 and `daemon.json` reports a different protocol, discovery reports incompatibility. It preserves the record and does not authorize attachment, shutdown, or launch. Stop that daemon with its matching client, then launch the protocol 3 client. The current client does not call older API routes. ## Daemon service ### External declarations Home-manager and other declaration owners can supply a supported native service. For the default home, declarative services use `albedo.service` on Linux or `systems.albedo.daemon` on macOS. CLI-installed services retain their per-home names. If both are registered, clients may attach but refuse service mutations until the registrations are reconciled. Custom homes retain their per-home names. For the two stable names Albedo reads the loaded registration, not the service file. It starts a loaded idle registration with supported command arguments, the matching daemon home, and supported lifecycle settings. For a shell wrapper, Albedo recognizes the argument layout without interpreting the shell command. The declaration owner is responsible for that command. It stops that registration's authenticated daemon over HTTP. A file must still exist under the stable name, and Albedo checks only that it exists. Albedo never installs, rewrites, reloads, enables, disables, bootstraps, or uninstalls an external declaration. Reconcile or remove it through its owner. See [Manage albedo with home-manager](home-manager.md) for configuration and migration. On macOS, file edits do not change the loaded registration until its owner activates them. On Linux a changed referenced unit reports `NeedDaemonReload=yes`, and Albedo refuses to start it until the owner reloads. Albedo does not detect a declaration replaced after its last observation. The manager starts whatever it holds. Unsupported service control still permits compatible authenticated attachment. ### Linux services installed by the CLI On Linux, the first `albedo daemon install` creates, starts and enables a systemd user service. Running it again refreshes the definition without restarting the daemon or starting a stopped service. Installation requires a packaged daemon selected by `ALBEDO_DAEMON`. Checkout and AppImage launchers are unsupported. Stop a running standalone daemon before first installation. Clients start an installed service through systemd. `albedo daemon --stop` uses the existing HTTP shutdown and leaves the service stopped until a client or the user manager starts it. Add `--kernels` to try saving variables before ending the kernels. `albedo daemon uninstall` removes the service and keeps kernels for reconnection. Use `albedo daemon status` to inspect it, or `status --json` for structured output. The unit uses `KillMode=process` so daemon stops leave kernels alive, and `Restart=on-failure` so crashes restart. Exit 75 means storage is held elsewhere and does not restart. Kernels end when the user manager exits or the host reboots. A managed build mismatch prints a notice instead of offering a restart, because the CLI cannot establish which build the service would start. The CLI can attach to a compatible daemon beside an edited or unsupported unit, but refuses lifecycle changes. Fedora's unmodified global timeout-abort drop-in is supported. Other drop-ins are refused. On a systemd host, an unreachable user manager also prevents launch and shutdown. A host with no service file and no registration keeps standalone launch. The [verification sources](#implementation-and-verification) distinguish policy tests from native-manager checks. A failed or cancelled install can leave a running service or enablement links. Inspect its status before changing anything by hand. Before trying start or enable, the installer may restore its unchanged file if the original process is unchanged and no job appeared. After either attempt, it leaves configuration in place and reports what it could observe. ### macOS agents installed by the CLI On macOS, `install` creates one LaunchAgent per Albedo home. It requires an exec-only packaged or sealed launcher and a captured `PATH`. Albedo checks the loaded launchd configuration and refuses service changes when it cannot safely interpret the output. Compatible attachment still works, and a home with no service file or registration runs standalone. The agent starts at load and restarts after a failed exit. Rapid failures are throttled, with no start limit. Clients bootstrap an owned agent that is not loaded, or kickstart a loaded idle one. They never replace a loaded registration. `daemon --stop` sends the authenticated shutdown to that one daemon instance. It never asks launchd to end the service. The agent stays loaded and idle, and kernels survive for the next start. `--kernels` ends the kernels too, and it needs a running daemon to ask. A daemon that keeps failing at startup stays in a retry loop. Status reports it as retrying, and stop cannot end it because no daemon is ready to ask. For a CLI-owned agent, `albedo daemon uninstall` removes the registration. For a home-manager agent, disable `services.albedo.enable` and activate the configuration. The agent lives in the GUI user domain. Without a GUI session, a home that has a service file refuses service changes. A home without one still runs standalone. Running `install` again on a loaded agent rewrites only its file. There is no reload step. The loaded registration keeps its old definition, a running daemon keeps running, and an idle agent stays stopped. For a CLI-owned agent, attach still works when the file and the loaded definition differ, but start refuses. Run `uninstall`, then `install`, to reconcile a supported difference. An edited file, a different loaded path, or a loaded definition outside the supported shape refuses every service change to a CLI-owned agent. Inspect those by hand instead. For an external declaration a failed activation can leave the old registration loaded, and Albedo starts what launchd holds. A disabled override blocks install and start, and Albedo never changes it. Status prints the `launchctl enable` command to run by hand. Uninstall still works while disabled and leaves the override in place. `uninstall` asks a managed daemon to stop first, so kernels normally survive. If that shutdown fails, the uninstall ends there and forces nothing down. Otherwise it removes the registration with one label-level `bootout` at this home's label. A replacement that arrives after the last check can be ended by that bootout, work in progress included. The checks keep every replacement they can see, but the last check and the removal are not atomic. A failed or cancelled change leaves the service file in place. Albedo does not roll it back by deleting state. The loaded-registration checks are not a guarantee against changes the manager does not report. Native-manager checks are platform-specific, as described under [verification](#implementation-and-verification). ## Authentication and defaults The daemon owns its home directory and token: by default it uses `~/.albedo` and generates a random token. It publishes `daemon.json` atomically with mode `0600` inside the private home directory. The record contains the endpoint, PID, protocol, token, and optional build identity: an `ALBEDO_BUILD` label plus a content digest of the code tree the daemon runs (sha256 over the sorted relative paths and bytes of every regular file under the application's `ebin/` and `priv/` trees, symlinks followed. The CLI hashes its candidate build with the same recipe, pinned across both implementations by the fixture in [build-digest fixtures](../test/fixtures/build-digest)). It is a local discovery file, not an API compatibility contract. Discovery checks the recorded PID against the authenticated `/server` response when the daemon reports one. The shared [`priv/bin/albedo-daemon`](../priv/bin/albedo-daemon) bootstrap installs VM defaults before Erlang starts. Source, test snapshots, and packaged startup use that bootstrap. Deliberate `ALBEDO_HOME`, `ALBEDO_TOKEN`, `ALBEDO_BUILD`, and `ERL_FLAGS` overrides remain available. Operator VM flags follow the defaults and take precedence. The local launcher filters provider overrides so saved daemon configuration remains the source of provider settings. Cancellation ends discovery, lock acquisition, startup waits, shutdown waits, and the restart prompt. It does not kill a detached daemon that has already started. A client disconnect cannot stop a daemon shared by other clients. ## Client development Use `Attach(ctx, snapshot, rediscovery)` for a validated API connection. Supply no rediscovery callback when the endpoint is fixed. A local client can supply `Rediscover`, which looks for a verified replacement without launching one. API recovery uses the supplied callback and validates the new endpoint before installing it. It does not know the client's home directory or executable. Attachment requires protocol 3 and the `durable_inputs`, `session_replay`, `collection_invalidation`, and `tool_progress` capabilities. `session_replay` requires version 2. The other required capabilities use version 1. Optional features check their own capabilities. Authentication, malformed server responses, and capability lookup failures propagate to callers. ## Implementation and verification These sources define the behavior described above: | Boundary | Implementation and evidence | | ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Discovery, launcher lock, approved replacement | [`localdaemon/lifecycle.go`](../cli/internal/localdaemon/lifecycle.go), [`lifecycle_test.go`](../cli/internal/localdaemon/lifecycle_test.go), and [`startup_test.go`](../cli/internal/localdaemon/startup_test.go). | | Compatibility and attachment | [`daemon/server.go`](../cli/internal/daemon/server.go) and [`server_test.go`](../cli/internal/daemon/server_test.go). | | Native service classification and safe control | [`localdaemon/service.go`](../cli/internal/localdaemon/service.go) and [`service_test.go`](../cli/internal/localdaemon/service_test.go). | | Declarative versus CLI-owned registrations | [`loginservice/daemon_selection.go`](../cli/internal/loginservice/daemon_selection.go) and [`daemon_selection_test.go`](../cli/internal/loginservice/daemon_selection_test.go). | | launchd parsing and mutation policy | [`daemon_launchd.go`](../cli/internal/loginservice/daemon_launchd.go), its [parser tests](../cli/internal/loginservice/daemon_launchd_test.go), and [launchd policy tests](../cli/internal/localdaemon/service_launchd_policy_test.go). | | Real CLI lifecycle workflows against controlled service managers | [`daemon_service_test.go`](../cli/test/e2e/daemon_service_test.go) and [`daemon_service_darwin_test.go`](../cli/test/e2e/daemon_service_darwin_test.go). | Controlled-manager tests establish Albedo's policy under their supplied observations. They do not prove that every systemd or macOS release produces those observations. The optional native procedures are [`service_linux.py`](../test/manual/service_linux.py) and [`service_darwin.py`](../test/manual/service_darwin.py). Their module instructions describe prerequisites and private test homes. They exercise installation, shutdown, kernel survival, and service removal against the host's real manager. A result applies to the tested host and manager version. No universal version-compatibility guarantee follows from it. For declarative activation, see [home-manager verification](home-manager.md#implementation-and-verification). For client changes, follow [Change the HTTP API](contributing-api.md) and [Client API ownership](client-api.md).