---
name: massu-loop-playwright
description: "When user wants browser-based testing, says 'test in browser', 'playwright audit', or needs visual/functional verification with Playwright"
allowed-tools: Bash(*), Read(*), Write(*), Edit(*), Grep(*), Glob(*), mcp__plugin_playwright_playwright__*, mcp__playwright__*
---
name: massu-loop-playwright

> **Shared rules apply.** Read `.claude/commands/_shared-preamble.md` before proceeding. CR-5, CR-12 enforced.

# Massu Loop Playwright: Browser-Based Audit & Fix Protocol

**Shared rules**: Read `.claude/commands/_shared-preamble.md` for POST-COMPACTION (CR-12), QUALITY STANDARDS, and CR-9 (fix all issues) rules.

---

## Workflow Position

```
/massu-loop -> /massu-loop-playwright -> [/massu-simplify] -> /massu-commit -> /massu-push
(IMPLEMENT)   (BROWSER VERIFY+FIX)      (QUALITY)            (COMMIT)        (PUSH)
```

**This command runs after implementation (standalone or post-massu-loop). It is the browser-level verification and fix loop.**

**Golden Path Integration**: This command is integrated into `/massu-golden-path` as Phase 2G. When running the golden path, this phase auto-triggers if the plan touches UI files. It can also be run standalone.

---

## USAGE

```
# Test a specific URL
/massu-loop-playwright https://example.com/docs

# Test a local dev server page
/massu-loop-playwright http://localhost:3000/docs/getting-started

# Test multiple pages
/massu-loop-playwright https://example.com/docs https://example.com/pricing

# Auto-triggered after massu-loop when plan touches UI files
(integrated -- no manual invocation needed)
```

### Argument Parsing

```
INPUT = $ARGUMENTS

IF INPUT starts with "http":
  MODE = "single" (or "multi" if multiple URLs provided)
  TARGET_URL(s) = INPUT (space-separated URLs)

ELSE IF INPUT starts with "/":
  MODE = "single"
  WARN: "No base URL configured. Please provide a full URL (e.g., https://example.com{INPUT})"
  STOP

ELSE:
  MODE = "single"
  WARN: "Please provide a full URL (starting with http:// or https://)"
  STOP
```

**Note**: Massu is a CLI/package, not a fixed web app. The user MUST provide the full target URL(s) to test. These could be:
- A documentation site
- A demo/marketing page
- Output artifacts generated by Massu (static sites, reports, etc.)
- A local dev server (`http://localhost:...`)

---

## SAFETY RULE (ABSOLUTE)

**NEVER use real client data for testing. NEVER modify production data during testing.**

- ALL test interactions MUST be read-only or use dedicated test data
- NEVER submit forms, create records, or trigger actions on production systems
- NEVER click destructive actions (Delete, Remove, etc.) on live data
- NEVER create test proposals/orders/emails targeting real clients or contacts
- NEVER use real client names in test data
- When a test requires data entry, use clearly fake/test values only
- If testing a system you do not own, limit to observation and navigation

**Violation of this rule is a P0 incident.**

---

## TOOL SELECTION

Use the Playwright MCP plugin tools (`mcp__plugin_playwright_playwright__*`) as the primary browser automation tool. These provide:

| Tool | Purpose |
|------|---------|
| `browser_navigate` | Navigate to URLs |
| `browser_snapshot` | Capture DOM state for inspection |
| `browser_take_screenshot` | Capture visual screenshot for evidence |
| `browser_console_messages` | Retrieve console errors/warnings |
| `browser_network_requests` | Check for failed network requests |
| `browser_click` | Click interactive elements |
| `browser_fill_form` | Fill form fields |
| `browser_select_option` | Select dropdown options |
| `browser_press_key` | Keyboard interactions |
| `browser_hover` | Hover over elements |
| `browser_tabs` | Manage browser tabs |
| `browser_wait_for` | Wait for elements/conditions |
| `browser_evaluate` | Execute JavaScript in browser context |
| `browser_resize` | Test responsive layouts |

