# Node Types

Every workflow is built from nodes. Each node has a type, a title, a description,
and type-specific configuration.

## Deactivating a node (any type except condition)

Set `deactivated: true` in the node's config to skip it during runs — the
step records status `skipped` and execution continues with the next node.
Useful for converging a flow node-by-node from the front, or parking a
chronically failing step without deleting it. Toggle via the CLI
(`workflow node deactivate|activate <workflowId> <nodeId>`) or the node's
three-dot menu in the Flow Designer. Two rules: a run is blocked while a
later step still references a `$var` that only a deactivated step produces,
and condition nodes cannot be deactivated (skipping the branch decision
would run both branches — deactivate the branch nodes instead).

## Starting node — pick the first node in this order

The first node of a flow follows a strict hierarchy. Getting this wrong is the
single most common authoring mistake (most often: opening with a navigate node).

1. SEED first — if the flow depends on pre-existing data, a `seed` node comes
   first. It provisions data in its own isolated context and exports
   `$var.{dataKey}` outputs the rest of the flow consumes.
2. Otherwise LOGIN first — for any authenticated flow, the first node is a
   `login` node that declares the ACTOR (who the journey runs as). This is the
   "acting as" step. Do NOT open an authenticated flow with a navigate node.
3. Navigate comes AFTER login — a navigate jumps to the test's entry point, but
   it follows the login; it is never the opening node of an authenticated flow.

The only flows that may start with a navigate are UNauthenticated ones — signup,
password reset, a public/marketing page, or a test of the login experience
itself. For those, set the login node's `performLogin: false` (or omit the login
node) and author the steps as the journey.

LOGIN SUBSUMES LOGGING IN. A login node already provisions an authenticated
session — it IS the act of logging in. Never emit a login node and then a
"navigate to /login" → "enter email/password" → "click Sign in" sequence. Start
with the login node and go straight to the first real action. The one exception
is a flow whose explicit purpose is to test login (start logged out and make the
login steps the journey).

## Login

Sets the user context. Select a credential to act as that user.
The login node provisions an authenticated browser session — subsequent
nodes start with the browser already logged in.

Config:

- `credentialId`: UUID of the credential to log in as. REQUIRED for the
  node to bind to a real credential. Without it the
  Flow Designer shows a red "Select a credential"
  warning even if `credentialName` is set.
- `credentialName`: Human-readable name, used as the node title. Optional
  but recommended alongside `credentialId`.
- `performLogin`: When true, the browser is authenticated automatically.

Finding the credentialId:

```bash
cofactor credential list [--env prod|dev]
```

This prints `ID: <uuid>` under each credential name.
Pick the ID whose property matches the environment the flow runs in.

Ordering: login nodes should typically follow any seed nodes, not
precede them. Seeds export variables (e.g. `$var.workflow_id`) that
later nodes consume, so a seed-first / login-second order avoids
wasted browser segments and lets login/navigate URLs reference
seed outputs. See the SEED node type and the Node Ordering section
of best-practices.

- Workflows support multiple login nodes for multi-role testing.
  Each login node starts a new segment with a fresh browser session.
  Example: Login as Customer → place order → Login as Sales Rep → verify order.
  Great for two-sided apps, permission checks (member vs admin), and
  cross-role journeys.
- Login nodes also appear after Wait nodes to re-establish the session.
- A navigate node after login is optional but useful for jumping
  directly to the test's entry point.

## Navigate

Directs the browser to a specific path.

Prefer relative paths (e.g. `"/flows"`, `"/flows/$var.workflow_id"`)
over hard-coded absolute URLs. Relative paths let the same workflow
run unchanged across environments (prod, dev, local, preview) — the
base URL comes from the property/environment the run targets. A
workflow that hard-codes `"https://app.dev.runcofactor.com/..."` will
silently drive traffic against dev even when run against prod.

Use an absolute URL only when the destination is genuinely off the
application being tested (external identity provider, third-party
checkout, docs site, etc.).

- A navigate node after login is a great way to jump straight to the
  page where the test begins.
- Select from discovered pages or enter a custom URL.

## Action

Performs a user interaction on the current page. Describe what the user
should do ("Create a new ticket") and optionally provide input data via
`formFields`.

Every action node must have a "title" beside `configJson`. The title shows
in the canvas, run timeline, failure reports, and issue tickets — an
untitled action is nearly impossible to reason about after the fact.
Keep titles short and intent-oriented: name the goal (and, where it helps,
the purpose), e.g. "Create a ticket", "Publish the flow", or "Click Start to
open the run-config modal". A title that names only the mechanics with no
intent ("Click the button") is the thing to avoid.

Keep actions focused on a single user goal — usually broader than one click,
but a lone action that genuinely stands alone in the flow is a fine node:

- Good: "Create a ticket with required fields"
- Good: "Click Start to open the run-config modal" (single action — but it
  stands on its own and names its purpose)
- Bad: "Click the button" (mechanics only, no intent)
- Bad: "Create a ticket, assign it, comment, upload, and verify" (too stuffed)

