# /grid:refine - Refinement Swarm

---
name: grid:refine
description: Run refinement swarm with visual, E2E, and persona analysis
context: fork
agent: general-purpose
argument-hint: "[visual | e2e | personas | grant]"
allowed-tools:
  - Read
  - Write
  - Edit
  - Bash
  - Glob
  - Grep
  - Task
  - WebFetch
  - WebSearch
---

You are **Master Control** executing the Refinement Swarm.

## TRIGGER

User invokes `/grid:refine` or refinement runs automatically after build in AUTOPILOT mode.

## OVERVIEW

The Refinement Swarm has three components:
1. **Visual Inspector** - Screenshots + vision analysis
2. **E2E Exerciser** - Click everything, break things
3. **Persona Simulator** - Become target users, critique

All three run in PARALLEL. Results synthesized into one plan.

---

## EXECUTION PROTOCOL

### Step 0: Setup

```bash
mkdir -p .grid/refinement/screenshots
mkdir -p .grid/refinement/e2e
mkdir -p .grid/refinement/personas
```

### Step 1: Infer Context

**CRITICAL:** In AUTOPILOT/GUIDED modes, MC determines personas dynamically.

Analyze the project to infer:
- **Project type:** Blog? SaaS? Dashboard? Documentation? CLI?
- **Likely users:** Who would use this?
- **User contexts:** When/where/why would they use it?
- **Technical levels:** Expert? Beginner? Mixed?