If the plugin tools are unavailable, fall back to standalone `mcp__playwright__*` tools (identical API).

---

## PHASE 0: SETUP

### 0.1 Initialize Report

```
TIMESTAMP = current time in PST (America/Los_Angeles), format: YYYY-MM-DD-HH-MM
REPORT_PATH = .claude/playwright-reports/{TIMESTAMP}-{PAGE_SLUG}.md
```

Create the report directory if needed:

```bash
mkdir -p .claude/playwright-reports
```

### 0.2 Navigate to Target URL

```
Use browser_navigate to: {TARGET_URL}
```

If the URL includes a path, navigate directly to that path.

### 0.3 Check Application Status

After navigation, use `browser_snapshot` to capture the page state.

| Indicator | Meaning | Action |
|-----------|---------|--------|
| Page content visible | App/site loaded | PROCEED |
| URL redirected to `/login` or auth page | Not logged in | Attempt persistent session or STOP |
| Error page, blank page, or connection refused | App not running or URL invalid | STOP and report |
| URL is target path with page content visible | Loaded successfully | PROCEED |

### 0.4 If NOT Ready

If the page requires authentication and persistent session cookies are not available, STOP and output:

```
AUTHENTICATION REQUIRED

The Playwright browser cannot access the target application.

Please:
1. The Playwright browser window should be open
2. Log in to the target application manually in that browser
3. Wait until you see the expected page loaded
4. Re-run: /massu-loop-playwright {ORIGINAL_ARGUMENTS}

The command cannot proceed without access to the target page.
```

**Do NOT attempt to type credentials. Do NOT hardcode passwords. Do NOT proceed without a loaded page.**

### 0.5 If Ready

Report to the user:

```
Page confirmed loaded. Starting browser audit...
Mode: {single / multi}
Target: {URL(s)}
Pages to test: {N}
```

---

## PHASE 1: LOAD AUDIT

For each target URL, execute these steps. Capture ALL findings before moving to Phase 2.

### 1.1 Navigate and Wait

```
1. browser_navigate to the target URL
2. browser_wait_for page load (up to 15 seconds)
3. If page does not load in 15 seconds, record as TIMEOUT
```

### 1.2 Console Error Capture

```
1. browser_console_messages -- capture ALL messages
2. Categorize each message:
```

| Category | Pattern | Severity |
|----------|---------|----------|
| **Console Error** | `level: error` | HIGH |
| **Console Warning** | `level: warning` | MEDIUM |
| **React Error** | `Uncaught Error`, `Cannot read properties`, hydration mismatch | CRITICAL |
| **CSP Violation** | `Content Security Policy`, `Refused to`, `blocked by CSP` | HIGH |
| **Auth Warning** | `401`, `403`, `Unauthorized`, `token expired` | HIGH |
| **i18n Missing** | `Missing message`, `MISSING_MESSAGE`, `IntlError` | LOW |
| **Deprecation** | `deprecated`, `will be removed` | LOW |

### 1.3 Network Failure Check

```
1. browser_network_requests -- check for failed requests
2. Record any request with status >= 400 or status = 0 (failed to connect)
```

| Network Issue | Pattern | Severity |
|---------------|---------|----------|
| **500 Error** | Status 500+ | CRITICAL |
| **404 Not Found** | Status 404 on API/resource | HIGH |
| **CORS Failure** | Status 0, CORS error in console | HIGH |
| **Timeout** | Request hung > 10s | MEDIUM |
| **CSP Block** | Resource blocked by CSP | MEDIUM |

### 1.4 CSP Violation Detection

Use `browser_evaluate` to check for CSP violations:

```javascript
// Check for CSP violation reports
window.__cspViolations = window.__cspViolations || [];
document.addEventListener('securitypolicyviolation', (e) => {
  window.__cspViolations.push({
    blockedURI: e.blockedURI,
    violatedDirective: e.violatedDirective,
    originalPolicy: e.originalPolicy
  });
});
```

After a brief wait, collect violations:

```javascript
JSON.stringify(window.__cspViolations || []);
```

