# Debug a Run: weigh the evidence

## Verifying the reported failure

The failure report (in `reported-failure.md` and the top of `summary.md`) is the **runner's hypothesis** about what failed. It is wrong often enough that you must always verify before forming a diagnosis.

Things that look like a step-3 failure but are really upstream:
- The agent on step 1 picked the wrong "Sign in" link, ended up on the consumer site instead of the staging site, and the failure surfaces as `AuthenticationError` two steps later.
- A cache-replay on step 2 used a stale selector that matched a hidden element; the step "succeeded" but didn't actually click anything; step 3 fails because the modal never opened. **The `success` flag is not evidence the action took effect** — confirm the post-state.
- The runner timed out a step but the page actually loaded fine — the timeout is a platform issue, not the app's fault.

Always cross-reference at least three sources before forming a hypothesis:
1. The screenshot at the failure timestamp (`browser/frames/...`). If that moment was an `evaluate`/observe/wait with no action frame, use the nearest real-pixel frame from the continuous screencast (`browser/screencast/index.jsonl` → the `.jpg` closest in time).
2. The agent's thoughts during the failed step (`thoughts/by-step/<stepId>.md`)
3. Either the network errors (`logs/network-errors.jsonl`) OR the console errors (`logs/console-errors.jsonl`) within ±2s of the failure timestamp

If the screenshot, thoughts, and logs all paint the same picture, the reported failure is probably accurate. If any one disagrees, walk backwards (see procedure step 3).

When you can drive a live browser session (see the `cofactor-browser-testing` skill) and the failure should reproduce for a real user, reproducing it yourself is the strongest verification there is — prefer it over inference when the hypothesis is testable in a few actions.


## Walking backwards

The visible failure is rarely the actual divergence. Common patterns:

- A `click` succeeded 3 steps ago but landed on the *wrong* element — the cache-replay layer hid the mismatch — and the failure surfaces only when the next required field can't be found.
- A cross-host navigation between two earlier steps invalidated the auth session, and the 401 doesn't appear until the next API call.
- A variable was captured from the wrong DOM element on step N, and step N+5 now has a meaningless `$var.X` value.
- The agent went down a wrong branch on a conditional, and the test ran a different path than intended.
- A prior step showed a validation banner or issue toast, but the workflow continued; the later step fails because the page never becomes ready.
- A non-blocking assertion or warning already proved a prerequisite was missing; a later action reports the same missing state as a blocking failure.
- A warning says an expected run, save, import, sync, or publish did not complete; the downstream failure is just the consequence of that missing prerequisite.
- A cached / L2-playbook step logged `success=true` but its action selected/typed *nothing* — a virtualized list never rendered the option, or a stale selector matched nothing — so the artifact it created (a run, a record) launched mis-configured, and the failure surfaces far downstream.

The default mode when the root cause is not obvious is **rule out agent/test mismatch first**: positively confirm that every step from the failure backwards actually *did what it was instructed to* before you entertain any external-cause category (`software_bug` / `app_changed` / `dependency_issue` / `platform_error`). Anchoring on a downstream symptom and labeling it a dependency/app problem — without confirming the upstream steps' effects — is the single most common misdiagnosis.

Walk-backwards algorithm:

1. `Read` `steps/<NNN-1>-<prevStepId>.md` for the step immediately before the failure.
2. **Confirm the step's effect, not just that it ran.** `Read` its screenshot (`browser/frames/<NNNN>-...png`). If the step verified state via `browser_evaluate`/observe/wait (no action frame), the nearest real-pixel frame is in `browser/screencast/` — find it via `browser/screencast/index.jsonl` and **look at it**. Ask: did the page reach the *post-state* this step was supposed to create — the value selected, the field populated, the modal opened?
3. Compare to the instruction by `Read` on `workflow/nodes/<nodeId>.json` — does the post-state match the intent of `actionDescription` and `inlineAssertions`?
4. **A cached/playbook step's `success` is a claim, not proof.** Cache replay and L2 playbooks commit a `success` flag without re-verifying the post-state. When a step ran via cache/L2 (see `committed-actions.md` and the rollup's cache line), descend into it: confirm each of its sub-steps' effects against the screencast filmstrip + the in-window actions. A green ✓ on the parent hides a per-sub-step mismatch (e.g. a `l2_playbook:click` on an option that selected nothing).
5. Skim the rollup's "Agent thoughts" section. Was the agent confused? Did it pick the wrong element, or give up on a sub-goal and proceed anyway?
6. Skim the rollup's "Navigation" section. A cross-host transition (⚠ marker) is a strong signal that auth state was lost between this step and the next.
7. Check whether the step has warnings, non-blocking failures, cache fallback, validation banners, issue toasts, or visible error badges. Treat these as root-cause candidates even if the step status is `success`.
8. Repeat with `steps/<NNN-2>-...md`, `<NNN-3>`, and so on.

