# Authoring with the MCP tools

## Building Tests — Workflow Authoring

After exploring an app via browser session, you can persist what you discovered as a reusable test workflow. The flow is: **explore → author → create**.

### Step 1: Gather Credential Info

Call `cofactor_credential_list` to get the credential UUID. You'll need it for the login node.
- Always use `credentialId` (UUID) — never just the credential name
- Set both `credentialId` and `credentialName` in the login node

### Step 2: Design the Workflow

A workflow is a directed graph of **nodes** connected by **edges**.

#### Node Types

| Type | Purpose | Required configJson |
|------|---------|-------------------|
| `login` | Authenticate with a credential | `credentialId`, `credentialName` |
| `navigate` | Go to a URL | `pageUrl`, `pageTitle` |
| `action` | Interact with elements | node-level `title`, `playbookSteps`, optionally `inlineAssertions` |
| `assertion` | Standalone page verification | `condition` text |
| `end` | Terminal node | (none) |

#### Action Node Guidelines

- Every action node **must** have a node-level `title` (beside `configJson`) — a short (3-8 word) human-readable title describing the step (e.g., "Create a new invoice", "Fill registration form"). Put the detail in `configJson.actionDescription`
- **Group related actions** into a single action node (one node per logical step, not per click)
- **Prefer inline assertions** on action nodes over separate assertion nodes. Add `inlineAssertions` to verify outcomes right after the action. **Do not author an `id` field** — the server stamps a UUID on persist:
  ```json
  {
    "inlineAssertions": [
      {
        "condition": "Success message 'Invoice created' is visible",
        "severity": "fail"
      }
    ]
  }
  ```
- Use separate `assertion` nodes only for standalone page-level verifications (e.g., initial page state before any action)

#### Playbook Steps (inside action nodes)

Playbook steps describe what to do within an action node. Each step has:
- `order`: sequence number (1, 2, 3...)
- `action`: what to do — `click`, `fill`, `fill_form`, `select`, `navigate`, `wait`, `scroll`, `hover`, `upload`, `verify`, `press_key`, `drag`, `resize`, `capture`, `extract_table`, `python_execute`, `verify_download`, `verify_download_content`, `screenshot`, `agent_loop`
- `target`: **semantic description** from the accessibility tree — button text, field labels, placeholder text. Describe as a human would: "Submit button", "Email input field", "Status dropdown". **Never use refs, CSS selectors, or XPaths.**
- `params`: for `fill` actions, include `{ "value": "..." }`

Each playbook step is one atomic intent executed in one browser tool call and maps to at most one recorded call. Draw boundaries at stable page states: fuse actions coupled through ephemeral UI state into that call; split unrelated intents and every stable intermediate into separate steps. Do not use `other`; if no concrete browser-tool-backed action fits, omit that diagnostic observation from `playbookSteps`. Use `click` for switches, checkboxes, and click-to-focus behavior. Use `press_key` with `{ "key": "Escape" }` or an explicit `click` to close popovers and panels; there is no `dismiss`, `toggle`, `focus`, or `handle_native_dialog` action.

### Macros — Always Prefer Over Hardcoded Data

Macros generate fresh values each run, preventing flaky tests from stale or colliding data. **Never hardcode emails, names, phone numbers, or dates when a macro exists.**

| Macro | Output | Example |
|-------|--------|---------|
| `$EMAIL()` | Unique test email | `test-xk9mq2@example-test.com` |
| `$FIRST_NAME()` | Random first name | `Jordan` |
| `$LAST_NAME()` | Random last name | `Chen` |
| `$PHONE()` | US phone (555 prefix) | `+1-555-382-7491` |
| `$UUID()` | Random UUID v4 | `a1b2c3d4-...` |
| `$RANDOM_INT(min, max)` | Random integer | `$RANDOM_INT(100,999)` → `427` |
| `$PICK(a,b,c)` | One listed value at random | `$PICK(212,312,415)` → `312` |
| `$RANDOM_STRING(length)` | Alphanumeric string | `$RANDOM_STRING(8)` → `xK9mQ3bR` |
| `$TODAY()` | Current date (YYYY-MM-DD) | `2026-04-06` |
| `$DATE(days)` | Date offset from today | `$DATE(-7)` → last week |
| `$NOW()` | ISO 8601 timestamp | `2026-04-06T14:30:00.000Z` |
| `$NOW(+5m, 'fmt')` | Shifted time (+5m/-2h/30s/1d), optional UTC format (YYYY MM DD HH mm ss, unpadded H m) | `$NOW(+5m, 'm H * * *')` → `35 14 * * *` |
| `$TIMESTAMP()` | Unix milliseconds | `1771520400000` |
| `$SEQUENCE("name")` | Auto-incrementing per run | `1`, `2`, `3`... |

