Gitwami

NixOS sandbox fleet

A forkable, stateful, NixOS-native execution layer for agent code — provisioned with nixos-anywhere, disko and Firecracker.

Companion to activegraph-continuity-plan.md. That plan covers the graph/event/behavior layer and lists "sandboxes" as §5; this document is the deep dive on the execution layer: a NixOS-native, forkable, stateful sandbox fleet provisioned with nixos-anywhere + disko on Hetzner (or any cloud), and how it plugs into the existing Haskell code.

Status: research / proposal. No schema or code has changed yet.


1. Framing: this is the EC2 path you already built

Gitoku's AWS backend is already the correct lifecycle: provision a VM → cloud-init fetches a signed payload over HTTP → the runner executes → results POST back to the callback handler → teardown. The NixOS version is the same protocol with three swaps, so it is a third backend, not a rewrite.

EC2 path (exists)NixOS-anywhere path (proposed)Code today
aws ec2 run-instances + AMIFirecracker microVM, guest = a Nix derivationprovisionAwsWorkflowVm (IsolatedExecution.hs:602)
cloud-init bootstrapguest init runs ${gitoku}/bin/App from /nix/storerenderWorkflowVmCloudInit (WorkflowRun.hs:396)
ephemeral EBS volumeZFS clone of a parent snapshot; snapshot on finish—
terminate-instancesstop microVM, optionally zfs destroy the cloneWorkflowVmCleanup

The payload contract (WorkflowVmPayload, PromptRunnerEnvironment) and the HTTP callback handlers (WorkflowRunStepIsolatedCallbackAction, etc.) are reused verbatim.


2. Provisioning: nixos-anywhere + disko + Hetzner

Sandbox hosts are flake nixosConfigurations, flashed with:

nixos-anywhere --flake .#sandbox-host root@<hetzner-ip>

disko declares the disk layout — and this is where ZFS goes (small ext4/xfs root + a ZFS data pool for workspaces). Because each host is a reproducible artifact:

  • Scale = flash more boxes. Hosts are cattle; a new sandbox host is one command and registers itself with the control plane.
  • Hetzner fit: prefer dedicated / Robot bare-metal — reliable nested KVM
    • local NVMe, ideal for Firecracker + ZFS. Hetzner Cloud KVM-nesting varies by plan; verify before relying on it.
  • Host config bundles: KVM, microvm.nix, the gitoku runner closure, the attic substituter (the attic service on port 8093 already exists) so guest closures are pre-cached, and an egress-allowlisted firewall.

This is the "build, but only the thin layer" move: a NixOS-native fleet on commodity Hetzner — no e2b/Modal lock-in, no whole platform to maintain.


3. Isolation primitive: microvm.nix (Firecracker), tiered

Each run = one Firecracker microVM defined by microvm.nix:

  • Image = derivation. Guest mounts /nix/store read-only via virtiofs (or a squashfs of just the runner closure). The "image" is nix build — reproducible, content-addressed, shared through attic. No Docker, no registry.

  • Workspace = virtio-blk on a ZFS zvol (or a dataset over virtiofs) — the per-run filesystem-as-memory.

  • Network = private tap + NAT, egress-allowlisted to the callback URL + git clone + attic only. No host FS, no Postgres, no sibling tenants — a real tenant boundary the current same-host child process lacks.

  • Tiers (reuse the resource-budget.nix tier concept):

    • microvm — untrusted / multi-tenant default (strong isolation)
    • nspawn — semi-trusted internal (container, lighter)
    • local-runner — dev (child process, current default)

    The same App runner binary runs in all three; only the wrapper changes.

Per-repo agents are backend-agnostic. A named agent (per-repo [agent.*] manifest, see developer-features §5) resolves to prompt + model + triggers and rides the existing payload contract, so an agent authored today and run on local-runner (this Nix machine) executes unchanged on the microVM fleet later. Start agents on local-runner; graduate the isolation, not the agent config.

Why NixOS wins here: reproducible guests make warm pools trivial (every base VM is identical), disko+ZFS make snapshot/fork O(1), and nixos-anywhere makes the fleet disposable.


4. Haskell: the backend interface

Turn the IsolatedExecutionBackend enum (IsolatedExecution.hs:91) into a record-of-functions and add a NixOS implementation:

