# Definition (cofactor.sandbox.yaml)

Everything about a sandbox lives in one file: `cofactor.sandbox.yaml`, at the
repository root or under a definition directory for a monorepo (for pushed
images, wherever you keep it — see the `upload` topic). The examples below
are fragments of one file for the guide's example app: a project tracker
with a `web` front end, an `api` server and Postgres.
`cofactor sandbox validate` checks every field below.

Required: `version`, `resources`, `ports`, `params`, `env`, `services`,
`lifecycle` and `environments`; write `{}` for one you don't use (e.g.
`params: {}`, `lifecycle: { prepare: [] }`). `personas`, `actions`, `emulation`, `object_storage`,
`databases` and `hosts` may be left out.
Names of ports, services, personas, actions, environments and plugins
are lowercase letters, digits and `-` (up to 32 characters, starting
with a letter); a seed step's `id` is lowercase letters, digits and `_`
(it is used in `${<id>.<output>}`, so no `-`).

## `version`

Always `1`. The schema version of the file itself.

## `resources`

The machine every sandbox of this application gets.

```yaml
resources: { vcpus: 2, memory_mib: 4096 }
```

## `setup`

(GitHub-delivered only.) A root shell script that installs the
toolchain: packages, language runtimes, database clusters. Runs once per
toolchain layer (keyed by this script's text plus `resources` and
`ports` — see the `overview` topic).

```yaml
setup: |
  apt-get update -qq
  apt-get install -y -qq postgresql-16 nodejs npm jq curl >/dev/null
```

## `repos`

(GitHub-delivered only.) Additional repositories checked out alongside
the repository containing this definition. The definition repository is
included automatically. For example, when this definition is in
`Acme/web`, list only the additional repositories. Members must be under
the same owner as the definition repository; otherwise resolution fails
with `SANDBOX_V2_REPO_INACCESSIBLE`, which `validate` cannot catch:

```yaml
repos:
  - github: Acme/api
  - github: Acme/worker
```

Every repository is checked out under `/workspace/<repository-name>`,
preserving the spelling of its name. Names must be unique ignoring case;
a member may not be named `repo`; a definition repository named `repo` is
fine (it is already checked out at `/workspace/repo`). `/workspace/repo`
remains a compatibility symlink to the definition repository. The
definition's setup and unscoped commands run from its directory in that
checkout.

A build step, service or action may set `repo` to a declared repository's
name. That build step runs from the repository root, and its `inputs` are
matched against that repository's Git index. A build step without `repo`
keeps using the definition directory. A service with `repo`
runs from that repository root; an action with `repo` resolves its `run`
path from that root. Build caching is tracked independently for each
repository. Uploaded images cannot use `repos` or `repo`: they are already
built, so remove those fields when validating with `--upload`.

## `previews`

(GitHub-delivered only.) Which pull requests get this application's
preview. A pull request in the definition's repository gets the preview
only if it changes a file matching `paths`. Without `previews`, every
pull request gets one. A preview that is already open keeps following its
pull request, and pull requests in member repositories (`repos`) are not
filtered.

`paths` is a non-empty list of git pathspecs relative to the definition
directory; `../` reaches files outside it. `:(glob)` is implied: do not
write it. A plain directory such as `src` or `../../packages/shared-ui`
matches everything under it, as in git. `:(exclude)` removes matches. At
least one entry must be an include. Other `:(...)` magic, the `:!` and
`:^` shorthands, a leading `!`, an empty `:(exclude)`, and braces
(`{a,b}`) are rejected. A path that climbs above the repository root is
not caught by `cofactor sandbox validate`: it fails at connect, refresh
and build time.

A repository with several applications should declare `paths` on every
one of them; `connect` and `refresh` warn about one that does not.
Two applications in one repository, one at the repository root and one at
`apps/web-marketing`:

```yaml
# cofactor.sandbox.yaml at the repository root
previews:
  paths: ["**", ":(exclude)apps/web-marketing/**"]

# apps/web-marketing/cofactor.sandbox.yaml
previews:
  paths: ["**", "../../packages/shared-ui/**", "../../bun.lock"]
```

## `ports`

Named ports the app listens on, each becoming its own public URL. Several
are normal — bundle web and API together so one sandbox serves both UI
flows and API sequences. `access: public` gets a routable URL; `private`
stays internal. At most 8 total, including the implicit `sync` port every
sandbox has (so at most 7 of your own), the `emulation` port added
automatically when `emulation` is declared, and `object-storage` when
`object_storage` is — see the `ports` topic.