Macros combine inline: `"QA Test $FIRST_NAME() $LAST_NAME()"`, `"order-$RANDOM_STRING(6)"`

**Prefix test data with "QA Test"** for identifiability.

### Step 3: Create the Workflow

Use `cofactor_workflow_sync` for existing workflows or construct the full workflow JSON and create via the API. Then verify with `cofactor_workflow_get`.

### Example Workflow JSON

```json
{
  "name": "Verify user can create an invoice",
  "description": "Tests the invoice creation flow end-to-end",
  "nodes": [
    {
      "nodeType": "login",
      "configJson": {
        "credentialId": "4f6db838-16be-49e8-8887-8d0be1c83a87",
        "credentialName": "QA User"
      }
    },
    {
      "nodeType": "navigate",
      "configJson": { "pageUrl": "/invoices", "pageTitle": "Invoices" }
    },
    {
      "nodeType": "action",
      "title": "Create a new invoice",
      "configJson": {
        "actionDescription": "Fill out the new invoice form and save",
        "playbookSteps": [
          { "order": 1, "action": "click", "target": "New Invoice button" },
          { "order": 2, "action": "fill", "target": "Client name field", "params": { "value": "QA Test $FIRST_NAME()" } },
          { "order": 3, "action": "fill", "target": "Amount field", "params": { "value": "$RANDOM_INT(100,999)" } },
          { "order": 4, "action": "click", "target": "Save button" }
        ],
        "inlineAssertions": [
          {
            "condition": "Success message 'Invoice created' is visible and the new invoice appears in the list",
            "severity": "fail"
          }
        ]
      }
    }
  ]
}
```

## Managing Workflows

- **cofactor_workflow_list** — Browse existing tests. Filter by Regression membership, `flowType` (standard/setup/seed/teardown), or `search` by name. The response includes active suites and Regression run state; pause and health remain separate from membership.
- **cofactor_workflow_get** — Inspect a test's full definition: nodes, edges, playbook steps, assertions.
- **cofactor_workflow_patch** — Update name, description, preflight, cleanup, or flow type. Only provided fields change. Description, preflight and cleanup are read by people: no raw IDs (name the seed, teardown or record), and write preflight and cleanup as short markdown bullet lists.
- **cofactor_workflow_run** — Trigger execution. Returns a `runId` — use it to track progress.
- **cofactor_workflow_sync** — Atomically replace all nodes and edges. Automatically snapshots current state first so changes are reversible. Read the current DAG with `cofactor_workflow_get` before syncing.

## Monitoring Runs & Debugging Failures

After triggering a workflow run, monitor and debug with:

- **cofactor_workflow_runs_list** — Recent runs for a workflow with status and duration.
- **cofactor_workflow_runs_get** — Detailed run view: step-by-step status, duration, errors. Also works for in-progress runs to check status.
- **cofactor_workflow_runs_diagnostics** — AI-generated failure analysis. Returns root cause and recommendations. Falls back to raw console logs and network requests if no AI analysis is available.

### Regression Suite

- **cofactor_test_suite_run** — Trigger a regression suite execution. Returns suiteId for tracking. Use cofactor_test_suite_list or cofactor_test_suite_get to check results.
- **cofactor_test_suite_list** — Recent regression suite executions with pass/fail counts.
- **cofactor_test_suite_get** — Individual test results within a suite execution.
- **cofactor_test_suite_diagnostics** — Failure diagnostics for a specific test in a suite run.
- **cofactor_test_suite_steps** — Step-by-step breakdown of a test run within a suite.

## Investigating Issues

Issues are bugs discovered by Cofactor during test runs.

