# Assertions

Assertions verify that the application behaves as expected. There are two
ways to add assertions: inline on action nodes, or as standalone assertion
nodes. Inline assertions are strongly preferred.

## Inline assertions (preferred)

Attach assertions directly to action nodes using the `inlineAssertions`
field. These are verified immediately after the action completes and
cached for fast replay.

Inline assertions are the best way to verify outcomes because they:

- Keep the test on track — verification happens right where the action is
- Produce clean failure reports — each assertion is tied to the step that caused it
- Are cacheable — fast replay on subsequent runs

Each non-agentic inline assertion is proved by exactly one `verify` step in
the playbook, bound to it by the assertion's id (see playbook.txt). That
binding is what lets the check compile and replay at the point in the flow
where it was actually verified, instead of trailing at the end of the node.

Example — after submitting a form:

```text
Action: "Submit the support ticket"
Inline assertions:
  - "Success toast appears" (severity: warn)
  - "Ticket appears in the ticket list" (severity: fail)
  - "Form is no longer visible" (severity: fatal)
```

Severity levels — what a failure means for the run:

- `fatal`: The test must end now. The run halts at this step.
  Use when continuing is pointless: login succeeded, the page
  loaded, a precondition every later step depends on.
  Example: "User is logged in and the dashboard is visible"
- `fail`: The test may continue. The step is marked failed and the run
  finishes marked failed, but later steps still execute and
  produce signal.
  Use for independent checks: data saved, expected row present,
  error absent.
  Example: "The new record appears in the table"
- `warn`: The test should continue. The failure is recorded as a warning
  and the run still passes.
  Use for cosmetic or non-critical checks: toast appeared,
  animation completed.
  Example: "Success toast appears"

Choosing a severity: ask "if this is wrong, is there any value in
running the rest of the test?" No → fatal. "Does this being wrong mean
the feature is broken?" Yes → fail. Otherwise → warn. When unsure,
prefer fatal for preconditions and fail for feature claims. Always set
a severity explicitly — don't leave it unspecified.

If verifying something requires significant interaction (scrolling,
navigating, expanding sections), model that as an action node with
inline assertions — not a detailed standalone assertion node.

## Standalone assertion nodes (use sparingly)

Use dedicated assertion nodes only when the check doesn't belong to
any action:

- Verifying a final page state after navigation (no action to attach to)
- Checking that data was NOT modified (absence checks after a sequence)
- Confirming a state visible only after a wait or page transition

A typical workflow has 0-1 standalone assertion nodes. If you find
yourself writing a complex assertion node that requires multiple steps
to verify, consider whether it should be an action node with inline
assertions instead.

## Agentic assertions

For visual or layout checks that can't be mechanically validated,
enable agent evaluation. These require the AI agent during replay
and cannot be cached.

Use for:

- Screenshots that should "look correct"
- Charts or graphs rendering properly

Changing content, timestamps, and measurable layout can still be checked
deterministically against current-run inputs and captured baselines.
Cached assertions replay verification code, never an earlier verdict.

Standard assertions are preferred — only use agentic when the
check needs subjective judgment.

## Exact checks over run variables

When the claim is about a value the run already holds in a `$var` (a received
email, an API response, a captured id, a sandbox action's output), assert it
with a check: a condition node with a typed predicate and
`"failOnFalse": true`. It is evaluated exactly, without the agent and without
a browser. True passes the step. False fails the step and the run, and the
step error reads, for example:

```text
Check failed: Expected $var.emails at "0.body" to contain "Thanks", got "..."
```

Never assert a run variable with an inline or agentic assertion (the judge
can pass it without reading the value) or with a sandbox action that raises
an error (that tests the database query, not the product).

One check per claim. A node config:

```json
{
  "conditionDescription": "The reply quotes the original message id",
  "predicate": {
    "subject": { "kind": "variable", "name": "emails", "path": "0.headers.in-reply-to" },
    "operator": "equals",
    "value": "$var.message_id"
  },
  "failOnFalse": true
}
```

- `subject.name`: the variable, without `$var.`.
- `subject.path` (optional): a field inside a JSON-string variable,
  dot-separated, numeric segments index arrays (`"0.body"`, `"items.2.id"`).
  Objects and arrays compare as their JSON text. A value that is not JSON,
  or a field that is not present, fails the run as unevaluable.
- `operator`: `equals`, `not_equals`, `contains`, `not_contains`, `matches` (a
  JavaScript regular expression), `is_set`, `is_not_set`, `gt`, `lt`, `gte`, `lte`.
- `value`: the expected value. `$var.<name>` references in it are substituted
  from the run first; one that is not set fails the run. In a `matches`
  pattern a substituted value matches literally.
- `conditionDescription`: the claim in product voice; it is the step's title.

A JSON null counts as not present. Secret variables (credentials, sensitive
values) are compared but never printed: the message says only whether the
comparison held.

Author it with `cofactor workflow create` / `workflow sync` like any node
(`"nodeType": "condition"`), or change one with
`cofactor workflow node patch <workflowId> <nodeId> --config '{...}'`
(pass the whole predicate; patch replaces nested objects whole).

## Writing good conditions

Assertions describe codified, user-visible behavior, not the mechanics
used to observe it. Derive the expected result from the specification,
product-map requirement, or confirmed user intent. Browser exploration
discovers how to exercise and measure the behavior; it does not invent
new acceptance requirements.

- Good: "The named column stays fixed while level columns scroll."
- Good: "After unpinning, the named column scrolls with the grid."
- Bad: "aria-pressed=false and the SVG has an outlined path."
- Bad: "Horizontal scroll increases at least 80 pixels." (unless required)

A scroll distance or viewport size chosen for the test belongs in setup
or the action. Measurements and comparison tolerances belong in replay
code. Confirm the intended user during browser preflight; do not add a
signed-in-user assertion unless identity/authentication is the journey.

Assertions must be specific and observable:

Good:

- "The status badge shows 'Active'"
- "The table contains a row with name 'Test Record'"
- "Error message is not visible"
- "The page title is 'Dashboard'"

Bad:

- "The page looks correct"
- "The action was successful"
- "Everything works"

Start with what's observable: "The page displays...", "The table
contains...", "The field shows...". Include the specific value
you expect when the requirement specifies it. Do not assert exact
incidental copy, attributes, or dimensions simply because they were observed.

## Assertion boundaries & self-contained checks

Each action node should end at a checkpoint you can assert on — a modal
disappeared, the URL changed, a row appeared, a toast fired. These boundaries
double as the run's progress markers, so prefer a concrete end-state check
to a vague one.

Make every assertion SELF-CONTAINED. An action may replay from cache while
its assertion is judged live by the agent, which does not have the action's
execution context — so an assertion that silently assumes "before" state is
unreliable. Relative or temporal checks are fine, but only when the baseline
was captured upstream and referenced by variable:

- Good: "current row count = `$var.captured_row_count` - 2"
- Bad: "the row count dropped by 2" (no captured baseline — the live
  evaluator can't know the old count)

Capture the baseline with `declaredOutputs` / a capture on the upstream node,
then reference it as `$var.<name>` in the assertion.

## Assertion placement

Place assertions at critical verification points:

1. After data creation: verify the record exists (inline on the create action)
2. After data modification: verify the change persisted (inline on the edit action)
3. After deletion: verify the item is gone (inline on the delete action)
4. At the goal completion point: verify the journey succeeded

Don't assert everything — focus on the claims that matter.
A focused assertion that proves the test's core claim is better
than a dozen checks on every UI element.
