# Visual Checkpoints

Visual checkpoints capture a meaningful screen state and compare it with the
rolling baseline for that checkpoint. Add one checkpoint at each state whose
appearance matters to the user; avoid taking several screenshots of the same
state just because the journey has several steps.

## Plan the screen's states

A good UI regression check visits a screen and captures each meaningful
state: empty, a little data, a lot of data, different kinds of data,
long or overflowing content, error or failure, loading when it can be held
stable, and permission-limited access. Pick the states that apply to that
screen; a single populated screenshot is rarely enough.

For example, check Cofactor's Workflows page with no workflows, three
workflows, and enough workflows with long names to exercise scrolling
and truncation. Check the Issues page with different
severities and statuses, and Settings as a member with limited permissions.
Capture a failed request with its error message when setup can reproduce it.

For every state, specify setup, the visible result, and a checkpoint named
for the page and state: "Workflows — empty", "Workflows — three rows",
"Workflows — many mixed rows". Use a separate checkpoint node per state
(or a separate scenario); keep its identity stable between runs. For
Playwright attachments, include the state in the attachment name.

Reset or replace only test-owned data between independent states, then set
up the next state, navigate to the page, and wait for its visible result
before capturing.
Use the sandbox's thin seeds as the starting point, generic actions for
setup, and a separate SQL fixture per state where appropriate. A fixture
can clear and replace only the test's own rows in its sandbox. If setup
cannot undo a change, use a separate test with a fresh sandbox copy.

Keep values, row counts, ordering, viewport, persona, flags and relative
dates repeatable. Do not use random content, arbitrary sleeps, or live
external failures. Use UI steps for open menus and validation errors. To
capture a repeatable request error, place the Workflow-only
`browser.request-fault` Sandbox action before navigation and choose
`respond` with an HTTP status from 200 to 599 and a JSON body. It matches one
exact uppercase method and pathname on the Run copy's declared public
Application ports, then clears after the next explicit Visual checkpoint
completes. Automatic action screenshots do not clear it.

The fault is an ordinary `sandbox_action` node with `actionSlug`
`browser.request-fault`. Its `params` are all strings: `name`, `method`,
`path` (an absolute pathname with no query or fragment) and `mode`
(`respond` or `hold`). `respond` also needs `status` (an HTTP status from 200
to 599) and `body` (valid JSON text); `hold` takes neither:

```json
{"nodeType": "sandbox_action", "configJson": {"actionSlug": "browser.request-fault",
 "params": {"name": "items", "method": "GET", "path": "/api/items",
  "mode": "respond", "status": "503", "body": "{\"error\":\"Unavailable\"}"}}}
```

It needs the Workflow's own live browser and an active Sandbox v2 copy. A
second active fault is rejected. The body is masked in the action config and
never written to runtime logs. Besides the next explicit checkpoint, a reset,
a browser or persona change, recovery, cancellation, disconnect and the end of
the Run also clear it. It is not a `cofactor sandbox run` operation, and there
is no separate clear node.

Ordinary native checkpoints wait for loading to finish and mark ongoing
loading as unstable; a held request alone does not make a loading screenshot
stable. Use a settled loading preview if the app provides one.

## Capture a held loading state

To capture a deliberate loading state, set
`"loadingRequest": "<request-name>"` in a Visual checkpoint's `configJson`.
It requires an active, matched and pending `hold` request with that name on
a declared application origin, and a resolvable `target`.
The request itself need not appear in the target; the target must visibly
contain the loader in its captured region. A missing target, unmatched hold,
or missing loader fails the checkpoint, including with `"severity": "record"`.

Settling exempts only the named held request and busy indicators inside the
target region. Other network activity and busy indicators outside the target
remain normal settle blockers under the usual budget. DOM quiet, fonts,
images, and finite animation checks still apply, and the two sampled
screenshots must match. The runtime verifies the held request after sampling
pixels and clears it when the checkpoint finishes, including failure.

A pull request that changes how a screen looks needs one of these as evidence:
see `cofactor proofs guide`.

## Link checkpoints to what they show

Link a screen that proves one rule with:

```bash
cofactor product-map rule link <prule_…> --workflow <wf_…> --node <checkpointNodeId>
```

Link a screen that shows a capability in general with:

```bash
cofactor product-map link <CAP_CODE> <wf_…> --node <checkpointNodeId>
```