- **cofactor_issues_list** — Search and filter issues by severity (`low`/`medium`/`high`), status (`open`/`closed`/`not_a_bug`), or property. Supports full-text search.
- **cofactor_issues_get** — Full issue detail including console errors and network failures from the latest occurrence, plus every evidence item on recent occurrences with signed screenshot/clip links (the first screenshots come back inline as images), and the issue's comments. Use this to understand what went wrong.
- **cofactor_issues_comment** — Add a comment to an issue (`get` returns the comments).
- **cofactor_issues_update** — Edit an occurrence's summary, repro steps, or evidence items (add, replace, or remove by the numbers cofactor_issues_get shows; screenshots as base64 image data).

## Product Map (what the app does, and what covers it)

Areas → capabilities, with flows linked to capabilities so coverage is showable. Available to every organization.

Capabilities have **natural codes** — `CAP-CMM-001`, areas `ARE-CMM` — which are stable and safe to carry between a ticket, a spec, and a tool call. Prefer them over prefixed ids when writing anything a human will read.

- **cofactor_product_map_get** — The whole map for an application. Call this before proposing a new capability so you reuse an existing one by code instead of creating a near-duplicate.
- **cofactor_product_map_coverage** — Linked/covered rollup. Always report the unmapped-flow count beside any coverage figure; coverage is always coverage of the *known* map.
- **cofactor_product_map_resolve_code** — Resolve a code, including one retired by a move. Use this before reporting that a code "does not exist" — it may just have been renumbered.
- **cofactor_product_map_get_capability** — One capability in full: body, linked flows by name, previous codes.
- **cofactor_product_map_link_flows** / **cofactor_product_map_unlink_flows** — Record that a flow covers a capability. Additive/subtractive; other links are preserved.

## API Sequences (API-only workflows)

For APIs that need deterministic, browser-free smoke testing — composed of ordered HTTP calls that chain outputs into inputs.

- **Create** with the same command as any workflow, with `--api-only`:
  `cofactor workflow create --api-only --name "<n>" --sequence-from-file seq.json`
  Returns `{ workflowId, apiSequenceId, nodeId }`. No `--property` — api-sequences are org-scoped.
- **Inspect runs** with the same command as any runs, with `--side api` (or `--side all` for both):
  `cofactor workflow runs list <wf> --side api`
  `cofactor workflow runs get <wf> <runId>`
- **Edit the sequence itself** via `cofactor workflow api-sequence <verb>`:
  - `get <wf>` — dump config + steps
  - `update <wf> --from-file seq.json` — replace config
  - `execute <wf>` — run it
  - `generate <wf> [--prompt "..."]` — AI-draft a config, then refine with `update`
- **Discover endpoints** before composing steps:
  `cofactor api-catalog sources list`
  `cofactor api-catalog endpoints list --search <q>`
  `cofactor api-catalog endpoints create --from-file ep.json` (add a one-off)
- **Read the reference first** for the config/step shape and template syntax:
  `cofactor workflow guide api-sequences`

Templates in step fields use `{{stepId.response.path}}` to reference prior-step outputs and `$MACRO()` for dynamic test data (same macros as browser workflows).

## Common Workflows

### "Let's explore the app"
1. `cofactor_login` (env: prod) → switch to the right org
2. `cofactor_credential_list` → find the right credential
3. `browser_start` → launch browser
4. Load credential and navigate to the app
5. Snapshot, interact, explore

### "Write a test for this feature"
1. Explore the feature via browser (above workflow)
2. `cofactor_credential_list` → get credentialId
3. Construct workflow JSON with nodes, edges, playbook steps, macros
4. Create or sync the workflow
5. `cofactor_workflow_run` → execute it
6. `cofactor_workflow_runs_get` → verify it passes

### "Why did this test fail?"
1. `cofactor_workflow_runs_list` → find the failed run
2. `cofactor_workflow_runs_get` → see which step failed
3. `cofactor_workflow_runs_diagnostics` → AI analysis of the failure
4. If needed, open a browser session to reproduce and investigate

### "What issues have been found?"
1. `cofactor_issues_list` → browse open issues
2. `cofactor_issues_get` → deep dive with console/network errors