```yaml
ports:
  web: { port: 3000, access: public }
  api: { port: 3001, access: public }
```

## `params`

Per-sandbox values, filled in by `prepare`, referenced from `env` as
`${params.name}`. Three shapes:

- a plain string: a fixed value, same in every sandbox.
- `{port: <name>}`: the sandbox's own public URL for that port.
  `{port: emulation}` is the emulator's public URL, allowed when
  `emulation` is declared (it is the `oidc` plugin's issuer).
- `{secret: true}`: a random value made when the version's ready
  snapshot is built, so every sandbox of that version and environment
  shares it (e.g. a session-signing key); not unique per claim.

```yaml
params:
  web_url: { port: web }
  api_url: { port: api }
  session_secret: { secret: true }
```

A port param may be `live: true`: read its resolved env at request/use time
from `/var/lib/cofactor/live-env.json`, a JSON object of env-name -> value.
A fast copy receives its URLs through one copy-values exec, which
keeps this file current using atomic replacement;
re-read when the file's inode or modification time changes. No private
Cofactor package is needed by your app.
Eligible copies with stored snapshot prepare results skip prepare and keep
services running: lifecycle.prepare does NOT run. They retain baked secrets
until the snapshot is rebuilt (the next claim, run or refresh after a secret
set or removal rebuilds it). A copy is eligible for the fast path only
when every port param is live.
Any non-live port param keeps the per-copy prepare and service restart.
An env key mixing a live port param with a non-live param also requires
prepare, as does an emulation plugin config that references a port param.
A real third-party secret (a Stripe or OpenAI key) is not a param: see
the `secrets` topic.

## `env`

Environment variables the services, prepare commands and actions run
with. `${params.name}` is substituted with that param's value. An
environment can add its own on top (see the `env` topic). A secret of
the same name (see the `secrets` topic) overrides the `env` entry.
(`${env.NAME}` is a different, narrower reference: it appears only as
the whole `url` of a `databases` entry — see the `databases` field.)

```yaml
env:
  DATABASE_URL: postgres://app@127.0.0.1:5432/app
  PUBLIC_URL: ${params.web_url}
  API_URL: ${params.api_url}
  SESSION_SECRET: ${params.session_secret}
```

## `services`

Long-running processes. `cofactor-sync` is reserved: every sandbox runs
it (the sync server, see the `local` topic). Restart a service by hand
with `cofactor sandbox exec <id> -- cofactor-sandbox restart <name>`.

```yaml
services:
  db:
    run: exec sandbox/start-postgres.sh
    health: { command: pg_isready -h 127.0.0.1 }
  api:
    run: cd api && exec npm start
    health: { http: 3001, path: /health }
    after_build: true        # don't start until lifecycle.build has produced its output
    reload_on_prepare: true  # restarted by prepare, so it sees per-sandbox env
  web:
    run: cd web && exec npm run serve
    health: { http: 3000, path: / }
    after_build: true
    reload_on_prepare: true  # reads PUBLIC_URL, API_URL and FEATURE_FLAGS
```

`health` is either `{ command: <shell> }` (checked by exit code) or
`{ http: <port>, path: </...> }`. `after_build` services start once
`lifecycle.build` has run (GitHub-delivered); in a pushed image they start
at boot, and `sync --build` restarts them after its build steps.

## `personas`

Named login identities declared here; each one's password is generated
when the snapshot is built and shared by its copies (see the `personas` topic). Only `email` is declared
in the definition.

```yaml
personas:
  owner:  { email: owner@example.test }
  member: { email: member@example.test }
  viewer: { email: viewer@example.test }
```

## `lifecycle`

- `build`: Ordered steps. GitHub-delivered: they produce the repo-base
  layer. Pushed image (already built): they run only on
  `cofactor sandbox sync <id> --build`, never at push or claim. Each has `name`, `run` (a shell command) and
  `inputs` (git pathspecs, relative to the repository root named by
  `repo`, or to the definition directory when `repo` is omitted; for
  an image, relative to its WORKDIR) — a step reruns only when the
  matching files changed in that repository, or an earlier build
  step for the same repository ran. For a definition in a monorepo
  subdirectory, inputs may use `../` to reach files elsewhere in the
  repository (for example `../../bun.lock`).

  ```yaml
  lifecycle:
    build:
      - name: install
        run: npm ci
        inputs: [package-lock.json, "**/package.json"]
  ```

- `prepare`: Shell scripts run every time a sandbox is prepared (a snapshot
  build, a legacy copy claim or an in-place move to a new commit), after services with
  `reload_on_prepare` have restarted with per-sandbox values. Each
  param is also available as `COFACTOR_PARAM_<NAME>`.

  ```yaml
  lifecycle:
    prepare:
      - bash sandbox/personas.sh
  ```

## `actions`

Typed scripts — the one way data gets into a sandbox (seeds, tests,
`cofactor sandbox run`). See the `seeds-and-actions` topic for
what makes a good one; the field shapes are:

```yaml
actions:
  create-workspace:
    description: A new workspace, created by the given persona, who becomes its owner.
    run: sandbox/actions/create-workspace.sh
    input:
      name: { type: string, required: true }
      as: { type: persona, required: true, description: Who creates it }
    output:
      workspace_id: { type: string }
    timeout: 60   # seconds, defaults to 60, max 1800
  add-member:
    description: Adds a persona to a workspace with a role.
    run: sandbox/actions/add-member.sh
    input:
      workspace_id: { type: string, required: true }
      persona: { type: persona, required: true, description: Who is added }
      role: { type: string, required: true, enum: [owner, member, viewer] }
      as: { type: persona, required: true, description: Who adds them }
```

Input properties: `type` (string | number | integer | boolean |
persona — a persona's name, checked against `personas`), `description`,
`required`, `default`, `enum`, `sensitive` (masked wherever input is
logged or returned).
Output properties: `type`, `description`.

## `emulation`

Plugin id → its config (often `{}`). Declaring any plugin here adds the
implicit, public, port-80 `emulation` port automatically — you don't
declare it yourself. See the `emulation` topic for what each plugin
intercepts. Plugin ids: `aws`, `email`, `google-oauth`, `jira`, `slack`, `oidc`
(a standard OIDC provider for the app to sign in against; see the
`authentication` topic).

```yaml
emulation:
  email: {}
```

## `object_storage`

An emulated S3 or GCS server with these buckets in every sandbox, its
standard client env given to everything that runs, and an implicit
public `object-storage` port. See the `object-storage` topic.

```yaml
object_storage: { provider: s3, buckets: [attachments] }
```

## `databases`

Postgres databases the built-in `database.fast-forward` operation can
move forward, by name: `engine` (`postgres`), `url` and `as_of` (when
the dump was captured, UTC with a `Z`). `url` is exactly one whole-string
`${env.NAME}` reference — nothing before or after it — resolved inside
the sandbox against the env actions get, including repository secrets.
See the `data-fast-forward` topic.

```yaml
databases:
  app:
    engine: postgres
    url: ${env.DATABASE_URL}
    as_of: 2026-09-30T00:00:00Z
```

## `hosts`

Hostnames that resolve to 127.0.0.1 inside every copy, for names your
app's server-side code calls that must reach a service in the same copy
(a fixture server, a callback URL, a service name from a compose file).
An image import rewrites `/etc/hosts`, and this gives one declared place
for the names: the sandbox writes them into its own block of `/etc/hosts` before any service
starts (both deliveries), keeping every other line.

```yaml
hosts: [fixtures.acme.test, callbacks.example.com, minio]
```

Loopback only: a name always means this copy's 127.0.0.1, so the service
behind it must listen there on the port the URL names, e.g.
`http://fixtures.acme.test:4010` (with `emulation` declared, ports 80 and
443 are the emulator's, so a URL without a port reaches the emulator,
not your service). A name never points outside the copy. The session
browser inside the copy resolves these names too (only preview hosts are
overridden); a browser outside the copy does not, so use a `ports` URL.
Each entry is a lowercase DNS name (letters, digits, `-`, `_` and `.`): no IP
addresses, wildcards (`*.acme.test`), ports, or `localhost`, and no
repeats; at most 50.

## `environments`

Named flavors of the same sandbox — different starting data and config.
Required, must include `default`. See the `environments` topic for the
full model (`extends`, seed steps, `${id.key}` references, `env`).

```yaml
environments:
  default:
    description: |
      Workspace "Acme", owned by the owner persona. No projects.
    seeds:
      - { id: acme, action: create-workspace, input: { name: Acme, as: owner } }
```

## Multi-line text

YAML `|` keeps line breaks (use it for multi-paragraph `description`s and
the `setup` script). YAML `>-` folds lines into one string with no
trailing newline (use it for a single long sentence, such as a long
action `description`).