### 1.5 Record Load Audit Results

```markdown
### Load Audit: {URL}

| Check | Result | Details |
|-------|--------|---------|
| Console Errors | {N} | [list] |
| Console Warnings | {N} | [list] |
| Network Failures | {N} | [list] |
| CSP Violations | {N} | [list] |
| Load Time | fast/slow/timeout | {ms if available} |
```

---

## PHASE 2: INTERACTIVE TESTING

### 2.1 Element Discovery

Use `browser_snapshot` to capture the full DOM state and identify ALL interactive elements:

- **Buttons**: All `<button>` elements and elements with `role="button"`
- **Links**: All `<a>` elements with `href` attributes
- **Forms**: All `<form>` elements with their inputs
- **Selects/Dropdowns**: All `<select>` and custom dropdown components
- **Tabs**: All tab navigation elements
- **Modals/Dialogs**: Any trigger elements for sheets, dialogs, modals
- **Data Tables**: Sortable headers, pagination, filters, row actions

Create an inventory:

```markdown
### Interactive Element Inventory: {URL}

| # | Element | Type | Text/Label | Testable |
|---|---------|------|------------|----------|
| 1 | Button | button | "Get Started" | YES |
| 2 | Link | a | "Documentation" | YES |
| 3 | Select | select | "Version" | YES |
| 4 | Tab | tab | "Overview" | YES |
```

### 2.2 Systematic Interaction Testing

For EACH testable interactive element:

```
1. Capture console state BEFORE interaction (browser_console_messages)
2. Perform the interaction:
   - Buttons: browser_click
   - Links: browser_click (check navigation or action)
   - Selects: browser_select_option (try each option)
   - Tabs: browser_click (switch between tabs)
   - Forms: browser_fill_form (with safe test data ONLY)
3. Wait briefly for async operations (2-3 seconds)
4. Capture console state AFTER interaction (browser_console_messages)
5. Compare before/after -- record any NEW errors
6. browser_snapshot to verify DOM state after interaction
7. If interaction opened a modal/sheet: test elements inside, then close it
8. Navigate BACK if the interaction changed the URL (unless testing navigation)
```

**SAFETY RULES for interactive testing:**

| Rule | Why |
|------|-----|
| NEVER submit forms with real data | Could create real records |
| NEVER click "Delete" or destructive actions | Could destroy production data |
| NEVER click "Send" on emails/notifications | Would send to real users |
| NEVER click "Submit" on payment/order forms | Would create real transactions |
| For forms: fill but do NOT submit | Test validation without side effects |
| For destructive buttons: test existence, do NOT click | Verify they render, nothing more |

### 2.3 Record Interactive Test Results

For each element tested:

```markdown
| # | Element | Action | Console Errors After | Visual Issue | Status |
|---|---------|--------|---------------------|--------------|--------|
| 1 | "Get Started" button | click | 0 | None | PASS |
| 2 | "Version" select | select "v2" | 1: TypeError | None | FAIL |
| 3 | "Overview" tab | click | 0 | Content missing | FAIL |
```

---

## PHASE 3: VISUAL AUDIT

### 3.1 Broken Image Detection

Use `browser_evaluate` to check for broken images:

```javascript
Array.from(document.querySelectorAll('img')).filter(img =>
  !img.complete || img.naturalWidth === 0
).map(img => ({ src: img.src, alt: img.alt }));
```

### 3.2 Layout Issue Detection

Use `browser_snapshot` and `browser_take_screenshot` to check for:

| Issue | How to Detect |
|-------|---------------|
| **Overflow/Scroll** | Elements extending beyond viewport |
| **Overlapping** | Z-index issues, elements stacking incorrectly |
| **Missing Content** | Empty sections that should have content |
| **Broken Alignment** | Elements not aligned with grid/layout |
| **Text Truncation** | Important text cut off without ellipsis |
| **Icon Issues** | Missing or broken icons |

### 3.3 Responsive Check

Use `browser_resize` to test at key breakpoints:

| Breakpoint | Width | Height | What to Check |
|------------|-------|--------|---------------|
| Desktop | 1440 | 900 | Full layout |
| Tablet | 768 | 1024 | Responsive collapse |
| Mobile | 375 | 812 | Mobile layout |

For each breakpoint:
1. `browser_resize` to the dimensions
2. `browser_take_screenshot` for visual evidence
3. Check for layout breaks, overflow, overlapping elements
4. Resize back to desktop (1440x900) when done

### 3.4 Screenshot Evidence

Take screenshots at these key states:

| State | When | Save As |
|-------|------|---------|
| **Initial Load** | After page fully loads | `{report-dir}/01-initial-load.png` |
| **After Interaction** | After any interaction reveals an issue | `{report-dir}/02-interaction-{element}.png` |
| **Responsive** | At each breakpoint if issues found | `{report-dir}/03-responsive-{breakpoint}.png` |
| **Error State** | When a visual error is visible | `{report-dir}/04-error-{description}.png` |

### 3.5 Record Visual Audit Results

```markdown
### Visual Audit: {URL}

| # | Issue | Type | Location | Severity | Screenshot |
|---|-------|------|----------|----------|------------|
| 1 | Broken image | Image | Hero section | MEDIUM | 04-error-broken-img.png |
| 2 | Layout overflow | Overflow | Sidebar on mobile | HIGH | 03-responsive-375.png |
```

---

## PHASE 4: PERFORMANCE AUDIT

### 4.1 Page Load Timing

Use `browser_evaluate` to collect performance metrics:

```javascript
const perf = performance.getEntriesByType('navigation')[0];
JSON.stringify({
  domContentLoaded: Math.round(perf.domContentLoadedEventEnd - perf.startTime),
  loadComplete: Math.round(perf.loadEventEnd - perf.startTime),
  ttfb: Math.round(perf.responseStart - perf.requestStart),
  domInteractive: Math.round(perf.domInteractive - perf.startTime)
});
```

### 4.2 Resource Analysis

Use `browser_evaluate` to find large resources:

```javascript
performance.getEntriesByType('resource')
  .filter(r => r.transferSize > 500000)
  .map(r => ({
    name: r.name.split('/').pop(),
    url: r.name,
    size: Math.round(r.transferSize / 1024) + 'KB',
    duration: Math.round(r.duration) + 'ms',
    type: r.initiatorType
  }));
```

### 4.3 Network Waterfall Check

Use `browser_network_requests` to identify:

- Requests taking > 3 seconds
- Sequential requests that could be parallelized
- Duplicate requests to the same endpoint
- Large payloads (> 1MB)

### 4.4 Performance Thresholds

| Metric | Good | Needs Work | Critical |
|--------|------|------------|----------|
| DOM Content Loaded | < 2s | 2-5s | > 5s |
| Full Load | < 4s | 4-8s | > 8s |
| TTFB | < 500ms | 500ms-1.5s | > 1.5s |
| Largest Resource | < 500KB | 500KB-2MB | > 2MB |
| API Response | < 1s | 1-3s | > 3s |

### 4.5 Record Performance Results

```markdown
### Performance Audit: {URL}

| Metric | Value | Rating |
|--------|-------|--------|
| DOM Content Loaded | {N}ms | GOOD/WARN/CRITICAL |
| Full Load | {N}ms | GOOD/WARN/CRITICAL |
| TTFB | {N}ms | GOOD/WARN/CRITICAL |
| Largest Resource | {name} ({size}) | GOOD/WARN/CRITICAL |
| Slow API Calls | {N} | GOOD/WARN/CRITICAL |
```

---

## PHASE 5: FIX LOOP

**This is what differentiates `/massu-loop-playwright` from `/massu-verify-playwright`. This command FIXES issues.**

### 5.1 Triage Findings

Compile ALL issues from Phases 1-4 into a single prioritized list:

| Priority | Criteria | Action |
|----------|----------|--------|
| **P0 - CRITICAL** | Console errors, React crashes, 500s, data exposure | Fix immediately in this loop |
| **P1 - HIGH** | Network failures, CSP violations, broken interactions, auth warnings | Fix in this loop |
| **P2 - MEDIUM** | Visual issues, performance warnings, broken images | Fix in this loop if code-fixable |
| **P3 - LOW** | Console warnings, deprecations, i18n missing keys | Document but do not fix unless trivial |

### 5.2 Fix Loop Execution

```
issues = ALL findings from Phases 1-4, sorted by priority (P0 first)
fix_count = 0

FOR EACH issue in issues WHERE priority <= P2:
  1. IDENTIFY the root cause
     - Use Grep/Glob/Read to find the source file
     - Trace from browser error to source code
     - Check CLAUDE.md patterns for known fixes

  2. APPLY the fix
     - Edit the source file(s)
     - Follow ALL CLAUDE.md patterns (no shortcuts)

  3. VERIFY the fix
     - The live site requires a rebuild/deployment to verify browser-side
     - For code-level verification: run applicable VR-* checks
     - VR-GREP: Confirm correct pattern is present
     - VR-NEGATIVE: Confirm incorrect pattern is removed
     - VR-BUILD: npm run build (must pass)
     - VR-TYPE: npx tsc --noEmit (must pass)

  4. LOG the fix
     - Record in fix log table (see report format below)
     - fix_count += 1

END FOR
```

### 5.3 Post-Fix Browser Retest

**After ALL code fixes are applied and build/type checks pass:**

```
1. Reload the target URL in the browser (browser_navigate)
2. Re-run Phase 1 (Load Audit) on all target URLs
3. Re-run Phase 2 (Interactive Testing) for elements that had failures
4. Compare before/after error counts

IF new_errors > 0:
  Add new errors to issues list
  Return to 5.2 (fix loop)
ELSE:
  PROCEED to Phase 6
```

**NOTE**: Browser retesting after code fixes requires a rebuild/deployment. If the site is built locally, rebuild and re-check. If deployed via CI/CD, note that a deployment is needed and document the expected fix.

### 5.4 Zero-Issue Standard

The fix loop continues until:

- ALL P0 and P1 issues have code fixes applied
- ALL P2 issues are either fixed or documented with justification
- Build passes (exit 0)
- Type check passes (0 errors)
- No new console errors introduced by fixes

**Partial fixes are NOT acceptable. Every fixable issue must be addressed.**

---

## PHASE 6: REPORT

### 6.1 Generate Report

Save the complete report to: `.claude/playwright-reports/{TIMESTAMP}-{PAGE_SLUG}.md`

Timestamps MUST be in PST (America/Los_Angeles).

### 6.2 Report Format