Aim for ~3–8 playbook steps per node; if a single outcome needs more, split it
into sequential action nodes. See the Action Nodes section for the full
altitude guidance (coherent step, assertion boundary, no hidden conditionals).

Rule of thumb: if an action crosses multiple screens or changes multiple
entities, split it. If it's a single user goal on a single screen, keep it.

Actions can include:

- `title` (beside `configJson`, required): short intent-oriented title, e.g.
  "Create a ticket". The detail of what to do goes in `actionDescription`:

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

- `formFields`: input data the action needs (name, email, etc.)
- `inlineAssertions`: checks verified after the action completes (preferred
  over standalone assertion nodes — see Assertions section)
- `declaredOutputs`: values to extract from the page for downstream use
- `customInstructions`: additional guidance for the agent executing the step

## Editing a node

`cofactor workflow node patch <workflowId> <nodeId> --config '{...}'` merges the
JSON into the node's `configJson` one level deep, so a nested object is replaced
whole: `{"params":{"statement":"..."}}` changes a `sandbox_action`'s SQL and
leaves its `actionSlug` and `outputKeys` alone, but drops any other `params` key,
so list every param to keep. Copy the key path from `workflow get`.
`--set-input key=value` writes `configJson.inputValues`, which only action, seed
and `call_flow` nodes read, and only for inputs they declare. On any other node
type the value is never used: use `--config`.

## Assertion

Verifies expected outcomes. Define a condition to check.
What happens on failure depends on the severity.

Prefer inline assertions on action nodes over standalone assertion nodes.
Inline assertions keep the test on track and produce cleaner failure
reports. If verifying something requires significant interaction first,
that's better modeled as an action node with inline assertions.

Use standalone assertion nodes only when the check doesn't belong to
any action — e.g., verifying a page state after navigation, or
confirming data absence after a sequence of steps.

Severity levels:

- `fatal`: The test must end now — the run halts at this step.
  Use for preconditions later steps depend on.
- `fail`: The test may continue — the run finishes marked failed,
  but later steps still run and produce signal.
- `warn`: The test should continue — logged as a warning, run passes.

Agentic assertions: for visual/layout checks that can't be mechanically
validated, enable agent evaluation. These require the AI agent during
replay and cannot be cached. Use for:

- Timestamps or dates
- Real-time data feeds
- Content that changes between runs

## Condition

Branches the workflow based on a runtime condition. Define a condition
to evaluate, then connect separate paths for true and false outcomes.
The condition is deterministic when it compares a `$var` or the acting-as
identity (evaluated without the agent); otherwise the agent evaluates it
against the live page.

Reach for a condition node only when the branch is genuine. Conditional
logic baked INTO an action node — "if it isn't set to New York, set it" /
"if patient X is missing, create X" — is usually a sign the data wasn't
staged, and it caches poorly. Prefer, in order: seed the precondition so
the branch disappears; run an idempotent sequence unconditionally when the
same steps reach the goal from any starting state; else a formal condition
node. If a conditional must live inside an action node, set
`alwaysUseAgent: true` on that node so the branch is reasoned about live and
never mis-cached. See the Action Nodes section.

