spwn

How it works

An env is one worktree's running world. This page explains what spwn does for it at each step: how ports are allocated, how services start, where volumes live, how a golden snapshot is built, and what a fork or a reset actually does.

One binary, three roles

spwn is a single static binary that runs as the CLI your host calls, as the MCP server your agent calls, and as a per-user daemon that both talk to over a unix socket. The daemon hosts the engine, which performs every mutation; it is started on demand and owns the supervisor for host-process services, the job table, the log streams, the env lock and the *.localhost reverse proxy. Containers go through the docker CLI, so Podman's docker compatibility works unchanged.

Everything listens on 127.0.0.1. There is no VM, no Docker-in-Docker, and no per-env process beyond the services you declared.

Envs and worktrees

One worktree has one primary env. Running spwn up twice in the same worktree reuses the same env id and, if still free, the same port block. A fork with --worktree shared creates a child env that lives in the same worktree; its state sits under .spwn/forks/<child-slug>/ and the env verbs address it with --env <id|slug>.

State lives in two places: .spwn/ inside the worktree (the env file, logs, the agent context file, and a data/ symlink to the env's volumes), and $XDG_STATE_HOME/spwn/ for the registry of envs, ports and data roots. The user-level settings file is ~/.config/spwn/config.toml: the port range, the data root and the worktree root live there, not in the repo.

What spwn up does, in order

  1. Allocate. An env id (a ULID), a URL-safe slug, a port block and the .spwn/ directory.
  2. create hooks. Dependency installs and cache links. No service is running yet.
  3. Materialize volumes. Each [volumes.*] entry is forked from its source: empty, or a golden snapshot (built first if missing or stale).
  4. Start services and run provision hooks, in dependency order. A service that a provision hook depends_on starts first, its post_start entries run inside it, and then the hook runs (migrations and seeds, anything that needs the database up). Every service that no provision hook depends on starts after the last hook has finished. Within those constraints depends_on sets the order, independent services start concurrently, and a service waits for the health check and post_start entries of each dependency.
  5. ready hooks. Then .spwn/env and .spwn/AGENT.md are written and the env is running.

up is idempotent and resumes from any state. Each step is a no-op when its result already exists: the port block is reused, volumes are left alone if present, a hook is skipped when its inputs hash matches its last success, a running service is not restarted. A failing step marks the env failed, keeps its logs and tears nothing down, so the agent or a human can inspect it; the next up continues from there.

Ports and URLs

Every env gets one contiguous block of host ports from a machine-wide range (default 41000-49999). Each named port has a fixed offset in the block, so api is always the first port of its env and debugging stays predictable. spwn starts at hash(env.id) mod blocks, takes the first block with no registered env and no foreign listener, and records it. Forks always get a new block. Host ports are exported as environment variables, <NAME>_PORT by default or whatever env names.

One reverse proxy per machine gives every http port a URL of the form http://<route>.<slug>.localhost:8642. Chromium and Firefox resolve *.localhost internally, so there is nothing to install. The macOS system resolver does not, which means Go, Node, Python and curl should call http://127.0.0.1:<port>; AGENT.md says so. The proxy is what makes agent-driven browser testing safe: a Playwright run in env A hits web.a1b2.localhost, never env B by mistake.

Services, start order and health checks

A service is anything long-running in the env, declared the way Compose declares it: its ports, volumes, environment, secrets, profiles and health check all sit on the service. The driver is inferred from its keys: run is a host process, image a container, url an external dependency spwn only templates, and a service that exists only in an included Compose file is a Compose service. There is no stage key. A provision hook names the services it needs in depends_on; those are the infra, and everything else waits for provisioning to finish. A service that should start alongside infra is simply listed in a hook's depends_on.

Health checks (healthcheck) are http (a 2xx or 3xx), tcp (the named port accepts a connection), cmd (exit 0) or log (a regex matches a line), with a 60 s timeout and 500 ms interval by default. Every check given must pass. For a container service, cmd checks run inside the container, so no client tools are needed on the host.

Host processes are spawned in their own process group with the caller's environment, the spwn variables and [env_file] environment, and their output goes to .spwn/logs/<service>.log. A container receives only what its service declares, as in Compose: its own environment, its listed secrets, the SPWN_* variables and one variable per port it declares. Commands that must run inside a container (create a database, load fixtures) are post_start entries on the service; they run after the health check passes and before anything that depends on the service starts, and pre_stop entries run before it stops on down. Containers get spwn.env and spwn.service labels, which is how spwn doctor finds them after a crash. A service that exceeds three restarts marks the env degraded.

Volumes

Every stateful thing is a named volume, declared under [volumes.*] and mounted by the one service that owns it with Compose syntax (volumes = ["pgdata:/var/lib/postgresql/data"], or just the name for a host process, which reads {{ volumes.pgdata.path }}). spwn assumes nothing about what the service is; Postgres, Redis, MinIO and an uploads folder are all directories to it. Each volume lives in the env's data root under data_root (user config), and .spwn/data/<name> is a symlink to it. All volumes of an env sit on one filesystem, so one snapshot can capture the whole world.

The inputs hashes of provision hooks and post_start entries are stored with the volumes, so they travel with forks, snapshots and resets: a child env cloned from a migrated parent does not re-run the migration.

Golden snapshots

A golden snapshot is a seeded starting point every new env forks from. spwn builds it in a throwaway env: it starts the owners of the captured volumes and what they depend on, runs their post_start entries, the provision hooks and the snapshot's steps, runs pre_snapshot hooks (so a VACUUM can reach the database), stops the services, and captures the listed volumes. The result is keyed by the hash of its inputs, named like seeded@3f9a1c, and rebuilt only when those files change. Snapshots can stack: from = "base" builds fixtures on top of a base. After a schema or seed change only the first new env waits for seeding; every other env, on any branch, clones.

spwn snapshot <name> captures a running env's state on demand; spwn reset restores an env to the snapshot it started from, or to --to <id>, and runs post_reset hooks afterwards.

The world fork

A fork copies every volume and, by default, the worktree as one operation, while the parent keeps running. What that costs depends on the filesystem under the data root:

StrategyMechanismConsistencyCost
snapshotZFS snapshot and clone; btrfs subvolume snapshotAtomic across the whole directoryConstant time
cloneAPFS clonefile; btrfs or XFS reflinkPer file, so the service is paused during the cloneProportional to file count; sub-second for a typical dev database
copyRecursive copyAs cloneSlow; fallback only, with a warning
emptyFresh directory, then provision hooks seed itn/aSeed time
sharedChild points at the parent's dataNone: both see the same rowsFree

fork = "auto" picks snapshot on ZFS or a btrfs subvolume, clone on any filesystem with clone support, otherwise copy. Before the copy the parent is made consistent according to quiesce: checkpoint (a Postgres CHECKPOINT or Redis BGSAVE, run inside the container) is enough on atomic backends; on per-file backends pause checkpoints, then stops the owning service's whole process group (or docker pause), syncs, clones and resumes. The clone is a crash-consistent image that Postgres and Redis recover from. The fork result reports pause_ms. stop is available for engines that are not crash-safe.

Copy-on-write works within one filesystem only. spwn keeps env volumes and snapshots under one data root and refuses to fork across filesystems rather than silently copying. A cloned worktree is created as a sibling of the parent worktree for the same reason, on a new branch spwn/<child-slug>; worktree = "shared" forks only runtime state, which covers "let me try this migration on a copy of the database" without touching code.

Hooks run around the fork: pre_fork in the parent before the clone (flush queues, pause workers), post_fork in the child after the clone and before its services start (rotate per-env ids, rename buckets). The child then goes through the normal up path from provisioning, so it is a complete env of its own with new ports and a new URL.

Lifecycle states

StateMeaning
allocating, creating, provisioning, startingThe steps of up, in order.
runningAll services ready; env file and AGENT.md written.
degradedA service exceeded three restarts. up returns it to running.
stoppedServices stopped, volumes kept: the idle reaper, or the env lock parked it. up or a lock grant resumes it.
failedA step failed. Logs are kept; up resumes; down destroys.
destroyingdown or the ttl reaper: services stop, children go first, the port block and volumes are released.

The env lock

Two worktrees cost two stacks of memory. With [limits] active = 1 (or any n ≥ 1), only that many envs of a repo run at once on a machine; the rest are parked, with services stopped and volumes, ports, worktree and URL kept. spwn lock or the env_lock tool takes the slot, waiting if needed; spwn unlock or env_unlock hands it to whoever waits and parks the env. A lock holder silent for lock_idle (30 m by default: no verb, MCP call, hook run or proxy request) loses the slot. A fork made by a lock holder shares its slot. AGENT.md opens with this rule when the cap is on, so an agent locks before it runs tests and unlocks when its task is done.

Cleanup and recovery

spwn down runs teardown hooks, stops the services, destroys children first, frees the port block and removes the env's volumes. [limits] caps envs with max_envs per repo and max_forks per env, so a runaway agent cannot fill the machine. The idle timer that stops services with volumes kept and the ttl that destroys idle envs are in the spec and arrive with R21.

After a crash or kill -9, spwn doctor reconciles the registry against what is really there: processes by process group, containers by label, volume directories under the data root, ports by bind test. It reports leaks and, with --fix, removes them. It never escalates privileges.