# Sandboxes v2 Overview

A Sandboxes v2 sandbox is a VM restored from a stack of snapshot layers,
not a container stood up from scratch each time. That's what makes claims
fast: the work (installing the toolchain and dependencies, building the
app, seeding its data) happens once per commit and environment and is
baked into a snapshot, and every claim restores its own copy.

Every example in this guide uses one invented app: a project-tracking
SaaS with workspaces, their members (roles: owner, member, viewer),
projects and tasks, a REST API with cookie sessions, and a Postgres
database. Substitute your own app's objects, roles and endpoints.

**If you get stuck** at any step, read `cofactor sandbox guide troubleshooting`
before guessing: it is organised by symptom, in the order of the setup steps.

## Setting up a new application: feasibility first

The goal is a hermetic sandbox: the app and everything it depends on
(its databases, queues, workers and third-party services, as services,
built-ins or emulators) run inside the sandbox, seeded and reproducible
at every commit. Only the calls the app has to make to a real provider
(see the `real` verdict) leave it. A hermetic sandbox is what the agent
builds, without asking, unless it isn't feasible or the user says
otherwise.

Before anything is built, plan it (`cofactor sandbox guide plan`):
research the app, ask the human every open question at once, and get
one plan approved. Nothing is written, pushed or claimed before that
approval; after it, the sandbox is built in one pass.

Before writing a cofactor.sandbox.yaml, check what the app needs against
what a sandbox supports (`cofactor sandbox guide feasibility`): list its
databases, queues, functions, third-party services, sign-in and platform
needs, give each its verdict, tell the user the gaps, and stop and ask
about anything unsupported (the topic lists when else to stop, and
when a procedure may batch its questions). Only if a hermetic sandbox
isn't feasible, or the user asks for it, does the same topic's escape
hatch apply: a frontend-only sandbox pointed at an existing
non-production backend,
explained to the user with its pros and cons before it is built. Then
write the definition (`definition`), validate it (`cofactor sandbox
validate`), connect or push it, claim a sandbox and check its logins
(`verify`). The steps for a GitHub repository, from the first claim on a
local files or a branch through proof before merge, are in `cli`, "Setting up a new GitHub application".

For a GitHub-delivered application, never build or run the app in local
Docker (or any local container) to try a definition. A sandbox is a VM
built from the definition, not that container, so a local build proves
nothing about it and costs minutes. `validate` is the instant local
check; a claim is the real test. (A pushed application's image is built
locally by design: see `upload`.)

Setup and proof do not require a merge. Connect with `--at <branch-sha>`,
or claim `--from-local` to use local files without a user commit. Iterate
with `sync --build`, then `verify-env --at` the final source SHA. Merge only
when the user wants the definition on the default branch.

## Layers

- **platform**: Cofactor's sandbox helper, which runs your services,
  prepare commands and actions. Rebuilt only when the
  helper's contract with Cofactor changes.
- **toolchain**: `setup` from cofactor.sandbox.yaml, plus `resources` and the
  declared `ports`. Rebuilt only when those change — this is
  the expensive layer (apt packages, language runtimes,
  database clusters).
- **repo base**: The repository checked out and built at a commit:
  `lifecycle.build` steps, each rerun only when the git
  pathspecs in its `inputs` changed since the layer this one
  is stacked on. This is what makes "the same commit, again"
  nearly free.
- **ready snapshot**: One commit and one environment: the repo base moved to the
  commit, prepared, and the environment's seeds run — then
  captured while its services are running. Built once, the
  first time anything asks for that commit and environment;
  every claim is a copy of it.

A GitHub-delivered sandbox is identified by **repository + definition
path**, not by repository alone, so a monorepo can hold several (see
below). Pushed images have no repository or build layers: the image is
the base, and each push gets its own ready snapshots (see the `upload`
topic).

A GitHub application can also include several repositories in one
definition. Each version pins the definition repository and every
declared member repository together; claims and previews restore that
same set of commits. See `definition` for the YAML and paths, and `cli`
for pinning and repository-specific previews.

## The claim lifecycle

