# Write a Test from the CLI

Use this section to author a test straight from the CLI: plan the journey, check
for duplicates, create or update the workflow, run it, and hand back its URL.

## Authoring loop

1. Understand the requirement. Read the ticket, PRD, or the user's intent, and
   explore the real UI first (see `best-practices` and `cofactor session guide`).
2. Avoid duplicates:

   ```bash
   cofactor workflow list --search "<keywords>"
   ```

   If a workflow already covers the journey, update it instead of creating one.
3. Create it (JSON on stdin or from a file; shapes are in `node-types`):

   ```bash
   cofactor workflow create --from-file test.json
   cofactor workflow create --from-file test.json --tags "p0,checkout"
   ```

   Input: `{ "name": "...", "nodes": [{ "nodeType": "...", "configJson": {...} }] }`

   A node has `nodeType`, `configJson` and, for action nodes, a required `"title"`
   (plus `id`/`orderIndex` when reusing). The title is short and says what the user
   does; the detail goes in `configJson.actionDescription`:

   ```json
   { "nodeType": "action", "title": "Create a ticket",
     "configJson": { "actionDescription": "Fill in the required fields and save" } }
   ```

   The title is what the run timeline, canvas and failure reports show. An
   action node without one is rejected: add `"title": "<short goal>"` to it.

   To act as a persona, make the first node a login node:

   ```json
   {"nodeType": "login", "configJson": {"credentialSource": "from_template",
    "credentialTemplateName": "<persona>", "performLogin": true}}
   ```

   Use `credentialTemplateId` instead of the name when the persona name exists on
   more than one application. Without `credentialSource` `"from_template"` a login
   node expects a stored `credentialId`.
4. Change an existing workflow:

   ```bash
   cofactor workflow get <workflowId>                       # read it first
   cofactor workflow sync <workflowId> --from-file test.json   # replace all nodes
   cofactor workflow node patch <workflowId> <nodeId> --config '{"params":{"statement":"..."}}'
   cofactor workflow patch <workflowId> --name "..." --description "..."
   cofactor workflow patch <workflowId> --preflight @preflight.md --cleanup @cleanup.md
   ```

   Reuse each existing node `id` in sync to keep a minimal diff. Every new or
   edited action step needs a `"title"`; an untitled legacy step you leave exactly
   as it is stays accepted. `workflow get --json` lists `"title": null` for such steps.
   Add `--propose` to sync to open a proposal for review instead of applying directly.

   `node patch --config` merges `configJson` one level deep: name the node's own
   keys (a `sandbox_action`'s SQL is `{"params":{"statement":"..."}}`; an action's
   text is `{"actionDescription":"..."}`). A nested object is replaced whole, so
   `"params"` must list every param to keep. Run `workflow get` first and copy the
   key path from the node's `configJson`. `--set-input key=value` writes
   `configJson.inputValues`, which only action, seed and `call_flow` nodes read, and
   only for inputs the node (or the called flow) declares. On every other node
   type the value is never used: use `--config`.

   The CLI rejects `--set-input` on node types that ignore `inputValues`, and on an
   action input the node has no data requirement for.
   For multi-line SQL or prompts, put the JSON in a file: `--config @patch.json`

5. Run it and look at the result:

   ```bash
   cofactor workflow run <workflowId> --stream
   cofactor workflow runs list <workflowId>
   cofactor workflow debug <runId>        # when a run fails
   ```

   To run on a sandbox you claimed: `cofactor workflow run <workflowId>
   --sandbox <sandboxId>`. The run targets the sandbox's own environment, so
   no `--environment` is needed. `cofactor sandbox claims` lists your live
   claims (ids, expiry) if you lost an id; `cofactor sandbox destroy <id>`.
6. Return the workflow URL printed by the CLI to the user verbatim. Never
   build the URL yourself.

To include a saved test in Regression, use:

```bash
cofactor workflow add-to-regression <workflowId>
```

To remove only that membership, use:

```bash
cofactor workflow remove-from-regression <workflowId>
```

These commands require CLI 0.59.0+. Upgrade with:

```bash
bun add -g @runcofactor/cli@latest
```

Older clients can use `POST` or `DELETE` `/workflows/<id>/regression`.

## The rubric: every test must satisfy all of these

### 1. One coherent journey per workflow

One user objective, possibly with several verifications along the way.
"Atomic" means coherent, not minimal. If isolating a check would force you
to duplicate most of another test's setup, fold it in as an inline
assertion on the larger journey.

- Good: create org -> invite a user -> claim invite -> land on dashboard.
- Good: submit a ticket and confirm it appears in the queue.
- Bad: submit a ticket, edit a user, generate a report (three journeys,
  three workflows).

Split only when the setup is genuinely different or the failure modes are
independent. A long single journey stays together; independent journeys
become separate workflows so they run in parallel and fail independently.

### 2. Specific, observable expected results

Every assertion is something a stranger could verify without judgement,
and comes from the requirement or confirmed user intent, not incidental
DOM details seen while exploring. Keep conditions about user-visible
behavior; do not invent ARIA/SVG checks or pixel thresholds.

- Good: "URL ends with /dashboard." "A row named X appears in the table."
- Bad: "The page looks correct." "It works."

Attach assertions inline to the action that produced the result (see
`assertions`). Pick severity deliberately: `fatal` ends the run (gating
preconditions), `fail` marks the run failed but continues (feature claims),
`warn` records without failing (cosmetics). A test with no run-failing
assertion proves nothing.
Relative checks ("the count dropped by 2") must reference a value captured
upstream and used via `$var.<name>`, never rely on memory of the earlier state.