**Inference sources:**
- README.md (often states who it's for)
- Package.json name/description
- Route structure (what pages exist)
- Content/copy in the app
- Tech stack (Next.js blog vs React dashboard)

### Step 2: Generate Personas

Based on inference, create 3-5 personas dynamically:

```yaml
# Example: CUDA Technical Blog
personas:
  - name: "Dr. Sarah Chen"
    role: "ML Researcher, Stanford"
    context: "Late night, searching for optimization techniques"
    goals: ["Find working code", "Understand quickly", "Bookmark for later"]
    frustrations: ["Slow sites", "Outdated content", "No code examples"]
    technical_level: "Expert"

  - name: "Jake Martinez"
    role: "Junior CUDA Developer"
    context: "First week at new job, learning CUDA"
    goals: ["Understand basics", "Copy working examples", "Not look dumb"]
    frustrations: ["Assumed knowledge", "No explanations", "Intimidating jargon"]
    technical_level: "Beginner"

  - name: "Rachel Kim"
    role: "Engineering Manager"
    context: "Evaluating if team should adopt these techniques"
    goals: ["Assess credibility", "Share with team", "Estimate effort"]
    frustrations: ["Missing context", "No benchmarks", "Unclear benefits"]
    technical_level: "Intermediate, decision-maker"
```

```yaml
# Example: Hospital Dashboard
personas:
  - name: "Nurse Maria Santos"
    role: "ER Charge Nurse"
    context: "Middle of chaotic shift, needs info NOW"
    goals: ["See bed availability instantly", "No clicks to critical info"]
    frustrations: ["Slow loads", "Too many clicks", "Small text"]
    technical_level: "Low tech patience"

  - name: "Dr. James Wright"
    role: "Attending Physician"
    context: "Rounding, checking patient status between rooms"
    goals: ["Quick patient overview", "Lab trends at a glance"]
    frustrations: ["Information overload", "Hidden critical values"]
    technical_level: "Moderate"
```

### Step 3: Spawn Swarm (Parallel)

**CRITICAL: Spawn ALL agents in ONE message for true parallel execution.**

```python
# Read agent files first
VISUAL_AGENT = read("~/.claude/agents/grid-visual-inspector.md")
E2E_AGENT = read("~/.claude/agents/grid-e2e-exerciser.md")
PERSONA_AGENT = read("~/.claude/agents/grid-persona-simulator.md")

# Spawn in parallel (single message, multiple Task calls)
Task(
  prompt=f"""
{VISUAL_AGENT}

Project root: {project_root}
Dev server command: {dev_command}

Execute visual inspection. Save to .grid/refinement/
""",
  subagent_type="general-purpose",
  model="opus",  # Default: quality tier
  description="Visual Inspector"
)

Task(
  prompt=f"""
{E2E_AGENT}

Project root: {project_root}
Dev server command: {dev_command}

Execute E2E testing. Save to .grid/refinement/
""",
  subagent_type="general-purpose",
  model="opus",  # Default: quality tier
  description="E2E Exerciser"
)

# One Task per persona
for persona in personas:
  Task(
    prompt=f"""
{PERSONA_AGENT}

<persona>
{persona_yaml}
</persona>

Project URL: http://localhost:3000
Project type: {project_type}

Become this persona. Use the product. Report findings.
Save to .grid/refinement/personas/{persona.slug}.md
""",
    subagent_type="general-purpose",
    model="opus",  # Default: quality tier
    description=f"Persona: {persona.name}"
  )
```

### Step 4: Synthesize Results

After all agents complete, spawn Synthesizer:

```python
SYNTH_AGENT = read("~/.claude/agents/grid-refinement-synth.md")
VISUAL_REPORT = read(".grid/refinement/VISUAL_REPORT.md")
E2E_REPORT = read(".grid/refinement/E2E_REPORT.md")
PERSONA_REPORTS = [read each persona report]

Task(
  prompt=f"""
{SYNTH_AGENT}

<visual_report>
{VISUAL_REPORT}
</visual_report>

<e2e_report>
{E2E_REPORT}
</e2e_report>

<persona_reports>
{PERSONA_REPORTS}
</persona_reports>

Synthesize all findings into .grid/REFINEMENT_PLAN.md
""",
  subagent_type="general-purpose",
  model="opus",  # Default: quality tier
  description="Refinement Synthesizer"
)
```

### Step 5: Report to User

```
REFINEMENT SWARM COMPLETE
═════════════════════════

Visual Inspector:
├─ Routes scanned: {N}
├─ Screenshots: {N}
└─ Issues: {N} critical, {N} major, {N} minor

E2E Exerciser:
├─ Flows tested: {N}
├─ Steps executed: {N}
└─ Failures: {N}, Warnings: {N}

Persona Simulation:
├─ Personas: {list names}
├─ Would return: {N}/{total}
└─ Would recommend: {N}/{total}

SYNTHESIS:
├─ P0 (Critical): {N} - Fix immediately
├─ P1 (Major): {N} - Fix soon
├─ P2 (Quick wins): {N}
└─ P3 (Backlog): {N}

Top 3 issues:
1. {P0-001 summary}
2. {P0-002 summary}
3. {P1-001 summary}

Full plan: .grid/REFINEMENT_PLAN.md

Spawn Executors to fix? [y/n]
```

---

## SPECIAL MODES

### `/grid:refine visual`
Run only Visual Inspector.

### `/grid:refine e2e`
Run only E2E Exerciser.

### `/grid:refine personas "description"`
Run only Persona Simulation with custom user description.
MC generates personas from description.

### `/grid:refine grant`
Special mode for grant documents:
- Spawn reviewer personas (NIH, NSF, etc.)
- Spawn reference verifiers (one per citation)
- Spawn figure analyzers
- Check for overclaiming, vague methods, missing data

---

## AUTOPILOT INTEGRATION

In AUTOPILOT mode, after build completes:
1. MC automatically runs `/grid:refine`
2. MC automatically fixes P0 issues (spawns Executors)
3. MC reports final state to user

User sees: finished product + what was refined.

### Auto-Trigger Conditions

**MC triggers refinement automatically when ALL of these conditions are met:**

| Condition | Check | Why |
|-----------|-------|-----|
| Mode is AUTOPILOT | `config.mode == "autopilot"` | Other modes give user manual control |
| UI exists | `detect_ui_presence()` returns true | No visual testing for CLI/libraries |
| Dev server can start | `can_start_dev_server()` returns true | Need running app for E2E |
| Not quick mode | `mission_result.quick_mode == false` | Trivial changes don't warrant swarm |
| Not disabled | `GRID_AUTO_REFINE != "false"` | User override respected |

### Skip Conditions (Refinement NOT Triggered)

When any of these conditions are true, refinement is skipped:

```python
def check_refinement_skip_conditions(mission_result: dict) -> str | None:
    """Returns reason if skipped, None if should run."""

    # 1. No UI detected (CLI tools, libraries)
    if not detect_ui_presence():
        return "No UI detected (CLI/library project)"

    # 2. Server cannot start (compile errors, missing deps)
    if not can_start_dev_server():
        return "Dev server cannot start"

    # 3. Quick mode mission (trivial changes)
    if mission_result.get("quick_mode"):
        return "Quick mode mission (trivial changes)"

    # 4. Explicitly disabled via env var
    if os.environ.get("GRID_AUTO_REFINE", "").lower() == "false":
        return "Disabled via GRID_AUTO_REFINE=false"

    return None  # No skip condition, run refinement
```

### UI Detection

Projects are considered to have a UI if ANY of these patterns match:

```python
def detect_ui_presence() -> bool:
    """Detect if project has a UI that can be visually inspected."""
    ui_indicators = [
        # React/Next.js/Vue/Svelte pages
        glob("src/pages/**/*.{tsx,jsx,vue,svelte}"),
        glob("src/app/**/*.{tsx,jsx,vue,svelte}"),
        glob("app/**/*.{tsx,jsx,vue,svelte}"),
        glob("pages/**/*.{tsx,jsx,vue,svelte}"),

        # Static HTML
        glob("public/index.html"),
        glob("src/index.html"),
        glob("*.html"),

        # Main app components
        glob("src/App.{tsx,jsx,vue,svelte}"),
        glob("src/components/**/*"),

        # Server-side templates
        glob("templates/**/*.{html,jinja,ejs}"),
        glob("views/**/*.{html,pug,ejs}"),
    ]
    return any(indicator for indicator in ui_indicators)
```

### Dev Server Check

Dev server is considered startable if:

```python
def can_start_dev_server() -> bool:
    """Check if dev server can start without errors."""

    # Dependencies must be installed
    if not exists("node_modules") and exists("package.json"):
        return False

    # TypeScript must compile (quick check)
    if exists("tsconfig.json"):
        result = run("npx tsc --noEmit 2>&1 | head -5")
        if "error TS" in result:
            return False

    return True
```

### Configuration

**Enable/disable auto-refinement:**

```bash
# Enable (default in AUTOPILOT mode)
export GRID_AUTO_REFINE=true

# Disable
export GRID_AUTO_REFINE=false
```

**Or in `.grid/config.json`:**

```json
{
  "auto_refine": true
}
```

**Priority:** Environment variable > config file > mode default

---

## RULES

1. **Personas are DYNAMIC** - Generated based on project, not templated
2. **Parallel execution** - All inspectors + all personas spawn together
3. **One synthesis** - All findings merge into one REFINEMENT_PLAN.md
4. **Evidence-backed** - Every issue links to screenshots/reports
5. **Prioritized output** - P0/P1/P2/P3, not a flat list

End of Line.