```markdown
# Playwright Audit Report

**URL**: {tested URL(s)}
**Date**: {YYYY-MM-DD HH:MM PST}
**Mode**: {single / multi}
**Status**: PASS / FAIL ({N} issues remaining)

---

## Summary

| Metric | Count |
|--------|-------|
| Pages Tested | {N} |
| Console Errors Found | {N} |
| Console Warnings Found | {N} |
| Network Failures Found | {N} |
| CSP Violations Found | {N} |
| Broken Images Found | {N} |
| Interactive Element Failures | {N} |
| Visual Issues Found | {N} |
| Performance Issues Found | {N} |
| **Total Issues** | **{N}** |
| **Issues Fixed** | **{N}** |
| **Issues Remaining** | **{N}** |

---

## Console Errors ({N})

| # | Page | Message | Severity | Fixed |
|---|------|---------|----------|-------|
| 1 | /docs | TypeError: Cannot read properties of null | CRITICAL | YES |

## Console Warnings ({N})

| # | Page | Message | Severity | Fixed |
|---|------|---------|----------|-------|

## Network Failures ({N})

| # | Page | URL | Status | Type | Fixed |
|---|------|-----|--------|------|-------|

## CSP Violations ({N})

| # | Page | Blocked URI | Directive | Fixed |
|---|------|-------------|-----------|-------|

## Broken Images ({N})

| # | Page | Image Src | Alt Text | Fixed |
|---|------|-----------|----------|-------|

## Interactive Element Failures ({N})

| # | Page | Element | Action | Error | Fixed |
|---|------|---------|--------|-------|-------|

## Visual Issues ({N})

| # | Page | Issue | Location | Breakpoint | Fixed |
|---|------|-------|----------|------------|-------|

## Performance Issues ({N})

| # | Page | Metric | Value | Threshold | Fixed |
|---|------|--------|-------|-----------|-------|

---

## Fix Log

| # | Issue | Severity | File(s) Changed | Fix Applied | VR Check | Verified |
|---|-------|----------|-----------------|-------------|----------|----------|
| 1 | TypeError in DocsPage | P0 | packages/core/src/... | Added null guard | VR-GREP | YES |

---

## Screenshots

| # | Description | Path |
|---|-------------|------|
| 1 | Initial page load | .claude/playwright-reports/{dir}/01-initial-load.png |

---

## Unfixed Issues (P3 / Deferred)

| # | Issue | Severity | Reason Not Fixed |
|---|-------|----------|------------------|
| 1 | Deprecation warning: findDOMNode | P3 | Third-party library, not actionable |

---

## Post-Fix Verification

| Check | Command | Result |
|-------|---------|--------|
| Build | npm run build | Exit 0 / PENDING |
| Types | npx tsc --noEmit | 0 errors / PENDING |
| Browser Retest | Console errors after reload | 0 / PENDING DEPLOY |
```

### 6.3 Present to User

After saving the report, present to the user:

1. Summary (total issues found vs fixed)
2. Any remaining unfixed issues with justification
3. The report file path
4. Whether a rebuild/deployment is needed to verify browser-side fixes
5. Recommendation for next steps

---

## INTEGRATION WITH MASSU-LOOP

### Auto-Trigger Criteria

When running as part of `/massu-loop`, this command auto-triggers if the plan touches ANY of these file patterns:

```
packages/*/src/**/*.tsx
packages/*/src/**/*.ts
src/**/*.tsx
src/**/*.ts
src/**/*.css
*.html
```

### Integration Protocol

```
IF massu-loop plan touches UI files:
  1. Identify which pages are affected by the changed files
     - Use file path to determine which output/page is affected
     - Include parent layout/template pages if layout files changed
  2. Run /massu-loop-playwright for each affected page
  3. Include playwright report in massu-loop completion output
  4. Any P0/P1 issues found become GAPS in the massu-loop audit
```

---

## COMMON ISSUE PATTERNS

### Issues This Command Catches That Code Review Misses

| Issue | Example | Root Cause |
|-------|---------|------------|
| Hydration mismatch | `Text content does not match server-rendered HTML` | Date formatting, random IDs |
| Missing null guard | `Cannot read properties of undefined (reading 'map')` | Data not loaded yet |
| CSP violation | `Refused to load script from 'cdn.example.com'` | Missing CSP directive |
| Broken API call | `Failed to fetch`, `NetworkError` | Endpoint renamed/removed |
| Layout shift | Content jumps after data loads | Missing skeleton/loading state |
| Dark mode issue | Element invisible in dark mode | Hardcoded color instead of semantic class |
| Mobile overflow | Horizontal scroll on mobile | Fixed-width element in flex container |
| Stale cache | Old data shown after mutation | Missing query invalidation |

### Common Error Patterns

| Error | Likely Fix |
|-------|-----------|
| `Hydration failed` | Check for browser-only APIs in server components |
| `Cannot update during render` | Move state update to useEffect |
| `Maximum update depth exceeded` | Check useEffect/useCallback dependency arrays |
| `Each child should have a unique key` | Add stable key prop to list items |
| `Invalid hook call` | Check component is not called as regular function |
| `Module not found` | Check import paths, missing dependency |

---

## NON-NEGOTIABLE RULES