Remove that direct capability link with `unlink` and the same arguments.
`--node` requires exactly one flow. Link directly whenever the flow covers
more than one capability; otherwise Screens uses the flow's capability.

Default-branch runs supply screen baselines automatically. PR and proof
captures never change the main baseline, including when the PR merges.
A later main run after merge establishes the baseline. Proof screen links
retain the exact before/after/diff evidence for read-only inspection,
including for draft forks; there is no screen approval or pending acceptance.

A checkpoint proves how a screen looks, not its values: dates and numbers
are ignored, so prove values with an assertion. Qualifying default-branch
captures establish the image and masks used for rule proof automatically.

## Native workflow checkpoints

First ask: where must this test run?

- Sandbox only: a SQL fixture is fine. This is the usual case for a visual
  regression test comparing an exact state at a commit.
- Also 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. Keep checkpoints on regions that do not depend on exact data,
  or rely on masking (automatic/healed for native checkpoints; see below).

A test that loads SQL is sandbox-only.

Seed the chosen state first, then capture it.
Choose among three kinds of test data:

- Seeds: shared, thin, generic base data nearly every test needs.
- Actions: typed, parameterized, generic operations; prefer the app's API.
- Visual-state fixtures: one SQL file per screen state, kept beside its test.
  Use fixed, neutral values and timestamps relative to `now()` (for example,
  `now() - interval '2 days'`) so relative-time text stays stable. Fixtures are
  never parameterized or shared; do not build a library of per-test seeds.

SQL fixtures are the default for sandbox-only visual data, only inserting
rows with no encryption and no side effects. For encrypted rows or side
effects, use the app's API or a generic action that calls it. Use UI steps for
interaction states such as an open menu or validation feedback. Repeat setup
and capture for each meaningful state of the screen.

The `target` is optional plain English describing an element, such as
`the invoices table`; omit it to capture the whole page. Never put a CSS,
XPath, or Playwright selector in `target`.

`expectedState` is optional plain language describing the correct visible state.
It guides the AI in deciding whether the current state is correct and whether
a visual change is real or can be healed. Use a specific observable
description, for example, "Three invoices are listed, each marked Paid, with
no error banner."

`"severity": "record"` is the default. It records visual findings without changing the
workflow result, and compares after the suite finishes. Choose `fail` when an
unresolved visual change should fail this workflow step; it compares inline.
Under either severity, a `target` that cannot be found is reported as a
checkpoint that could not be compared, and under `fail` it fails the step.
Both severities appear in Visual results.

Dynamic text is masked automatically. If the AI heals a difference, it saves
an element mask and its reason on the checkpoint. The review shows the heal;
a reviewer can revert the mask or flag the change as a regression. Masks are
automatic or healed; never author mask rules yourself.

## Before your first visual test

For a sandbox-only SQL test, check `cofactor.sandbox.yaml` for a generic
SQL-loading action. If absent, add one to the app's definition. For Postgres,
this action loads a repo-relative `.sql` path from the claimed commit. Claim
the commit containing both the test and its fixture. Install git and psql
in the sandbox; `DATABASE_URL` must already name its sandbox database in env
(or repository secrets). Use your app's database URL variable if different.

```yaml
actions:
  load-sql:
    description: Load a test's SQL fixture into the sandbox database.
    run: sandbox/actions/load-sql.sh
    input:
      path: { type: string, required: true, description: Repo-relative .sql file }
    output:
      ok: { type: boolean }
```

```bash
# sandbox/actions/load-sql.sh
#!/usr/bin/env bash
set -euo pipefail
git show "HEAD:$INPUT_PATH" | \
  psql "$DATABASE_URL" -X --set=ON_ERROR_STOP=1 --single-transaction >&2
printf '{"ok":true}\n'
```

The generic loader is shared; each screen's fixture belongs only to its test.
SQL errors fail the action; success is the last JSON line on stdout.

## Standalone visual regression tests

This example checks several states of Cofactor's Workflows page. Keep the
three SQL files beside the test at the claimed commit. Each clears only this
test's workflow rows and inserts its own state; shared persona and membership
data stays in place. Use neutral names such as "Review settings" and "Create a
project", fixed ordering and relative dates. The last fixture includes rows with long names
and enough rows to scroll. Use API-backed
actions for any setup with side effects.

