# Seeds vs. Actions

An action is a script with a typed input and output schema. It is the one
way data gets into a sandbox — seeds call it, and so do tests and
`cofactor sandbox run`. Every environment's `seeds` list is
just an ordered sequence of action (and emulator operation) calls. For
the script contract (`INPUT_<NAME>`, the result line), see the `upload`
topic's worked example; it is the same for GitHub-delivered apps.

## A seed step that is an operation

A seed step runs exactly one of `action:` (a declared action, or an
emulator operation named `<plugin>.<op>`) or `operation:` (a platform
built-in). Today the only built-in is `database.fast-forward`, which
moves a restored database's dates forward:

```yaml
- { id: fast_forward, operation: database.fast-forward, input: { database: app } }
```

A step with both keys, or neither, fails `validate`. See the
`data-fast-forward` topic.

## What to build first

1. One persona per role your tests need. The example app has three
   roles, so it declares `owner`, `member` and `viewer`. A persona in
   the definition is only a login (prepare makes it work — see
   `personas`); its role comes from a seed action such as `add-member`,
   or from prepare itself when the persona is an account your app
   already has with the right role. With one persona per role, tests can
   sign in as each and check what that role may and may not do.
2. One environment per plan or feature-flag combination your tests care
   about: `default`, `free-plan`, `beta-features`. Set each with a seed
   action that goes through your app's admin API or database (the
   example's `set-plan`), or with the environment's `env:` when your app
   reads the flag from an environment variable (the example's
   `FEATURE_FLAGS`; see the `env` topic for which processes see it).
   Params are per definition, not per environment, so they can't vary a
   flag between environments. See the `environments` topic.
3. Actions for the few core objects nearly every test needs, each taking
   `as: <persona>`: in the example, `create-workspace`, `add-member`,
   `create-project`, `create-task`. Keep the shared seeds thin; tests
   create the rest themselves with these actions.
4. If your app has a database, include a generic `load-sql` action as
   standard sandbox setup for visual-state fixtures. See `cofactor workflow guide visual-checkpoints` for the complete example. Each test owns
   its fixture; never create a seed or action for one screen's data.
5. If your app stores files, declare `object_storage` and seed the few
   files every test needs (a logo, an import template) with an action;
   see the `object-storage` topic.

## Seeds, actions, and visual-state fixtures

First ask: where must this test run? A test that loads SQL is sandbox-only,
the usual choice for visual regression at an exact commit. If it must also
run against staging or prod, seed only through the app's API, generic
API-backed actions, or the test's own UI steps; only a sandbox exposes its
database. Checkpoint regions independent of exact data, or rely on masking.

Seeds are shared, thin, generic base data: the handful of things nearly
every test needs before it can start — a workspace and its members, one
per role. A shared seed stays thin and generic; it does not try to
anticipate every test's needs.

Actions are typed, parameterized, generic operations, API-first. A test
about archiving a project calls `create-project` for its own project,
then operates on the returned id; the operation is shared, its data is not.

Visual-state fixtures are one SQL file per screen state, beside the test,
never parameterized or shared. Use fixed, neutral values and timestamps
relative to now() so relative-time text stays stable. Load them through
the app's generic SQL action, only for rows with no encryption and no
side effects. Per-screen data never becomes a named seed or action.
Encrypted rows and side effects go through the app's API or generic
actions that call it; interaction states use UI steps.

## Setting up multiple states of a screen

Plan the meaningful states before authoring visual checkpoints: empty,
little or lots of data, mixed kinds, long content, errors, stable loading,
and limited permissions. For Cofactor's Workflows page, that might be an
empty list, three rows, and many rows with long names.

Start from the environment's thin seeds. Before each checkpoint, run the
generic actions or load that state's own SQL fixture, reload the page,
and wait for the expected visible state. When one state changes data that
should return to the environment's baseline, use the Workflow's ordinary
`sandbox.reset` action before setting up the next state:

**Sandbox action — sandbox.reset**

Reset restores the exact snapshot and version already pinned to that Run,
including its environment and a preview's captured snapshot. It does not
move to the latest version, rebuild the snapshot, or replay the earlier
setup, seed, or called-Workflow steps. Add the next state's data with
authored actions after reset. The Run's mapped browser persona is signed in
again with fresh session state; an anonymous Run remains anonymous. Add an
explicit Navigate step before the next checkpoint: reset does not guess a
destination from the previous page. The action applies to a Workflow-owned
Sandbox v2 copy, not a manually claimed sandbox or a permanent environment.
A fixture can still clear and replace only its own rows when a full-copy
reset is unnecessary. Changes outside the sandbox still need explicit
cleanup.