Stop only once you have positively confirmed the effect of every step on the path from the failure back to the last confirmed-good state. The first step whose effect you *cannot* confirm — or that you confirm diverged from intent — is your root-cause candidate. Cite that step's screenshot/screencast frame and the diverging detail in your `actuallyHappened` narration.

If the reported failure says a later state was not established, your final answer must name the earlier step that should have established it and the concrete evidence showing why it did not.


## Visual evidence — when to read frames

A large fraction of diagnoses turn on what the page actually *looked like* at a given moment. Text alone cannot tell you:
- Whether an unexpected modal/banner is blocking the click target
- Whether the layout shifted such that the agent's selector resolved to a different element
- Whether the brand on screen matches what the test expected (cross-host redirects often land on a sibling brand)
- Whether a stale cached fragment is being shown
- Whether a button is disabled, missing, or moved

Two visual sources, complementary:

- `browser/frames/<NNNN>-<absoluteTsMs>.png` — a re-render of the DOM **snapshot taken at an action** (click/fill/navigate). Exact DOM, pairs with `browser/doms/` + `browser/a11y/`, but exists **only for actions that snapshot** — a step that read state via `browser_evaluate`/observe/wait has none.
- `browser/screencast/<NNNN>-<absoluteTsMs>.jpg` — the **continuous screencast**: real pixels captured on a timer, so a frame exists at *every* moment, including the evaluate/wait moments the per-action frames miss. Index at `browser/screencast/index.jsonl` (one line per frame: `timestampMs`, `pageId`, `file`); grep it for the moment of interest, then read the nearest `.jpg`. Frames are on the same `timestampMs` axis as `browser/actions.jsonl`, so they correlate with actions and step windows directly. Each step rollup also lists the frames inside its window.

How to use vision:

- Use `Read` on a `.png` or `.jpg` path. The extension triggers multimodal output, so you see the image directly.
- When no action frame covers the moment (evaluate/wait), reach for the screencast frame — that is the only image of what was actually on screen.
- For run-vs-run comparison, read the frame at the same step in `history/last-green/browser/frames/<NNNN>-...png` and the failing run's frame in adjacent `Read` calls. Reason about the visual delta directly.
- When visual evidence is decisive, include a `before_after` entry in your `evidence[]` with the two image paths.

Do not `cat` an image — `Read` is the only way to see it.


## Comparing to a passing run — the green→red methodology

If `summary.md`'s history section names a recent green run, comparison is **required** — it is the highest-yield step for a pass→fail regression. A green→red boundary with an unchanged test eliminates only test-authoring causes; everything else stays live until the comparison discriminates. The **most likely** verdicts are a legitimate app change (`app_changed`), an app regression (`software_bug`), an agent error (`agent_confusion`), and a platform error (`platform_error`) — but two more remain on the table and are easy to mistake for the others: a `dependency_issue` (the data/fixture the test needs was missing or expired *this run* — date-sensitive seed data that wasn't refreshed presents exactly as a stable green→red) and a `data_collision` (the run interacted with the *wrong* data — a leftover record, duplicate row, or wrong tenant). Those two are **less common on a regression but must not be pre-excluded** — a missing-data or wrong-data run looks identical to an app/agent failure until you confirm the target data was actually present. Never default to any one of the six — earn the verdict with evidence.

Procedure:

1. **Materialize the green baseline.** `summary.md`'s "History" section names the green run and the exact mechanism for this workspace:
   - Run the printed `cofactor workflow debug materialize <greenRunId> --out history/last-green/` command.
   `<green>` below means the comparison workspace path.
