---
description: Detect, diagnose, and auto-heal failed Playwright tests by updating selectors, waits, and assertions, then re-run to verify
argument-hint: "[test-pattern] [max-iterations]"
---

Run the Playwright test suite, detect failures, diagnose the root cause of each failing test, apply safe fixes, and re-run until the tests pass or the retry budget is exhausted. Only target applications and test code you own or have authorization to modify.

## Steps

1. **Inspect the workspace**.
   - Use `bash` to list the project root and locate `playwright.config.ts`, `playwright.config.js`, or the configured `testDir`.
   - Identify the test command from `package.json` (e.g., `test:e2e`, `test`, `e2e`).
   - Determine whether the user supplied a test pattern in `$1`; if not, use the default project test command or `npx playwright test`.

2. **Run the tests and capture structured results**.
   - Prefer running with JSON and line reporters so failures are machine-readable:
     ```bash
     npx playwright test <pattern> --reporter=line,json --output=./test-results
     ```
   - Save JSON output to a file, e.g. `./test-results/playwright-results.json`.
   - If running all tests is too slow, first list tests with `npx playwright test --list`, then run only the failing subset once identified.

3. **Parse failures**.
   - From the JSON report, collect each failed test: file path, test title, project/browser, error message, and the last run attempt.
   - Count distinct failures. If zero failures, stop and report success.

4. **Gather diagnostics for each failure**.
   - Locate the trace archive for each failing test under `./test-results/` (typically `<test-file>-<project>-<hash>/trace.zip`).
   - Locate screenshots and videos in the same output directory.
   - Read the failing test source file using `read`.
   - Open the trace to inspect the DOM, locator resolution, network, and console errors:
     ```bash
     npx playwright show-trace <path-to-trace.zip>
     ```
     or, if unavailable, use `npx playwright test <file> --trace on` and re-run.
   - Extract the relevant failing line, the locator used, the expected value, and any surrounding context (fixtures, setup, teardown).

5. **Classify the root cause**.
   For each failure, decide which category applies:
   - **Locator broken** — selector no longer matches an element (renamed class/id, removed element, dynamic content).
   - **Timing / flakiness** — element appears but assertion or action races with rendering/network/JS.
   - **Assertion mismatch** — expected text/URL/value changed legitimately (UI copy, route, data).
   - **Environment / data** — missing dependency, wrong baseURL, test data conflict, auth expired, viewport.
   - **Real product bug** — failure represents an actual regression; not safe to auto-heal.

6. **Apply safe auto-heals**.
   Only make changes when the cause is clearly one of the first four categories. Prefer minimal, resilient edits:
   - **Fix locators**:
     - Replace brittle CSS/XPath selectors with semantic Playwright locators in this priority order: `getByRole`, `getByLabel`, `getByPlaceholder`, `getByText`, `getByTestId`.
     - If a dynamic class is unavoidable, prefer stable attributes (`data-testid`, `aria-label`, role + name) over class names.
   - **Fix timing / flakiness**:
     - Add explicit waits via web-first assertions (`await expect(locator).toBeVisible()`).
     - Use `page.waitForURL`, `page.waitForLoadState`, or `page.waitForResponse` when navigation/network is involved.
     - Remove `page.waitForTimeout` if present; replace with deterministic waits.
   - **Fix assertions**:
     - Use `expect(locator).toHaveText(/partial/)` or `toContainText` instead of exact string assertions when copy is volatile.
     - Update URLs to match current routing only if the new route is clearly correct.
   - **Fix environment/data**:
     - Adjust `baseURL`, test fixtures, or setup steps.
     - Regenerate or reseed test data if it is clearly stale.
   - Avoid sweeping rewrites. Edit only the failing tests and helper functions directly responsible.

7. **Re-run failed tests**.
   - Run only the previously failing tests with the same reporter setup.
   - Capture results and compare with the previous run.

8. **Iterate with a retry budget**.
   - Use `max-iterations` from `$2`; default to `3` if not provided.
   - Repeat steps 3–7 until either all targeted tests pass or the budget is exhausted.
   - If a fix introduces a new failure, revert that change before trying an alternative.

9. **Report and escalate**.
   - If all targeted tests pass after healing, report the changes and verification results.
   - If failures remain, summarize:
     - Which tests still fail.
     - The most likely root cause (locator, timing, assertion, environment, product bug).
     - The trace/screenshot paths for human inspection.
     - Recommended next steps or a proposed fix that requires user confirmation.

## Rules

- Do not auto-heal tests against applications you do not own or have explicit authorization to test.
- Do not blindly weaken assertions to make tests pass when the failure signals a real product regression.
- Do not change production application source code; only modify test files, page objects, fixtures, and config.
- Prefer `getByRole`/`getByTestId` over CSS/XPath; keep selectors as resilient as possible.
- Never use `page.waitForTimeout` as a fix; always prefer deterministic waits.
- Keep one behavior per test; do not bundle unrelated fixes into a single large edit.
- Use `edit` for precise test/code changes; use `write` only for new files or complete rewrites you author.
- Preserve TypeScript types and existing code style.
- Do not delete trace archives, screenshots, or videos; they are the primary diagnostic artifacts.
- Stop iterating if a failure clearly indicates a product bug or requires human product decisions (copy, routing, data).

## Safety check before editing

For each proposed change, verify:
1. The original failing line and error message are clearly understood.
2. The fix addresses the diagnosed root cause, not just the symptom.
3. The change follows Playwright best practices from the `playwright-core` skill.
4. The same test passes after the fix in the next iteration.

After completing, summarize:
- Total failures found and the iteration count used.
- Files modified and the nature of each fix (locator, wait, assertion, fixture, config).
- Final test run results.
- Any remaining failures, their likely root cause, and the paths to trace/screenshot artifacts.
- Any changes that need human review before merging.