data SandboxBackend = SandboxBackend
  { provision   :: ProvisionSpec -> IO SandboxHandle   -- boot microVM, optionally from a parent ZFS snapshot
  , awaitResult :: SandboxHandle -> IO RunResult        -- already HTTP-callback driven; reused as-is
  , snapshot    :: SandboxHandle -> IO SnapshotRef      -- `zfs snapshot pool/gitoku/run-<uuid>@final`
  , forkFrom    :: SnapshotRef   -> IO WorkspaceRef     -- `zfs clone` (CoW, instant)
  , teardown    :: SandboxHandle -> IO ()
  }

ProvisionSpec carries the existing payload + Maybe SnapshotRef (parent to clone) + a resource tier. The microVM implementation slots in at runLocalRunnerProcess / localRunnerProcessCommand (IsolatedExecution.hs:683/1146): clone the volume, render + start the microVM unit, hand it the signed payload URL + short-lived token via kernel cmdline. Everything downstream of the callback is unchanged.

Collapse the three current dispatch sites (parseExecutionBackend, WorkflowRun.hs:84, PromptPullRequest/Run.hs:128) onto this interface.


5. Statefulness: the dual-memory model

Two layers of memory, with the graph owning the relationship:

  • Semantic memory — the graph (Postgres, IHP/Haskell). Tasks, claims, evidence, decisions, the event log, lineage. Durable forever, queryable, small. Injected into prompts via the renderCodexPrompt seam.
  • Physical memory — the workspace snapshot (ZFS). Working tree, dep caches, build artifacts. Durable as long as referenced, large, opaque.

The graph references the filesystem; it does not store it. Add a workspace_snapshot node whose payload is a snapshot reference (pool/gitoku/run-<uuid>@final), with edges produced_by (the run) and derived_from (parent snapshot).

Carried-over memory — the one thing gitoku throws away today — becomes: boot from the latest accepted snapshot (warm caches, prior edits) and inject the relevant subgraph (what we decided and why). Both memories travel together.

Cross-host portability: since hosts are cattle, a snapshot must move between flashed boxes. zfs send | recv through minio (the existing gitoku-pr-uploads bucket pattern; S3 = "mount external storage") is the transport; the graph node holds the canonical reference and which host currently has it warm.


6. The self-improvement loop, made physical

Statefulness + the graph + ZFS converge into "branching and forking execution states":

  1. fork = zfs clone parent@snap + fork the subgraph (proposed prompt/rule patch as a proposed node).
  2. Run A and B in two microVMs from the two clones.
  3. diff = diff the two result subgraphs (claims/decisions/events) and/or git diff the two output volumes.
  4. promote = accept the proposed node + keep the winning snapshot; zfs destroy the loser.

Self-modification with lineage, with O(1) CoW forks as the substrate.


7. Fleet & performance

  • Cold start: Firecracker ~100–150 ms; closure pre-cached in attic; a warm pool of identical base microVMs makes the common case instant.
  • Resume: boot-from-snapshot = clone + Firecracker boot, near-instant.
  • Orchestration: the IHP job runner stays the orchestrator (harness outside the sandbox, as today); concurrency via the existing workflow concurrency_key + a per-host slot counter; scale out by flashing more hosts and registering them.
  • Topology: one control-plane host (app + Postgres + graph + minio) and N flashed sandbox hosts, connected over a private mesh (wireguard / Hetzner vSwitch / tailscale).

8. Decisions to nail down

  • Hetzner flavor + nested KVM — Robot bare-metal is the safe bet; confirm local NVMe for ZFS.
  • disko layout — ZFS-on-root vs. data-pool-only.
  • Snapshot GC/retention — clones are cheap but unbounded; the graph already knows which snapshots are referenced, so GC = "destroy snapshots no live node points to."
  • Control-plane ↔ sandbox-host network + egress allowlist.
  • Secrets — short-lived per-run API token already exists (created/revoked around the run); inject via kernel cmdline or virtiofs file; sops for host-level secrets.

9. Sequencing

  1. Backend interface refactor (§4) — small, unblocks everything; independent of the graph work. Matches plan §5a.
  2. sandbox-host nixos-config module (§2–3) — disko + ZFS + microvm.nix + runner closure + attic substituter; flash one box, prove a single microVM run end-to-end against the existing callback protocol.
  3. workspace_snapshot graph node + snapshot/fork (§5) — needs the graph triple from plan Phase 1.
  4. Cross-host snapshot transport via minio (§5).
  5. Self-improvement loop (§6) — capstone; needs plan Phases 2 + 4 and steps 1–3 above.

Steps 1 and 2 can start in parallel and carry most of the near-term value: real isolation for untrusted agent code + a reproducible, disposable fleet.

When implementing, scaffold the sandbox-host module and the runner-registry service into ~/nixos-config via the existing service patterns (the new-service skill).