2. **Establish execution mode on BOTH sides of the boundary — before any visual comparison.** Read each workspace's `timeline/cache-decisions.jsonl` and `thoughts/all.jsonl`. A cache-replayed run has few or no agent thoughts (it replayed recorded actions); a live-agent run has many. The mode pairing changes which hypotheses are plausible:
   - **Green replayed, red fell to live agent** → the red run executed a *different procedure* than every green before it. **First rule out a data cause for the eject**: the playbook ejects to the live agent when its recorded `type → select` / click finds nothing, which is the signature of a **`dependency_issue`** (the option/row/record the recipe targeted is simply absent this run) or a **`data_collision`** (a different record now matches) — confirm by checking whether the live agent's own DOM inspection found the target *present* or *missing*. Only once you've confirmed the target data was present do you compare the recorded recipe's verification with what the live agent improvised — a verification-method mismatch then points to `agent_confusion` (drift), and the cache miss/uncertainty itself may point to `platform_error`. Do NOT read the eject as agent drift when the agent correctly observed the target was gone, and do NOT classify `app_changed` from a replay-vs-live pair without an independent, concrete app-behavior delta visible in both runs' frames.
   - **Both live-agent** → thoughts diff cleanly; interpretation drift vs. a genuine page delta is directly observable.
   - **Green replayed, red replay-failed** → suspect `platform_error` (replay machinery) or a genuine app change that broke the recorded selectors; the frames decide.
3. **Visual comparison.** `Read` the suspect step's screenshot in both runs:
   - `browser/frames/<NNNN>-...png` — failing
   - `<green>/browser/frames/<NNNN>-...png` — passing
   The visual delta is often the smoking gun. Same screens → the app did not change; weigh the agent/platform hypotheses. (If the green workspace has no frames — no trace — fall back to thoughts and node-config diffs.)
4. **Diff thoughts and node configs:**
   - `diff thoughts/by-step/<stepId>.md <green>/thoughts/by-step/<stepId>.md`
   - `diff workflow/snapshot.json <green>/workflow/snapshot.json | head -100`

Common signals from comparison:

- Identical authored workflow + visual/label delta **confirmed in both runs' frames** = **app changed**. Classify `app_changed` (intent unverifiable) unless the delta is clearly a defect (error page, 5xx, broken layout), in which case `software_bug`.
- Different workflow snapshot = **test changed** (possibly `test_underspecified` if the new instructions are ambiguous).
- Same screenshot but different thoughts = **agent interpretation drift** (`agent_confusion`, or `test_underspecified` if the test allowed the prior interpretation).
- Same everything but new network 5xx = **dependency/backend issue** (likely `software_bug` or `dependency_issue`).
- A recorded option/row/record is **absent this run** — replay's select/click matched nothing AND the live agent's DOM inspection confirms the target is genuinely missing (not merely hidden, virtualized, or off-screen) = a **data regression** (`dependency_issue`, e.g. seed data not refreshed for today) or a **data collision** (`data_collision`, the wrong record now matches). This is **not** agent confusion and **not** an app change — the agent reading an empty/"no results" state correctly is evidence *for* this, not against it.
- Green passed by cache replay while red improvised live = **verification drift**, not an app change — see step 2.

## When comparison is unavailable

If the comparison workspace cannot be produced (the materialize command fails), you have NOT performed the required comparison. Do not pick `app_changed` on the regime steer alone — keep the live hypotheses in your writeup and record an explicit openQuestion that the green baseline could not be materialized for comparison.

## The regime gates your verdict

`summary.md`'s History section reports a **Regime** and, when available, an **AUTHORED TEST UNCHANGED / CHANGED** line computed from a content fingerprint of the authored definition. Do not overrotate on a bare "last run green, this run red" — gate the conclusion on the regime:

- **`STABLE_REGRESSION` + AUTHORED TEST UNCHANGED** → the test did not change across the pass→fail boundary, so `test_underspecified` is **off the table** — but that alone does NOT pick a verdict. Run the methodology above to discriminate between `app_changed`, `software_bug`, `agent_confusion`, and `platform_error`, and keep `dependency_issue` and `data_collision` live too (less common on a stable regression, but a missing-data or wrong-data run presents *exactly* as a stable green→red — so confirm the target data was actually present before reaching for an agent/app verdict). Only classify `app_changed` after confirming a concrete behavior delta against the green workspace; name the delta and record in `openQuestions` that you could not verify whether the change was intentional.
- **`STABLE_REGRESSION` + AUTHORED TEST CHANGED** → the test was edited; judge whether the new instructions are ambiguous (`test_underspecified`) before blaming the app.
- **`FLAKY`** → a single green→red does **NOT** justify `app_changed`. The test oscillates; weigh `agent_confusion`, intermittent `dependency_issue`, and `data_collision`. Comparison still helps, but only conclude `app_changed` with a **clear, persistent** behavior delta — never a one-off.
- **`NEW` / `PERSISTENT_FAIL`** → no stable green baseline; rely on the within-run procedure (verify + walk backwards).
