stoker: Technical Specification #
stoker is a Tailscale-native, warm-store deployment orchestrator for heterogeneous NixOS and nix-darwin fleets. It replaces ephemeral CI builds and ad-hoc SSH pushes with persistent, warm-store hosts authenticated directly by Tailscale identity, exact derivation diffing, and crash-safe automatic rollback.
1. Problem & Goals #
Standard Nix CI deploys run on ephemeral cloud VMs with empty /nix/store directories. On a 3-line NixOS module edit, an ephemeral runner spends 95%+ of its wall-clock time re-downloading flake inputs, pulling gigabytes of already-cached store paths just to assemble etc.drv and system-units.drv, and shipping a few kilobytes of diff back to hosts that already had 99.9% of the closure on disk.
Existing tools each solve one slice of this:
deploy-rshas magic rollback and nix-darwin support, but is stateless SSH push, struggles across architectures, and lacks.drvdiffing.cominkeeps stores warm via pull-based GitOps, but forces weak hosts to build locally, has no central builder routing, and has no failure-triggered rollback.colmenadoes parallel push, but has no magic rollback and no nix-darwin support.- None use Tailscale identity as the auth and transport layer.
Design Goals #
- 15 to 25 second deploys for normal config changes on warm hosts; <5 seconds to skip unchanged hosts.
- Zero public webhooks, zero SSH keys, zero bearer tokens. All control-plane traffic stays on the tailnet and authenticates via Tailscale
WhoIs. - Exact change detection. Decide which hosts need deploying by evaluating
.drv/ output paths and comparing against what is actually running, never by path regexes. - First-class NixOS and nix-darwin. Both platforms get detached activation, closure diffs, and working automatic rollback.
- Smart build routing. Build where the store is already warm; offload heavy compiles from weak hosts to fast builders of matching architecture.
- Bulletproof rollback. A broken network config, broken Tailscale config, or self-upgrade of
stokeritself must never strand a host.
Non-Goals #
- Initial machine provisioning (use
nixos-anywhere/disko). - Secret management (keep
agenix/sops-nix). - Replacing binary caches (stoker complements
atticorcachix, it does not serve NARs itself).
2. Architecture Overview #
stoker ships as a single static Go binary (x86_64-linux, aarch64-linux, aarch64-darwin) with three subcommands:
stoker coordinator: Runs on one always-on host (e.g.,prattle). Maintains a warm git checkout and warm Nix eval-cache, evaluates the flake, diffs each target's derivation against live state, routes builds, triggers activations, and streams logs to callers.stoker agent: Runs as a root daemon on every managed host (including the coordinator host itself). Exposes a tiny Tailscale-only HTTP API for status, local builds, detached activation, and rollback confirmation.stoker(CLI): Invoked from a developer laptop or a thin GitHub Action. Connects to the coordinator over Tailscale, triggers a deploy, streams structured progress/logs, and exits with a clean status code.
[GitHub Action (tag:deploy)] or [Developer Laptop (atalanta)]
|
| HTTPS/HTTP over Tailscale (WhoIs auth)
v
+-------------------------+
| stoker coordinator | (on prattle: warm git + warm eval-cache)
+-------------------------+
| | |
Tailscale Tailscale Tailscale (WhoIs auth: coordinator node only)
v v v
+---------+ +---------+ +---------+
| prattle | | beef | |terebithia|
| (agent) | | (agent) | | (agent) |
| x86_64 | | darwin | | aarch64 |
| builder | | builder | | light |
+---------+ +---------+ +---------+
\ | /
\ v /
+-----------------+
| attic (cache) | (http://prattle:8091/dots)
+-----------------+
3. Transport & Authentication #
Stoker does not expose anything to the public internet, does not require GitHub webhooks, and does not manage SSH keys or sudoers rules.
Tailscale LocalClient.WhoIs #
Both the coordinator and every agent bind exclusively to the host's Tailscale IPv4/IPv6 address (discovered via tailscale.LocalClient.Status at startup, with retry until tailscaled is ready).
On every incoming HTTP request, the server calls LocalClient.WhoIs(ctx, req.RemoteAddr):
- If
WhoIsfails or returns no peer, reject with403 Forbidden. - Extract the peer's tags (
Node.Tags) and user login (UserProfile.LoginName). - Enforce role-based policy from config:
- Coordinator endpoints (
/deploy,/rollback): allowlisted Tailscale tags (e.g.tag:deploy) and/or specific user logins (e.g.kierank@...). - Coordinator read-only endpoints (
/status,/diff): broader tailnet allowlist (e.g. monitoring/status page or any authorized user). - Agent endpoints (
/build,/activate,/confirm,/rollback): strictly restricted to the coordinator's Tailscale node/tag (e.g.tag:stoker-coordinatoror explicit coordinator node ID). - Agent read-only endpoint (
/status): coordinator + authorized users.
- Coordinator endpoints (
Why LocalClient.WhoIs over embedded tsnet?
- Reuses each host's existing
tailscaleddaemon, routes, and MagicDNS. - Zero extra Tailscale auth keys to rotate or store in
agenix. - Zero extra nodes cluttering the tailnet admin console.
- (An optional
--tsnetmode can be added later if a host ever runs without systemtailscaled, since both expose the exact sameWhoIsinterface.)
Security Boundary #
- Agents never accept arbitrary shell commands.
/activateonly accepts a validated/nix/store/<hash>-<name>path that exists in the local store (or can be substituted from configured trusted substituters / signed cache). - The coordinator only deploys commits from its configured git repository and allowed branches (default:
main, or explicit SHA reachable from the configured remote).
4. Configuration #
Coordinator Config (/etc/stoker/coordinator.toml) #
listen_port = 7420
repo_url = "https://github.com/taciturnaxolotl/dots.git"
default_branch = "main"
workdir = "/var/lib/stoker/repo"
state_dir = "/var/lib/stoker"
cache_push_cmd = ["attic", "push", "dots"] # optional, best-effort after build
[auth]
allowed_tags = ["tag:deploy"]
allowed_users = ["kieran@dunkirk.sh"]
# Optional: read nodes from a file in the repo (like lib/deploy-targets.json)
# or declare them explicitly below.
[nodes.prattle]
address = "prattle:7421"
system = "x86_64-linux"
platform = "nixos"
flake_attr = "nixosConfigurations.prattle"
role = "builder"
[nodes.beef]
address = "beef:7421"
system = "aarch64-darwin"
platform = "darwin"
flake_attr = "darwinConfigurations.beef"
role = "builder"
extra_systems = ["aarch64-linux"] # via darwin.linux-builder VM
[nodes.terebithia]
address = "terebithia:7421"
system = "aarch64-linux"
platform = "nixos"
flake_attr = "nixosConfigurations.terebithia"
role = "light"
builder_fallback = "beef" # offload heavy compiles here
light_drv_budget = 25 # build locally if <= N trivial drvs unbuilt
Agent Config (/etc/stoker/agent.toml) #
listen_port = 7421
platform = "nixos" # or "darwin"
state_dir = "/run/stoker" # /var/run/stoker on darwin
confirm_timeout = "60s"
activation_timeout = "240s"
[auth]
allowed_nodes = ["prattle"] # Tailscale MagicDNS hostname or NodeID
allowed_tags = ["tag:stoker-coordinator"]
5. Exact .drv Diffing & Change Detection #
Regex-based path filtering (modules/ -> deploy everything) produces constant false positives. Stoker replaces it with Nix's own dependency graph:
- Coordinator runs
git fetch originin its persistent worktree (workdir) and checks out the target commit into a detached worktree (or evaluatesgit+file:///var/lib/stoker/repo?rev=<sha>). - Because the coordinator's
/nix/storeand~/.cache/nix/eval-cache-v*are persistent, flake inputs are already on disk unlessflake.lockchanged. - For each requested node (in parallel, bounded concurrency), coordinator evaluates:
topleveloutput path:nix eval --raw .#<attr>.config.system.build.toplevel.outPathtoplevelderivation path:nix eval --raw .#<attr>.config.system.build.toplevel.drvPath
- Coordinator queries
GET /statuson each target agent in parallel to get:current_system:readlink -f /run/current-systemlast_drv: last successfully activated.drvpath (recorded by agent)
- Skip rule: If
target.outPath == agent.current_system(and--forceis not set), mark the nodeunchangedand skip it completely. Total time for an unchanged node: ~3 to 5 seconds of warm eval, 0 seconds of build/copy/activate.
6. Warm-Store Build Routing #
Once the coordinator knows which nodes actually changed, it decides where each node builds.
Case A: role = "builder" (e.g., prattle, beef) #
The target host itself has CPU, RAM, and a warm /nix/store.
- Coordinator sends
POST /buildto the host's agent with{repo_url, rev, flake_attr}(or copies the.drvclosure vianix copy --derivationif the agent doesn't keep a git mirror; keeping a tiny shallow git checkout on builders avoids even copying.drvclosures). - The builder runs
nix build --no-link --print-out-pathsagainst its warm store. - If
cache_push_cmdis configured, the builder pushes newly created outputs toatticin the background (non-blocking or best-effort, never fails a deploy).
Case B: role = "light" (e.g., terebithia) #
Small VPSes have warm stores for runtime closures, so building 8 tiny config derivations (etc.drv, system-units.drv, activate.drv) locally takes ~3 seconds and requires zero network transfer. Compiling a Rust or Go package locally would thrash the VPS.
Stoker uses a two-path heuristic:
- Coordinator inspects the unbuilt derivations for the node (
nix build --dry-run --jsonor checking which.drvoutputs are missing from both the target and attic). - Fast path (config-only change): If the number of unbuilt derivations is within
light_drv_budgetand none are flagged as heavy (or all match cheap builders likeetc,unit-*,activate,nixos-system-*,dry-activate,boot.json,system-path,manifest), instructterebithia's agent to build locally directly against its warm store. - Offload path (package compile needed): Route the build to
builder_fallback(e.g.,beef, which hasaarch64-linuxviadarwin.linux-builderwith native Apple Silicon virtualization and a warm store). The builder compiles the package, pushes the output toattic, andterebithiasubstitutes only the new store paths fromatticbefore activating.
If builder_fallback is offline, stoker either falls back to building on the target (configurable) or fails cleanly with a clear reason.
7. Bulletproof Activation & Rollback Protocol #
This is the core reliability contract. Every failure mode must leave the host reachable on Tailscale and running a known-good generation.
7.1 Single-Flight Locking #
Each agent holds an exclusive file lock (/run/stoker/deploy.lock). If a deploy is already in progress, a new /activate request immediately returns 409 Conflict with the active deploy ID. The coordinator also serializes per-node deploys and cancels/queues overlapping runs cleanly.
7.2 Detached Execution (Surviving Self-Upgrades) #
If a deploy upgrades stoker-agent itself, switch-to-configuration will restart the stoker-agent service. If the switch ran as a child process of stoker-agent, systemd/launchd would kill the switch mid-flight.
Therefore, /activate never runs activation in-process:
- NixOS: Spawns a transient detached unit via
systemd-run --unit=stoker-activate-<id> --collect --no-block .... - nix-darwin: Spawns a detached job via
launchctl(or a detached helper binary outside the agent's launchd job).
7.3 State Machine & Dead-Man's Switch #
Before switching, the agent writes /run/stoker/pending.json (atomically via write + rename):
{
"deploy_id": "01J...",
"previous_path": "/nix/store/...-nixos-system-...",
"target_path": "/nix/store/...-nixos-system-...",
"previous_generation": 42,
"started_at": "2026-11-28T19:00:00Z",
"confirm_deadline": "2026-11-28T19:01:00Z",
"status": "activating"
}
Then the detached activator executes:
- Arm independent watchdog: Starts a separate detached watchdog unit (
stoker-watchdog-<id>) that sleeps untilconfirm_deadline(default: 60s after activation finishes). The watchdog is a tiny subcommand (stoker watchdog --state /run/stoker/pending.json). - Realize & register profile:
- Ensure
target_pathis present in/nix/store(substituting fromattic/cache.nixos.orgif built on a remote builder). - Set the system profile:
nix-env -p /nix/var/nix/profiles/system --set <target_path>.
- Ensure
- Activate:
- NixOS:
<target_path>/bin/switch-to-configuration switch - nix-darwin:
<target_path>/activate(note: modern nix-darwin runsactivate-user+activateas root, or usesdarwin-rebuild's exact activation sequence). - If activation exits non-zero, immediately run the rollback procedure (Section 7.4) and mark
pending.jsonasrolled_back.
- NixOS:
- Await confirmation:
- Activator updates
pending.jsonto"status": "awaiting_confirm"withconfirm_deadline = now + confirm_timeout. - Coordinator polls
GET /activation/<id>over Tailscale until it seesawaiting_confirm. - Coordinator runs optional post-activation health probes (e.g. Tailscale reachable is already proven by the HTTP call itself; optional custom checks like
systemctl is-system-running --waitor HTTP checks). - Coordinator sends
POST /confirm/<id>over Tailscale.
- Activator updates
- Confirm & disarm:
- Agent verifies
deploy_idmatchespending.json, writes"status": "confirmed", removespending.json, and stops the watchdog unit. - Because state lives in
/run/stoker/pending.json, even ifstoker-agentwas restarted by the switch, the new agent instance readspending.jsonand handlesPOST /confirm/<id>seamlessly.
- Agent verifies
- Watchdog expiry (dead-man's switch):
- If
confirm_deadlinepasses andpending.jsonstill exists without"status": "confirmed", the watchdog triggers rollback automatically. - This catches broken firewall rules, broken
tailscaled, broken DNS, crashedstoker-agent, or a crashed coordinator.
- If
7.4 Platform-Specific Rollback #
NixOS Rollback:
nix-env -p /nix/var/nix/profiles/system --set <previous_path><previous_path>/bin/switch-to-configuration switch- Record failure reason in
/var/lib/stoker/last-result.json.
nix-darwin Rollback (explicitly avoiding deploy-rs's bug):
In deploy-rs, darwin rollback fails when trying to invoke nix-darwin's generation switcher through nix-env --rollback / broken environment variables. Stoker instead rolls back deterministically using the exact saved store path:
nix-env -p /nix/var/nix/profiles/system --set <previous_path>- Execute
<previous_path>/activatedirectly with a clean root environment (PATHcontaining/nix/var/nix/profiles/default/bin:/usr/bin:/bin:/usr/sbin:/sbin). - Verify
/run/current-systemresolves to<previous_path>andtailscaledis up.
8. HTTP/RPC Wire Protocol #
Plain JSON over HTTP/1.1 (Tailscale WireGuard already provides encryption and mutual authentication; no TLS cert management needed inside the tailnet). Streaming endpoints use NDJSON (application/x-ndjson) so both CLI and GitHub Actions can render live logs cleanly.
Coordinator Endpoints #
| Method | Path | Description |
|---|---|---|
GET |
/health |
Liveness check (200 OK). |
GET |
/status |
Fleet-wide summary: per-node current rev, system path, last deploy time, health, active lock. |
POST |
/diff |
Body: {"rev": "HEAD", "nodes": []}. Evaluates and returns per-node changed bool + closure diff without deploying. |
POST |
/deploy |
Body: {"rev": "sha-or-ref", "nodes": [], "dry_run": false, "force": false}. Streams NDJSON events until all targeted nodes finish. |
POST |
/rollback |
Body: {"nodes": ["beef"]}. Manually rolls back specified nodes to their previous generation. |
Agent Endpoints #
| Method | Path | Description |
|---|---|---|
GET |
/status |
Returns {hostname, system, platform, current_system, last_drv, pending, uptime}. |
POST |
/build |
Body: {"rev": "...", "flake_attr": "...", "repo_url": "..."}. Streams build log NDJSON, ends with {out_path, drv_path, built_drvs}. |
POST |
/activate |
Body: {"deploy_id": "...", "target_path": "...", "drv_path": "..."}. Starts detached activation, returns immediately with 202 Accepted. |
GET |
/activation/{id} |
Returns current state (activating, awaiting_confirm, confirmed, rolled_back, failed) + log tail. |
POST |
/confirm/{id} |
Disarms watchdog and finalizes the deployment. |
POST |
/rollback |
Immediately rolls back to previous generation. |
NDJSON Event Schema (Coordinator -> CLI / CI) #
{"ts":"...","node":"prattle","phase":"eval","msg":"drv changed: /nix/store/..."}
{"ts":"...","node":"beef","phase":"eval","status":"skipped","msg":"unchanged"}
{"ts":"...","node":"terebithia","phase":"eval","status":"offline","error":"agent terebithia GET .../status: dial tcp ...: i/o timeout"}
An offline node is one whose agent could not be reached at all. It is a warning, not a failure: the rest of the fleet deploys, the deploy still finishes ok, and the node is caught up by the next deploy because drv diffing compares against what it actually runs.
{"ts":"...","node":"prattle","phase":"build","msg":"building 12 derivations locally"}
{"ts":"...","node":"prattle","phase":"diff","added":0,"removed":0,"updated":1,"summary":"crushling: 0.1.0 -> 0.1.1"}
{"ts":"...","node":"prattle","phase":"activate","msg":"switching generation"}
{"ts":"...","node":"prattle","phase":"confirm","status":"ok","duration_ms":14200}
9. Closure Diffing & Observability #
Before (or right after) switching, the agent computes a closure diff between previous_path and target_path using store-path runtime references (nix path-info -r or direct SQLite read of /nix/var/nix/db/db.sqlite / invoking dix if present).
- Shows added, removed, and version-bumped packages right in the CLI and GitHub Actions log.
- Stored in
/var/lib/stoker/history.jsonl(ring buffer of last 50 deploys) sostoker historyworks from anywhere on the tailnet. - Coordinator
/statusJSON is directly consumable by status pages (e.g.infra.dunkirk.sh).
10. CLI & CI Integration #
CLI UX #
stoker status # table of all nodes: rev, drift, last deploy, health
stoker diff # evaluate HEAD and show which nodes would deploy + why
stoker deploy # deploy main to all changed nodes
stoker deploy --node prattle # deploy only prattle
stoker deploy --rev <sha> # deploy a specific commit
stoker rollback prattle # roll back prattle to previous generation
GitHub Actions Integration (10-second trigger) #
The existing .github/workflows/deploy.yaml shrinks to two tiny jobs:
deploy:ubuntu-latest->tailscale/github-action(tag:deploy) -> runstoker deploy --rev ${{ github.sha }}(a single prebuilt static binary, ~5 MB, zero Nix install on the runner!). Streams the full fleet logs straight into the GitHub Actions UI and exits non-zero if any node fails.docs: stays gated onneeds: deploy, unchanged.
This keeps GitHub commit status checks, concurrency locks, and the docs gate intact while cutting runner setup from ~60s + 5.6 GiB downloads down to ~5s.
11. NixOS & nix-darwin Packaging #
The stoker flake exports:
packages.<system>.stoker— single Go binary (buildGoModule, CGO disabled on Linux).nixosModules.coordinator— systemd service (stoker-coordinator), userstoker, persistent/var/lib/stoker, Nix eval access, firewall rule allowinglisten_portontailscale0only.nixosModules.agent— systemd service (stoker-agent), runs as root (required forswitch-to-configuration), firewall rule ontailscale0only.darwinModules.agent—launchd.daemons.stoker-agent, compatible with bothnix.enable = trueand Determinate Nix (nix.enable = false, reading/nix/var/nix/profiles/default/bin).
12. Failure Modes Matrix #
| Failure | What happens | Recovery |
|---|---|---|
New config breaks tailscaled or firewall |
Coordinator cannot reach /confirm over Tailscale. |
Watchdog expires after 60s and reverts to previous_path. Tailscale comes back. |
Deploy upgrades stoker-agent itself |
Detached systemd-run / launchctl finishes switch while agent restarts. New agent reads /run/stoker/pending.json. |
Coordinator's /confirm hits the new agent and disarms watchdog. If new agent crashes on boot, watchdog reverts. |
| Coordinator crashes mid-deploy | Agent never receives /confirm. |
Watchdog reverts cleanly after 60s. |
| Activation script fails mid-switch | Detached activator catches non-zero exit. | Immediate rollback without waiting 60s; error returned to coordinator. |
| Two pushes trigger deploys simultaneously | Coordinator queues or rejects; agent file lock rejects concurrent /activate with 409. |
Second deploy runs cleanly after first completes (or evaluates latest SHA). |
attic binary cache is down |
Build still succeeds using cache.nixos.org + local warm store; cache push is best-effort. |
Warning logged; deploy succeeds. |
builder_fallback (beef) is asleep/offline |
Coordinator detects unreachable builder before starting activation. | Either falls back to local build on target (if allowed) or fails fast before touching the target's running generation. |
Host reboots while pending.json exists |
/run/stoker is tmpfs (cleared on reboot); system boots into whichever profile was last set. |
On NixOS, boot loader entries are only updated after /confirm (optional enhancement: switch-to-configuration test before confirm, boot after confirm, so even a hard power-cut during activation boots the old generation!). |
Subtle NixOS win from the last row: Running
switch-to-configuration testbefore/confirmandswitch-to-configuration bootafter/confirmmeans even a kernel panic or sudden power loss during the 60s confirmation window automatically reboots into the previous known-good generation.
13. Implementation Roadmap #
Phase 1: MVP (Working 20-second deploys) #
- Go module setup +
flake.nixwithpackages,nixosModules,darwinModules. - Tailscale
LocalClient.WhoIsmiddleware + config loader. agent:/status,/build, detached/activate,/confirm, watchdog rollback (NixOS + nix-darwin).coordinator: warm git worktree,.drv/outPathdiffing, parallel per-node deploy with NDJSON streaming.cli:stoker deploy,stoker status,stoker diff.- Wire up
prattle,terebithia,beefand swap.github/workflows/deploy.yamlto the thin trigger.
Phase 2: Smart Builder Routing & Hardening #
lightvsbuilderheuristic (inspect unbuilt.drvcount, offload heavy compiles forterebithiatobeef'slinux-builder+attic).- NixOS two-stage
test->/confirm->bootso even power-loss mid-deploy rolls back on reboot. - Integration tests in NixOS VM (
nixosTest) explicitly testing: broken firewall rollback, self-upgrade survival, and concurrent deploy locking.
Phase 3: Polish & Observability #
- Built-in closure diffing (package added/removed/updated summary in CLI & CI logs).
- Deploy history ring buffer (
stoker history,stoker rollback). - Optional
infra.dunkirk.shintegration via/status.