Save it as `workflows-visual.json` and create it with
`cofactor workflow create --from-file workflows-visual.json`. For later
changes, save `cofactor workflow get <workflowId> --json` to a file, edit it,
and apply it with `cofactor workflow sync <workflowId> --from-file <file>`.
That file carries each node's ID, so every checkpoint keeps its identity and
baseline.

```json
{
  "name": "Workflows list visual regression",
  "description": "An admin can scan workflows when the list is empty, small or crowded.",
  "nodes": [
    {"nodeType": "login", "configJson": {"credentialSource": "from_template",
      "credentialTemplateName": "admin", "performLogin": true}},
    {"nodeType": "sandbox_action", "configJson": {"actionSlug": "load-sql",
      "params": {"path": "tests/visual/workflows-empty.sql"}}},
    {"nodeType": "navigate", "configJson": {"pageUrl": "/flows"}},
    {"nodeType": "visual_checkpoint", "configJson": {"title": "Visual checkpoint: Workflows — empty",
      "description": "Visual checkpoint: Workflows — empty", "name": "Workflows — empty",
      "expectedState": "The empty list offers a clear way to create a workflow.",
      "severity": "fail"}},
    {"nodeType": "sandbox_action", "configJson": {"actionSlug": "load-sql",
      "params": {"path": "tests/visual/workflows-three-rows.sql"}}},
    {"nodeType": "navigate", "configJson": {"pageUrl": "/flows"}},
    {"nodeType": "visual_checkpoint", "configJson": {"title": "Visual checkpoint: Workflows — three rows",
      "description": "Visual checkpoint: Workflows — three rows", "name": "Workflows — three rows",
      "expectedState": "Three workflows are visible with their names and statuses.",
      "severity": "fail"}},
    {"nodeType": "sandbox_action", "configJson": {"actionSlug": "load-sql",
      "params": {"path": "tests/visual/workflows-many-mixed-rows.sql"}}},
    {"nodeType": "navigate", "configJson": {"pageUrl": "/flows"}},
    {"nodeType": "visual_checkpoint", "configJson": {"title": "Visual checkpoint: Workflows — many mixed rows",
      "description": "Visual checkpoint: Workflows — many mixed rows", "name": "Workflows — many mixed rows",
      "expectedState": "Many workflows with long names fit without overlapping controls.",
      "severity": "fail"}},
    {"nodeType": "end", "configJson": {"outcome": "pass"}}
  ]
}
```

A viewport capture shows only the visible rows. Add a scroll and another
checkpoint for content below the fold when that layout matters.

Submit invalid form data and checkpoint the validation state:

```json
{
  "name": "Signup validation visual regression",
  "description": "A visitor sees clear validation feedback when required signup fields are missing.",
  "nodes": [
    {"nodeType": "navigate", "configJson": {"pageUrl": "https://app.example.com/signup"}},
    {"nodeType": "action", "title": "Submit the empty signup form",
      "configJson": {"actionDescription": "Submit without entering any values so the required-field messages appear.",
        "inlineAssertions": [{"condition": "A required-field validation message is visible.",
          "severity": "fail"}]}},
    {"nodeType": "visual_checkpoint", "configJson": {"title": "Visual checkpoint: Required-field validation",
      "description": "Visual checkpoint: Required-field validation", "name": "Required-field validation",
      "target": "the signup form",
      "expectedState": "Required fields have clear validation messages and the form has not been submitted.",
      "severity": "record"}},
    {"nodeType": "end", "configJson": {"outcome": "pass"}}
  ]
}
```

## Playwright attachment checkpoints

In an external Playwright suite running on Sandboxes v2, an attached PNG is a
visual checkpoint:

```ts
await testInfo.attach(name, { body: await page.screenshot({ mask }), contentType: 'image/png' })
```

Its identity is the Playwright spec file, test title, and attachment name. Keep masking
in the test code with Playwright's `mask` option. The service explains and
reports Playwright changes but never fails the Playwright test. Failure
screenshots, trace frames, and `toHaveScreenshot` actuals are excluded. Do
not use `toHaveScreenshot` for this feature; attach the screenshot instead.

## Review results

Review main-run changes and AI assessments on the Screens timeline. Proof
comparisons retain their before/after/diff evidence without acceptance.
From the CLI, use `cofactor visual list` to find captures and
`cofactor visual get <captureId> --json` to inspect comparison IDs.
File an Issue with the before/after/diff evidence using:

```bash
cofactor visual flag-regression <changeId> --note "Unexpected layout shift"
```

Flags never stop later main captures from becoming baselines.