1. **NEVER use real client data** -- all test data uses fake/test values only
2. **NEVER click destructive actions** -- no Delete, Send, Submit on live data
3. **NEVER skip a phase** -- all 6 phases must execute
4. **NEVER claim "PASS" with unfixed P0/P1 issues** -- zero-issue standard for critical/high
5. **Evidence over claims** -- every finding has a console message, screenshot, or DOM snapshot
6. **Fix in code, verify in browser** -- fixes are applied to source files, not browser hacks
7. **PST timestamps** -- all report timestamps in America/Los_Angeles timezone
8. **Complete reports** -- even if zero issues found, generate the full report structure
9. **Follow CLAUDE.md patterns** -- all code fixes must comply with established patterns
10. **CR-9 always** -- fix ALL issues encountered, whether from current changes or pre-existing

---

## ERROR HANDLING

### Browser Session Issues

| Scenario | Action |
|----------|--------|
| Page returns 404 | Record as issue, check if route exists in codebase |
| Page hangs (>15s) | Record as TIMEOUT, check for infinite loops |
| Redirected to login/auth | Session expired. STOP. Report partial results. |
| Playwright not available | STOP. Tell user to check MCP server. |
| Console messages unavailable | Use browser_evaluate as fallback to check window.console |

### Fix Loop Safety

| Scenario | Action |
|----------|--------|
| Fix introduces new error | Revert fix, try alternative approach |
| Build fails after fix | Revert fix, investigate build error separately |
| Fix requires DB change | Document but do NOT apply -- DB changes need separate migration |
| Fix scope expands beyond page | Document for separate task, fix only the targeted issue |
| More than 20 issues on one page | Fix P0/P1 first, document P2/P3 for batch fix |

### Circuit Breaker

If the fix loop exceeds 5 iterations on the same page without reaching zero issues:

```
CIRCUIT BREAKER: Fix loop stalled after {N} iterations on {URL}.
Remaining issues: {list}
Options:
  (a) Continue with different approach
  (b) Save partial report and stop
  (c) Escalate remaining issues for manual review
```

Ask the user how to proceed.

---

## AUTO-LEARNING PROTOCOL (MANDATORY after every fix)

After EVERY browser-discovered bug fix:

### Step 1: Ingest into Memory
Use `mcp__massu-codegraph__massu_memory_ingest` with:
- type: "bugfix"
- description: "[Browser symptom] -> [Code fix]"
- files: [list of files changed]
- importance: 5 (if crash/data issue), 3 (if build/type), 2 (if cosmetic)

### Step 2: Record Pattern
Update `.claude/session-state/CURRENT.md` with:
```markdown
## [Category] Browser Bug (discovered [date])
- SYMPTOM: [what the browser showed]
- ROOT CAUSE: [what was wrong in code]
- FIX: [what was changed]
- File(s): [where]
```

### Step 3: Add to Pattern Scanner (if grep-able)
If the incorrect pattern can be detected by grep, add it to `scripts/massu-pattern-scanner.sh`.

### Step 4: Codebase-Wide Search (CR-9)
```bash
grep -rn "[bad_pattern]" packages/ src/ --include="*.ts" --include="*.tsx"
```
Fix ALL instances, not just the one found on this page.

---

## START NOW

**Step 0: Write AUTHORIZED_COMMAND to session state (CR-12)**

Before any other work, update `session-state/CURRENT.md` to include:
```
AUTHORIZED_COMMAND: massu-loop-playwright
```

**Then execute:**

1. Parse arguments to determine mode (single URL / multi URL)
2. Launch Playwright and navigate to target
3. Verify page is loaded (STOP if not accessible)
4. **PHASE 1**: Load audit -- console errors, network failures, CSP violations
5. **PHASE 2**: Interactive testing -- discover and test all interactive elements
6. **PHASE 3**: Visual audit -- broken images, layout issues, responsive check
7. **PHASE 4**: Performance audit -- load times, large resources, slow APIs
8. **PHASE 5**: Fix loop -- triage, fix code, verify, repeat until zero P0/P1 issues
9. **PHASE 6**: Report -- generate comprehensive report, save to filesystem, present to user

**Remember: Find it. Fix it. Prove it. Report it.**