1. **snapshot**: The claim needs the ready snapshot for its commit and
   environment. If there isn't one yet, it is built first
   (once, however many claims are waiting on it):

   - the nearest layer (toolchain or repo base) is
     restored;
   - the outstanding `lifecycle.build` steps bring it to
     the commit (only the steps whose `inputs` changed);
   - `prepare` runs (see step 3);
   - the environment's seed chain runs, in order (parent's
     seeds before its own — see the `environments` topic);
     each step is an action or an emulator operation,
     and its output can be referenced by later steps;
   - the VM is captured with its services running.

2. **restore**: A copy of the ready snapshot is restored. Nothing is
   built or seeded: the copy starts exactly where the
   snapshot left off, data included.
3. **identity**: A copy whose port params are all live, with stored snapshot
   prepare results, receives public port URLs through one
   copy-values exec. The sandbox materializes
   `/var/lib/cofactor/live-env.json` for the
   running app; lifecycle.prepare does NOT run. There is no
   service restart, emulator reconfiguration or bucket creation.
   Secrets, persona passwords, emulator token/config and seeded
   storage stay exactly as captured. A user claim receives its
   private sync key by a separate exec, never in the copy-values
   exec or its file. Non-user copies cannot be synced.
   Legacy prepare runs instead when any port param is non-live,
   an env key mixes live/non-live params, or an emulator config
   references a port param; it keeps per-copy prepare and restart.
   Pinned PR-preview captures without stored prepare results
   also keep the existing copy prepare path.
4. **ready**: The sandbox reports its port URLs, persona logins, and the
   seed outputs (the same for every copy of the snapshot).
   From here it behaves like a real running instance of the
   app until it's destroyed or its lease expires. A copy is
   never reused.

`cofactor sandbox show` breaks the claim's time down into these phases.

A failure while building the snapshot (a build step, `prepare` or a seed)
fails the claims waiting on it; the next claim of that commit and
environment builds the snapshot again, so a failure that happens every
time needs a fix and a new source version. See the `verify` topic for what to do
when that happens.

A failure of the sandbox platform itself (a worker that is slow to restore,
a capture that is still running) is retried: the snapshot's build tries
again, resuming where it stopped, and so does claiming the copy when the
fleet has no room. Every claim has a time limit — 2 hours unless
`cofactor sandbox claim --timeout` sets another. A claim not ready by then
fails with the last problem it met, and a sandbox is never handed over after
it: a copy still being made at the limit is destroyed when it finishes. That
can be up to about 10 minutes of waiting for room plus the copy's prepare
after the limit, so the failure may arrive later than the limit itself.

## Applications, and where their code comes from

A sandbox is always a sandbox of a Cofactor application. How the
application's code reaches its sandboxes is its own setting:

- GitHub (`cofactor sandbox connect --application A --repo owner/name [--dir D]`):
  the `cofactor.sandbox.yaml` under `D` at each commit
  installs (`setup`) and builds (`lifecycle.build`) a checkout. A
  monorepo can connect one application per definition directory.
  Commands run **from that definition's directory** — an action's
  `run:` path, build steps and services resolve relative to where the
  `cofactor.sandbox.yaml` lives, not the repo root.
- Pushed images (`cofactor sandbox push`), for a team that gives
  Cofactor no repository access: see the `upload` topic.

Either way, each environment in the definition is one sandbox
environment of the application, and each persona one of its personas, so
test runs on that environment sign in with the sandbox's own logins.
There is no need to create the application first: `connect` or `push`
with a new application name creates it, and its sandbox `default`
environment is its default environment.

## How a test agent uses this

1. Browse what's available: `cofactor sandbox envs --application <name>`
   lists the definition's environments, actions, emulator operations,
   ports and personas.
2. Claim one: `cofactor sandbox claim --application <name> [--environment <name>] --wait`.
   Without `--environment` you get
   `default`.
3. Write the test against the claimed sandbox: drive the app through its
   port URLs, call actions to set up data the test needs
   (`cofactor sandbox run <id> <action>`), and call emulator operations
   to inspect or drive third parties (`cofactor sandbox run <id> <plugin.op>`).
4. Try uncommitted changes against it: `cofactor sandbox sync <id>`
   writes your working tree into the sandbox, then `cofactor workflow run <flow> --sandbox <id>` runs a flow on it (see the `local` topic); `cofactor sandbox claims` lists your live claims.
5. Destroy it when done: `cofactor sandbox destroy <id>`.