Use fixed neutral values, counts and ordering, with relative dates. Switch
personas through a login step for permission states; an action's `as`
input only selects who performs that action, not the browser's user.
Reproduce request errors with the Workflow-only `browser.request-fault`
action when the test runs in its own live browser. Use `mode: respond` with
an HTTP status from 200 to 599 and a valid JSON body, or `mode: hold` to keep
one exact request pending. The matcher is limited to the Run copy's declared
public Application ports and one control may be active at a time. It clears
when the next explicit Visual checkpoint finishes (including failure), and
reset, browser/persona replacement, recovery, cancellation, disconnect or Run
end also clear it. Automatic navigation/action screenshots do not consume it.
It cannot be run as an ad-hoc `cofactor sandbox run` action. A held request by
itself does not make a loading checkpoint stable; ordinary visual settling
still waits for loading to finish. Name checkpoints by page and state.
See `cofactor workflow guide visual-checkpoints` for a test with several
named checkpoints.

## What makes a good action

- Typed inputs and outputs. The input schema is what a test (or an
  agent) uses to call it correctly; the output schema is what the next
  step gets to chain from. Untyped free-form data defeats the ability to
  validate `${id.key}` references and CLI input ahead of time.
- Fast. Seeds run once per version, while its snapshot is built; calls
  run inline in a test — slow seeds slow every new version's first
  claim, and slow calls slow every test.
- Returns the ids a test needs next. `create-project` returns
  `project_id`, not just "ok" — that id is what the test's next action
  or assertion needs.
- Safe to call more than once, or unique by its own input. Either the
  action is idempotent (`set-plan` re-run with the same plan changes
  nothing), or a distinct call naturally produces a distinct result
  (`create-project` with a new name makes a new project) rather than
  silently colliding with a previous call's data.
- Explicit about who acts: the `as` persona pattern. Every action that
  performs a real business operation (creating a project, inviting a
  member) takes an explicit `as: <persona>` input naming which persona
  performs it, rather than assuming "the admin" or "whoever is logged
  in." The script signs in as exactly that persona (its login is in
  `COFACTOR_PERSONAS`) and acts in the workspace it was given; the
  persona must already have a role there that allows the operation. So
  an action has **no hidden dependency** on some other seed having run
  first to establish who's "in charge" — the caller says so, in the
  input.
- Goes through the app's own API when the data is encrypted or has side
  effects. `invite-user` calls the real invite endpoint so the
  invitation email is actually sent (and can be observed later with
  `email.sent-emails`); a raw insert would silently skip the send. The
  same goes for anything the app encrypts or hashes on write.
- For business operations, uses the database only when there is no API,
  and only for rows with no encryption and no side effects (e.g. `set-plan`).
  The generic SQL-loading action is the sanctioned DB-direct action for
  visual fixtures, even when an API exists; the same row restrictions apply.

## Anti-patterns

- A giant do-everything seed. One seed step that creates a workspace,
  three members, two projects and their tasks in one script is harder to
  reuse, harder to debug when it fails partway, and forces every test
  that wants only part of it to take all of it. Break it into separate
  actions and chain them with `${id.key}`, as `default` does.
- An action that silently acts as an admin. If an action doesn't take
  `as`, and instead assumes some fixed identity internally, a test
  writer has no way to know (or override) who actually performed the
  operation, and the action can't be reused for a test that needs a
  viewer to attempt (and be denied) the same thing.
- Hardcoded ids. An action or seed that references a specific workspace
  or project id baked into the script defeats the whole point of
  chaining `${id.key}` — every id a later step needs should come from an
  earlier step's declared output.
- An action that depends on seed ordering it doesn't declare. A script
  that assumes some other seed already ran (e.g. that a particular
  workspace exists) without that dependency showing up as an input is a
  hidden coupling — if the environment's seed order ever changes, the
  action breaks with no local sign of why. Take everything you need as
  an explicit input instead (as `create-project` takes `workspace_id`
  and `as`).
- Writing output anywhere but the last `{`-starting stdout line. The
  action's result is exactly the *last* line of stdout that starts with
  `{`. Send every progress message, debugging `echo` and intermediate
  curl response to stderr — printing one to stdout by mistake silently
  corrupts the parsed output (or an earlier `{`-line gets picked up as a
  decoy if you print the wrong one last).

## Worked example: create then archive a project

Workspace "Acme" already exists (seeded by `default`'s `acme` step); the
test supplies its own project rather than relying on a seeded one,
because creating and archiving a project are the test's own subject.

1. Claim a sandbox on `default` and note `acme`'s output:

   ```bash
   cofactor sandbox claim --application "Project Tracker" --wait
   ```

   The claim's seed outputs include `acme.workspace_id`.

2. Create the project the test will operate on, acting as the member:

   ```bash
   cofactor sandbox run <id> create-project \
     --input workspace_id=<acme.workspace_id> \
     --input name=Temp \
     --input as=member
   ```

   Returns `{"project_id": "<id>"}`.

3. Drive the app (via its `web`/`api` port URLs) to verify the project
   shows up wherever the product surfaces it, using the `project_id`
   from step 2 to find the right row.
4. Archive it the way the product's UI or API would — this is what the
   test is actually verifying, so it belongs in the test's own steps,
   not in a seed. Repeating it as `viewer` should be refused.
5. Destroy the sandbox:

   ```bash
   cofactor sandbox destroy <id>
   ```

Nothing about the project this test created is shared with any other
test, and nothing another seed does could break this test's setup.
