# `internal/daemon` architecture This document captures the current (pre-refactor) layout of the daemon package and the lock ordering its callers must respect. It is the baseline against which the phased split described in `~/.claude/plans/fluffy-seeking-teapot.md` is executed. ## Composition `Daemon` is the composition root. Subsystem state and locks have moved onto owning types: - Layout, config, store, runner, logger, pid — infrastructure handles. - `vmLocks vmLockSet` — per-VM `*sync.Mutex`, one per VM ID. - `createVMMu sync.Mutex` — serialises `CreateVM` (guards name uniqueness + guest IP allocation window). - `imageOpsMu sync.Mutex` — serialises image-registry mutations (`BuildImage`, `RegisterImage`, `PromoteImage`, `DeleteImage`). - `createOps opRegistry[*vmCreateOperationState]` — in-flight VM create operations, owns its own lock. - `imageBuildOps opRegistry[*imageBuildOperationState]` — in-flight image build operations, owns its own lock. - `tapPool tapPool` — TAP interface pool; owns its own lock. - `sessions sessionRegistry` — active guest session controllers; owns its own lock. - `listener`, `webListener`, `webServer`, `webURL`, `vmDNS` — networking. - `vmCaps` — registered VM capability hooks. - `imageBuild`, `requestHandler`, `guestWaitForSSH`, `guestDial`, `waitForGuestSessionReady` — injectable seams used by tests. ## Lock ordering Acquire in this order, release in reverse. Never acquire in the opposite direction. ``` vmLocks[id] → {createVMMu, imageOpsMu} → subsystem-local locks ``` Subsystem-local locks (tapPool.mu, sessionRegistry.mu, opRegistry.mu, guestSessionController.attachMu/writeMu) are leaves. They do not contend with each other. Notes: - `vmLocks[id]` is the outer lock for any operation scoped to a single VM. Acquired via `withVMLockByID` / `withVMLockByRef`. - `createVMMu` and `imageOpsMu` are narrow: each guards one family of mutations and is released before any blocking guest I/O. - Holding a subsystem-local lock while calling into guest SSH is discouraged; copy needed state out under the lock and release before blocking I/O. ## External API Only `internal/cli` imports this package. The surface is: - `daemon.Open(ctx) (*Daemon, error)` - `(*Daemon).Serve(ctx) error` - `(*Daemon).Close() error` - `daemon.Doctor(...)` — host diagnostics (no receiver). All other `*Daemon` methods are reached only through the RPC `dispatch` switch in `daemon.go` and are free to move/rename during refactoring.