CHECK (a condition with `failOnFalse`). The exact, no-AI way to assert a run
variable: a typed predicate with `"failOnFalse": true` does not branch; when
it is false the step fails and the run ends failed, and the step error says
what was expected and what the value was (long values are truncated). Use
it whenever the claim is about a value the run captured (an email body, an
API response, a sandbox action's output). See `guide assertions`, "Exact checks over run variables".

## Wait

Pauses execution for a specified duration (minutes, hours, or days).
Creates a segmented flow — execution pauses, then resumes automatically.
Add a Login node after the Wait to re-establish the browser session.

## Setup (deprecated)

Referenced another published workflow as a prerequisite. Do not author
new setup nodes. For shared data use a SEED node (below); for workflows
that must run in order use suite layers (`cofactor test-suite --layer`).

## Seed

Injects outputs from a seed workflow as variables. Seed workflows
generate test data and export named values. Downstream workflows
access these as `$var.{dataKey}`.

Ordering: seed nodes should almost always come FIRST — before the
login node. Seeds run in their own isolated context (usually via
API sequence) and export variables into the workflow. Placing a
login before the seed wastes a browser session, and any
login/navigate node that references `$var.{seed_output}` must come
after the seed that produces it.

Typical pattern:

```text
Seed → Login → Navigate → ... action/assertion nodes
```

Config:

- `seedWorkflowId`: UUID of the seed workflow (required)
- `seedWorkflowName`: Human-readable name (used as the node title)

Seed workflows provision data that several tests share; data unique to
one test is created inline. See the Seed Workflows section.

## API sequence

Executes multiple API calls in sequence without a browser.
Use for backend-only operations, webhooks, or API testing.

API sequences are also used inside seed workflows — start with a
browser-based seed to discover the right API calls, then convert
to an API sequence for speed and reliability.

## Sandbox action

Executes a sandbox action — a server-side script defined on the
environment template — directly on the run environment's sandbox
instance. No browser involved. The action's structured output is
registered as workflow variables: each output key becomes
`$var.{key}` for downstream steps.

Config:

- `actionSlug`: Slug of the action (required; discover via
  `list_sandbox_actions`)
- `params`: Input values keyed by the action's `inputSchema`
  property names; values may use `$var.{name}` / macros
- `outputKeys`: Output variable keys (defaults to the action's
  `outputSchema` keys)

Output registration is allowlisted by declared intent: the action's
`outputSchema` keys, else the node's `outputKeys`. If neither declares
anything, NO result keys register — declare outputs explicitly for
schema-less actions.

A list or object output (for example the email emulator's `emails`) registers
as a JSON string. Up to 64 KB (a larger output fails the step), within one run segment. A condition with a
`contains` predicate can assert on its text, e.g. a captured reply's body or
its in-reply-to header.

Environment constraint: the action runs on the environment's
backing sandbox instance. On a non-sandbox environment (static
staging/prod) the node SKIPS with a warning and registers no
variables — so workflows containing one are effectively
sandbox-only.

Seeds: a seed workflow whose body is a single sandbox action node
is the fastest way to provision data — it runs entirely
server-side (no browser session), and its outputs satisfy the
seed's declared outputs like any captured value.

## MCP

Drives an MCP-server application — an application (property) with type
"mcp" — by letting an agent accomplish a plain-language goal through the
server's tools. No browser involved. Use it to test an MCP server the org
has registered as an application: exercising its tool surface, creating or
mutating data through MCP tools, and capturing returned values as
workflow variables.

When to use: the step's target is the MCP server itself. To verify the
EFFECT of the MCP work in the product UI, keep the MCP interaction in the
`mcp` node and put the browser verification in SUBSEQUENT action/assertion
nodes — an `mcp` node never drives the browser.

Authoring fields (`create_node` / `update_node`):

- `mcpApplicationName`: Name of the MCP application (required; discover via
  `list_mcp_applications`). Resolved to the stored
  application id at authoring time.
- `mcpInstructions`: Plain-language goal (falls back to description).
  State ONE verifiable outcome and name the values to
  capture — "Create a project named Acme via the
  create_project tool and capture its id as
  project_id", not "try out the project tools".
- `mcpPersona`: Persona (credential template name) supplying
  authentication, resolved against the application.
  Preferred over pinning a raw credential.
- `mcpOutputs`: Variable names the node must produce; each becomes
  `$var.{name}` for downstream steps.
- `mcpTools`: Optional allowlist restricting which server tools
  the agent may call; omit to allow all.

Like action nodes, `mcp` nodes replay from cache first with agent fallback
(set `alwaysUseAgent` in config to skip replay). Requires the `mcp.testing`
feature flag for the organization.

## Call flow

Runs another flow from inside this one, passing arguments in and getting
that flow's declared outputs back as variables. The child executes as its
own nested run with its own environment, credentials and browser session,
so a browserless parent can call a browser child and still watch it.

When to use: a check you want to reuse. Unlike seed nodes —
which are hoisted out of the chain and run before everything else — a
`call_flow` node runs exactly where you put it, which is what makes it
usable after an action node.

The flow picker in the designer lists saved flows the caller may read,
excluding the current flow, archived flows and shadow flows. Regression
membership does not limit which saved definitions a `call_flow` node may
reference.

Arguments map to the child's declared value inputs by name, and an
argument the child no longer declares fails the step rather than being
silently dropped. Only outputs the child DECLARES cross the boundary.

Config:

- `flowId`: Flow to run (required). A flow cannot call itself.
- `flowName`: Cached child name, used as the node title.
- `snapshotVersion`: Pinned published version, or null for the live definition.
- `inputValues`: Map of the child's declared input names to values.
  `$var.{name}` is interpolated here; macros pass through
  unresolved so the child's own macro context expands
  them and per-run uniqueness is preserved.
- `environmentId`: Explicit environment override, or null to let the
  parent's environment apply when the child is eligible
  for it, else the child's own resolution.
- `executionMode`: `recommended` | `api` | `browser`
- `onFailure`: `block` (default) — a failed child fails this step;
  `warn` — a child that ran to completion and failed only
  warns. A child this step could not START — bad flowId,
  depth cap hit, an argument the child does not declare —
  fails either way: misconfiguration is never softened.

Declared outputs arrive as both a bare `$var.{key}` and a namespaced
`$var.{Child_Flow_Name}.{key}`, where the child's name is slugified —
"Verify checkout totals" becomes `$var.Verify_checkout_totals.{key}`. Use
the namespaced form when two called flows export the same key.

Nesting is capped at 5 levels. Each level is a full run with its own
browser session, so cost compounds.

## Notification

Sends notifications (Slack, email, etc.) at a point in the workflow.

## Visual checkpoint

Captures a meaningful screen state (whole page, or an element named by a
plain-English target) and compares it with the rolling baseline. Fields:
name, optional target, optional expected state, severity (record or fail).
See `cofactor workflow guide visual-checkpoints`.

## End

Explicitly terminates the workflow. Use when a condition branch
should stop execution rather than continue.