### 3. Idempotent, self-owned, isolated

- Rerunning passes without a manual reset: use macros (`$EMAIL()`, `$UUID()`,
  `"QA Test $RANDOM_STRING(6)"`) for anything that must be unique (see `macros`).
- The test creates the records it operates on, inline. A seed workflow is
  for data that several tests share; a seed with one consumer is overhead.
  Data the test only reads may pre-exist, but never mutate it.
- Never modify shared resources (billing, integrations, API keys, org
  config) as a side effect.
- Tests that depend on one another run as ordered suite layers, never by
  implicit ordering.
- A fatal assertion halts the run before trailing cleanup. Anything that
  must be gone after a failure belongs in a seed with a teardown (see
  `seed-workflows`, `data-lifecycle`).

### 4. Traceable

Link the test to the product-map capability it proves:

```bash
cofactor product-map link <CAP-code> <workflowId>
```

Traceability comes from that link, not from text: do not write capability
codes, ticket ids or requirement references into the name or description.
If no capability covers the test, tell the user; untraceable tests rot.

### 5. Risk-prioritized

Tag each test `p0`, `p1`, or `p2` with `--tags` / `--tags-add`:

- `p0`: happy path of the core promise; if it breaks the feature is broken
- `p1`: primary edge cases, validation, role variants, common error states
- `p2`: rare conditions, visual or agentic checks, low-frequency edges

### 6. Preconditions, data, and cleanup are explicit

Auth and role: use a persona (`cofactor persona list --application "<app>"`)
rather than raw usernames and passwords. Shared setup: a seed node, placed
before login. Test data: workflow inputs with macros. Anything else the
test depends on (pre-existing data it reads, flags, third-party systems)
goes in the workflow's preflight, and how its side effects get reset goes
in its cleanup. Write each as a short markdown bullet list:

```bash
cofactor workflow patch <workflowId> --preflight @preflight.md
cofactor workflow patch <workflowId> --cleanup @cleanup.md
```

### 7. The description says what the test is for

Read together with the name, the description gives the spirit of the
test: what we are doing and why it matters, in one or two plain
sentences. It never holds capability codes, preconditions, issue ids,
status ("expected red", "blocked"), step narration, endpoints, payloads,
timings or cache details. Each of those lives elsewhere: the product-map
link, the preflight, the linked issue, the run history, the nodes.
People read the description, preflight and cleanup in the web UI, so
never put a raw ID in them: no UUID, UUID prefix, `wf_`/`prule_` or other
prefixed id, issue id or run id. Name the thing instead (the seed
workflow's name, the teardown's name, the connection's name, the
record's name).

Good: name "Invite a teammate to Acme", description:

```text
An admin invites a new teammate by email and the
teammate can sign in. Growing a team depends on invites
reaching people.
```

Bad description:

```text
CAP-ORG-004. Needs seed org + admin persona. Steps:
open /settings/team, POST /api/invites, wait 5s, check inbox.
Expected red until ISSUE-812 ships. Cache warm.
```

Bad preflight:

```text
Seed 5e055090 creates an empty layer. Paired teardown d9a44386
deletes the flow.
```

Good preflight:

```text
- The "Acme empty layer" seed creates an empty layer
- Its paired teardown, "Acme empty layer teardown", deletes the flow
```

### 8. Written as human intent, not UI mechanics

Action titles say what the user is trying to do ("Assign the ticket to
Support"), not click-by-click steps. Each action is one coherent,
assertable step: usually broader than one click, ends at a visible
boundary (modal gone, URL changed, row appeared), and has no conditionals
inside it. If the data might not exist, seed it instead of branching.

## Choosing values

- Names existing data in the target app (a property, persona, credential, a
  seeded record): do not guess. Look it up with `cofactor property list`,
  `cofactor persona list --application "<app>"`, or
  `cofactor workflow list --search <term>`, and ask the user when several
  candidates fit.
- Synthesizable (email, UUID, throwaway string, date): use a macro and move on.
- Auth or role: prefer a persona over a raw credential.

## Coverage checklist

Before handing work back, for each item either include a test or say why it
does not apply: happy path (p0); primary edges and boundary inputs; negative
paths and validation errors; permission and role variants; empty, loading,
and error states; cross-entity side effects (does this change something
visible elsewhere?); cleanup or undo.

Aim for the smallest set that proves the feature works. Five sharp tests beat
twenty fuzzy ones.

## Visual regression coverage

Put the appearances you want reviewed together in one ordinary Workflow, not
one Workflow per state. Screens groups the native captures by Workflow and
step order; each Visual checkpoint keeps its own identity and a descriptive
name. Keep checkpoint IDs stable after the first create: edit the
`cofactor workflow get <workflowId> --json` output and sync it back. Follow the "Standalone visual regression tests" part of
the visual-checkpoints section
(`cofactor workflow guide visual-checkpoints`) for the multi-state example.

On CLI 0.59.0 or later, `sandbox.reset` restores the exact snapshot pinned to
a Run, keeps the mapped persona signed in with fresh session state, and
requires an explicit Navigate afterward. Reset does not replay earlier setup
or seed steps, so set up the next data state again and refresh any IDs or
action outputs derived from the old copy. Browser request faults belong to
the Workflow's live browser and clear after the next explicit checkpoint; use
`loading:` only with a named held request and a target that contains the
visible loader.
