# MC Protocols Reference

This document contains detailed protocol specifications for Grid operations. Agents read this for full implementation details. MC contains summaries; this document contains the complete specifications.

---

## PROGRAM SPAWNING PROTOCOL

### Plan-Execute Direct Pipeline

**Planner returns structured plan data.** MC receives plans directly in memory, no re-reading from disk.

**Planner completion format:**
```yaml
## PLANNING COMPLETE

cluster: {name}
total_blocks: {N}
total_waves: {M}

plans:
  - id: "01"
    path: ".grid/phases/01-foundation/01-PLAN.md"
    wave: 1
    depends_on: []
    autonomous: true
    files_modified: [list]
    objective: "{brief objective}"

    frontmatter: {full YAML frontmatter}
    content: |
      <objective>...</objective>
      <context>...</context>
      <threads>...</threads>

wave_structure:
  1: ["01", "02"]
  2: ["03"]
```

**MC workflow:**
```python
# Step 1: Spawn Planner
planner_result = Task(prompt="...", ...)

# Step 2: Parse plan data (already in memory!)
plan_data = parse_yaml(planner_result)

# Step 3: Execute by wave (no file reads needed!)
for wave_num in sorted(plan_data['wave_structure'].keys()):
    for plan_id in plan_data['wave_structure'][wave_num]:
        plan = get_plan_by_id(plan_data['plans'], plan_id)

        Task(
          prompt=f"""
First, read ~/.claude/agents/grid-executor.md for your role.

<plan>
---
{plan['frontmatter']}
---
{plan['content']}
</plan>

Execute the plan.
""",
          ...
        )
```

**Benefits:**
- Zero file reads between planning and execution
- MC has all plan metadata immediately
- Wave execution begins instantly after planning
- Files still written by Planner (for persistence/audit)

---

## WAVE EXECUTION PROTOCOL

Plans are assigned **wave numbers** during planning. Execute waves sequentially, with **automatic verification** after each wave:

```
WAVE 1: [plan-01, plan-02]
   |-- Spawn Executors (parallel)
   |-- Wait for completion
   |-- Auto-spawn Recognizer (wave-level verification)
   |-- If GAPS_FOUND -> Spawn Planner --gaps
   v
WAVE 2: [plan-03]
   |-- Spawn Executor
   |-- Wait for completion
   |-- Auto-spawn Recognizer
   |-- If CLEAR -> Proceed
   v
WAVE 3: [plan-04, plan-05]
   |-- Spawn Executors (parallel)
   |-- Wait for completion
   |-- Auto-spawn Recognizer
```

**Verification Timing:** Wave-level, not plan-level. This prevents redundant checks on interdependent plans.

**Verification Skipped When:**
- Executor returned CHECKPOINT (incomplete work)
- Executor returned FAILURE (broken state)
- Plan frontmatter has `verify: false`
- User said "skip verification"

Read wave numbers from plan frontmatter:
```yaml
---
phase: 01-foundation
plan: 02
wave: 1
depends_on: []
---
```

---

## EXECUTE-AND-VERIFY PRIMITIVE

**Verification is AUTOMATIC after successful execution.** The atomic unit is:
```
Executor -> (if SUCCESS) -> Recognizer -> (if GAPS) -> Planner --gaps
```

### Protocol

**1. Executor completes with status:**
- `SUCCESS` -> Auto-spawn Recognizer (default path)
- `CHECKPOINT` -> Return to MC, don't verify incomplete work
- `FAILURE` -> Return to MC with structured failure report

**2. Recognizer spawns AUTOMATICALLY unless:**
- Executor returned CHECKPOINT (incomplete work)
- Executor returned FAILURE (broken build)
- Plan frontmatter contains `verify: false`
- User explicitly said "skip verification"

### Wave Execution with Auto-Verify

```python
def execute_wave(wave_plans, state_content, warmth=None):
    """Execute a wave and auto-verify results."""

    # 1. Spawn all Executors in wave (parallel)
    exec_results = []
    for plan in wave_plans:
        result = Task(
            prompt=f"""
First, read ~/.claude/agents/grid-executor.md for your role.

<state>{state_content}</state>
<plan>{plan['content']}</plan>
{f'<warmth>{warmth}</warmth>' if warmth else ''}

<scratchpad_rules>
You MUST write to .grid/SCRATCHPAD.md during execution:
1. On discovering codebase patterns (IMMEDIATELY)
2. On making decisions affecting other areas (BEFORE COMMITTING)
3. On finding blockers (IMMEDIATELY)
4. On long work (EVERY 5 MINUTES as progress heartbeat)

Before starting, READ scratchpad to see what other Programs learned.
</scratchpad_rules>

Execute the plan. Return SUCCESS | CHECKPOINT | FAILURE.
Include lessons_learned in your SUMMARY.
""",
            subagent_type="general-purpose",
            model=get_model("executor"),
            description=f"Execute {plan['id']}"
        )
        exec_results.append((plan, result))

    # 2. Analyze wave results
    checkpoints = [r for r in exec_results if "CHECKPOINT" in r[1]]
    failures = [r for r in exec_results if "FAILURE" in r[1]]

    if checkpoints:
        return {"status": "CHECKPOINT", "details": checkpoints}
    if failures:
        return {"status": "FAILURE", "details": failures}

    # 3. Skip verification if opted out
    if should_skip_verification(wave_plans):
        return {"status": "SUCCESS", "verification": "SKIPPED"}

    # 4. Collect summaries for wave
    summaries = collect_wave_summaries(wave_plans)
    must_haves = extract_wave_must_haves(wave_plans)

    # 5. Auto-spawn Recognizer
    verify_result = Task(
        prompt=f"""
First, read ~/.claude/agents/grid-recognizer.md for your role.

PATROL MODE: Wave verification

<wave_summaries>
{summaries}
</wave_summaries>

<must_haves>
{must_haves}
</must_haves>

Verify goal achievement. Three-level check:
1. Existence
2. Substantive (not stubs)
3. Wired (connected to system)

Return: CLEAR | GAPS_FOUND | CRITICAL_ANOMALY
""",
        subagent_type="general-purpose",
        model=get_model("recognizer"),
        description=f"Verify wave"
    )

    # 6. Handle gaps
    if "GAPS_FOUND" in verify_result:
        gaps = extract_gaps(verify_result)
        gap_plan = spawn_planner_gaps(gaps, state_content)
        return {"status": "GAPS_FOUND", "verification": verify_result, "gap_closure": gap_plan}

    return {"status": "VERIFIED", "verification": verify_result}


def should_skip_verification(wave_plans):
    """Check if verification should be skipped."""
    for plan in wave_plans:
        if plan.get('frontmatter', {}).get('verify') == False:
            return True
    return session_state.get("skip_verification", False)
```

### Opt-Out Mechanism

**Plan-level:** Add `verify: false` to frontmatter:
```yaml
---
wave: 1
verify: false
verify_reason: "Prototype/throwaway code"
---
```

**Session-level:** User says "skip verification for this session"

---

## WARMTH TRANSFER PROTOCOL

**Programs die, but their knowledge shouldn't.**

When spawning a continuation or fresh Program after another completes:

### 1. Extract Warmth from Dying Program

Programs include `lessons_learned` in their SUMMARY.md:

```yaml
---
# ... other frontmatter
lessons_learned:
  codebase_patterns:
    - "This codebase uses barrel exports (index.ts)"
    - "API routes expect req.json() not req.body"
  gotchas:
    - "The auth middleware runs before validation"
    - "Database timestamps are UTC, not local"
  user_preferences:
    - "User prefers explicit error messages"
    - "User wants mobile-first styling"
  almost_did:
    - "Considered using Zustand but stuck with useState for simplicity"
---
```

### 2. Pass Warmth to Fresh Program

```python
Task(
  prompt=f"""
First, read ~/.claude/agents/grid-executor.md for your role.

<warmth>
Previous Program learned:
{lessons_learned_yaml}
</warmth>

<state>{state}</state>
<plan>{plan}</plan>

Apply the warmth above. Don't repeat mistakes. Build on discoveries.
""",
  ...
)
```

### 3. Warmth Categories

| Category | Contents |
|----------|----------|
| `codebase_patterns` | How this codebase does things |
| `gotchas` | Traps to avoid |
| `user_preferences` | What User seems to want |
| `almost_did` | Decisions considered but rejected (with why) |
| `fragile_areas` | Code that breaks easily |

---

## SCRATCHPAD PROTOCOL

**Mandatory observability during execution.** Programs MUST write to scratchpad--it's not optional.

`.grid/SCRATCHPAD.md` - Programs write here during execution, not just at end.

### Mandatory Writing Rules

Executors MUST write to scratchpad in these situations:

1. **On unexpected codebase patterns** (WRITE IMMEDIATELY)
   - File structure differs from assumption
   - Naming conventions found (e.g., displayName not name)
   - API patterns (e.g., req.json() not req.body)

2. **On decisions affecting other areas** (WRITE BEFORE COMMITTING)
   - Choosing library A over B
   - Schema changes
   - API contract changes

3. **On finding blockers or gotchas** (WRITE IMMEDIATELY)
   - Missing dependencies
   - Authentication requirements
   - External service configuration needs

4. **On long-running work** (WRITE EVERY 5 MINUTES)
   - Progress heartbeat: "Still working on X, 60% complete"
   - Prevents MC from thinking agent died

**Failure to write = protocol violation.** Recognizer checks for scratchpad entries.

### Entry Format

Each entry MUST follow this structure:

```
### {program-id} | {ISO-timestamp} | {category}

**Finding:** {one clear sentence}

**Impact:** {who needs to know / areas affected}

**Action:** [INFORM_ONLY | REQUIRES_CHANGE | BLOCKER]

**Details:**
{Additional context, file paths}
```

**Categories:**
- `PATTERN` - Codebase pattern discovered
- `DECISION` - Decision made affecting other work
- `BLOCKER` - Blocking issue found
- `PROGRESS` - Heartbeat progress update
- `CORRECTION` - Correcting a previous entry

### MC Monitoring During Execution

MC actively monitors scratchpad while Programs execute:

```python
def monitor_scratchpad_during_wave(active_programs, wave_start_time):
    """Monitor scratchpad for updates while Programs execute."""
    last_check = wave_start_time
    max_silence = timedelta(minutes=10)

    while programs_still_running(active_programs):
        time.sleep(30)  # Check every 30 seconds
        scratchpad = read(".grid/SCRATCHPAD.md")
        new_entries = parse_entries_since(scratchpad, last_check)

        if new_entries:
            display_live_updates(new_entries)
            last_check = datetime.now()

        # Alert on stalled agents
        for program in active_programs:
            if time_since_last_entry(program) > max_silence:
                alert_user(f"{program} hasn't written in 10 minutes")
```

**Display live updates:**
```
Live Updates from Executors:
|-- executor-01 (14:32): Found pattern - using displayName not name
|-- executor-02 (14:35): Decision - chose JWT over sessions
|-- executor-01 (14:40): Progress - Auth endpoints 60% done
|-- executor-03 (14:42): BLOCKER - Missing Stripe API keys
```

### Archival After Wave Completion

After wave completes, archive scratchpad:

```python
def archive_scratchpad(wave_number, phase, block):
    scratchpad = read(".grid/SCRATCHPAD.md")
    archive_entry = f"""
---
wave: {wave_number}
phase: {phase}
archived: {datetime.now().isoformat()}
---

{scratchpad}
"""
    append(".grid/SCRATCHPAD_ARCHIVE.md", archive_entry)

    # Clear for next wave
    write(".grid/SCRATCHPAD.md", "---\nupdated: ...\nactive_programs: []\n---\n")
```

---

## CHECKPOINT PROTOCOL

When a Program hits a checkpoint, it returns structured data:

```markdown
## CHECKPOINT REACHED

**Type:** [human-verify | decision | human-action]
**Block:** {block-id}
**Progress:** {completed}/{total} threads complete

### Completed Threads
| Thread | Name | Commit | Files |
| ------ | ---- | ------ | ----- |
| 1.1    | ... | abc123 | ... |

### Current Thread
**Thread {N}:** [name]
**Status:** [blocked | awaiting verification]

### Checkpoint Details
[Type-specific content]

### Awaiting
[What User needs to do]
```

**MC response:**
1. Present checkpoint to User via I/O Tower
2. Collect User response
3. Spawn FRESH continuation Program (not resume) with:
   - Completed threads table
   - User's response
   - Resume point
   - **Warmth from prior Program**

### Checkpoint Types

| Type | Use | Frequency |
|------|-----|-----------|
| `human-verify` | User confirms automation works | 90% |
| `decision` | User chooses between options | 9% |
| `human-action` | Unavoidable manual step (2FA, email link) | 1% |

### Type-Specific Content

**human-verify:**
```markdown
**What was built:**
{Description of completed work}

**How to verify:**
1. {Step 1 - exact URL/command}
2. {Step 2 - what to check}
3. {Expected behavior}
```

**decision:**
```markdown
**Decision needed:**
{What's being decided}

**Options:**
| Option | Pros | Cons |
|--------|------|------|
| option-a | {benefits} | {tradeoffs} |
| option-b | {benefits} | {tradeoffs} |
```

**human-action:**
```markdown
**Automation attempted:**
{What you already did via CLI/API}

**What you need to do:**
{Single unavoidable step}

**I'll verify after:**
{Verification command/check}
```

---

## RETRY PROTOCOL

**When Programs fail, don't retry blind.**

### Structured Failure Report

Programs return on failure:
```yaml
## EXECUTION FAILED

**Block:** {block-id}
**Thread:** {thread that failed}
**Attempts:** {N}

### What Was Tried
1. {Approach 1} -- Failed because: {reason}
2. {Approach 2} -- Failed because: {reason}

### Partial Work
- Created: {files created before failure}
- Commits: {commits made}

### Hypothesis
{Why it's failing}

### Suggested Retry Approach
{Different approach to try}

### Do NOT Retry
- {Approach that definitely won't work}
```

### Retry Spawning

Pass failure context to retry:
```python
Task(
  prompt=f"""
First, read ~/.claude/agents/grid-executor.md for your role.

<prior_failure>
{failure_report}
</prior_failure>

<state>{state}</state>
<plan>{plan}</plan>

Previous attempt failed. DO NOT repeat failed approaches.
Try the suggested retry approach or a novel approach.
""",
  subagent_type="general-purpose",
  model="sonnet",  # Maybe upgrade to opus for retries
  description="Retry execution"
)
```

---

## STATE MANAGEMENT

### STATE.md Structure

Check `.grid/STATE.md` on startup. If it exists, load context:

```markdown
---
cluster: React Todo App
current_phase: 02
current_block: 01
status: in_progress
---

## Current Position
Phase: 2 of 4 (Authentication)
Block: 1 of 3
Status: In progress

Progress: [||||||||                      ] 25%

## Decisions Made
- Use JWT with refresh rotation
- httpOnly cookies for tokens

## Blockers/Concerns
- CORS headers need careful handling

## Session Continuity
Last session: 2024-01-23 14:30
Stopped at: Block 2.1 checkpoint
```

### SUMMARY.md Per Plan

After each plan completes, ensure SUMMARY.md exists with frontmatter:

```yaml
---
phase: 01-foundation
plan: 02
subsystem: auth
requires:
  - phase: 01-foundation
    provides: "Database setup"
provides:
  - "JWT auth endpoints"
affects:
  - 02-dashboard (uses auth)
tech-stack:
  added: [jose, bcrypt]
key-files:
  created: [src/lib/auth.ts]
  modified: [prisma/schema.prisma]
commits: [abc123, def456]

# WARMTH - knowledge that survives
lessons_learned:
  codebase_patterns:
    - "Pattern discovered"
  gotchas:
    - "Gotcha found"
  almost_did:
    - "Considered X, chose Y because Z"
---
```

This frontmatter enables fast context assembly AND warmth transfer.

---

## EXPERIENCE REPLAY

Master Control learns from past projects. This institutional memory improves planning decisions over time.

### Session Startup

On every session start, check for and load learnings:

```python
LEARNINGS_PATH = ".grid/LEARNINGS.md"

if file_exists(LEARNINGS_PATH):
    learnings = read(LEARNINGS_PATH)
    # Parse and apply relevant learnings to current context
```

**What to extract from learnings:**
- Similar project types -> What worked before
- Common failure patterns -> What to avoid
- Successful patterns -> What to replicate
- Tech stack experiences -> Informed choices

### Post-Project Capture

After project completion (all phases done, Recognizer verified), capture learnings:

```python
Task(
  prompt=f"""
First, read ~/.claude/agents/grid-executor.md for your role.

Analyze this completed project and extract learnings.

<project_context>
{STATE_CONTENT}
</project_context>

<all_summaries>
{COLLECTED_SUMMARIES}
</all_summaries>

Write findings to .grid/LEARNINGS.md using the append format below.
Focus on actionable patterns, not project-specific details.
""",
  subagent_type="general-purpose",
  model="sonnet",
  description="Capture project learnings"
)
```

### LEARNINGS.md Format

```markdown
# Grid Learnings

Accumulated patterns from past projects. Read at session start, write after completion.

---

## Entry: {YYYY-MM-DD} - {Project Name}

**Project Type:** {web-app | api | cli | library | integration | etc}
**Tech Stack:** {key technologies used}
**Complexity:** {simple | medium | complex | massive}

### What Worked
- {Pattern or approach that succeeded}

### What Failed
- {Approach that caused problems} -> {How it was fixed}

### Patterns Discovered
- **{Pattern Name}:** {Description of reusable pattern}

### Recommendations for Similar Projects
- {Specific actionable advice}

---
```

---

## PROGRESS UPDATES FORMAT

Never leave User in darkness. Show what's happening (including automatic verification):

```
Executing Wave 1...
|-- Spawning Executors: plan-01, plan-02 (parallel)
|   |-- plan-01: Creating components... [done]
|   |-- plan-02: Writing API routes... [done]
|-- Executors complete
|-- Auto-spawning Recognizer...
|   |-- Verifying artifacts and goal achievement... [done] CLEAR
|-- Wave 1 verified

Executing Wave 2...
|-- Spawning Executor: plan-03
|   |-- plan-03: Integrating auth... [done]
|-- Auto-spawning Recognizer...
|   |-- Verifying artifacts... [warning] GAPS_FOUND
|-- Spawning Planner for gap closure...
|   |-- Creating closure plan... [done]
|-- Wave 2 needs fixes (gap closure plan ready)

Live Scratchpad Updates:
|-- executor-01 (14:32): Found pattern - using displayName
|-- executor-02 (14:35): Decision - chose JWT over sessions

End of Line.
```

The "Auto-spawning Recognizer" line shows verification is automatic, not manual.

---

## VERIFICATION (RECOGNIZER)

After execution completes, spawn Recognizer for goal-backward verification:

**Three-Level Artifact Check:**
1. **Existence** - Does the file exist?
2. **Substantive** - Is it real code (not stub)? Min lines, no TODO/FIXME
3. **Wired** - Is it connected to the system?

**Stub Detection Patterns:**
```
TODO|FIXME|PLACEHOLDER
return null|return {}|return []
<div>Component</div>
onClick={() => {}}
```

If Recognizer finds gaps, spawn Planner with `--gaps` flag to create closure plans.

### Recognizer Patrol Mode

After execution waves complete, spawn Recognizer in patrol mode:

```python
Task(
  prompt=f"""
First, read ~/.claude/agents/grid-recognizer.md for your role.

PATROL MODE ACTIVATED.

<block_summaries>
{all_summary_contents}
</block_summaries>

<must_haves>
{from_plan_frontmatter}
</must_haves>

Survey all completed work. Verify goal achievement, not just task completion.
Report gaps structured in YAML for gap closure planning.
""",
  subagent_type="general-purpose",
  model="sonnet",
  description="Patrol completed blocks"
)
```

Recognizer returns VERIFICATION.md with gaps -> Spawn Planner with `--gaps` flag.

---

## DEBUG SESSION MANAGEMENT

Debug sessions persist in `.grid/debug/` and survive `/clear`:

### Debug Session Structure

```markdown
---
session_id: {timestamp}-{slug}
symptoms: [immutable list]
status: investigating | hypothesis | testing | resolved
created: {ISO timestamp}
updated: {ISO timestamp}
---

## Investigation Graph

### Hypotheses
| # | Hypothesis | Status | Evidence |
|---|------------|--------|----------|
| 1 | Auth token expired | RULED OUT | Token valid per jwt.io |
| 2 | CORS misconfigured | TESTING | Seeing preflight fail |

### Tried
- Checked token expiry -> Valid
- Checked network tab -> CORS error on preflight

### Ruled Out
- Token issues (verified valid)
- Server down (other endpoints work)

### Current Focus
CORS configuration in API route

## Findings
{Updated as investigation proceeds}
```

This captures the investigation graph, not just findings. Resuming knows what was tried.

---

## REFINEMENT SWARM

After building, run refinement to test and polish. In AUTOPILOT mode, this runs automatically.

### Manual Invocation
```
/grid:refine           # Full swarm (visual + E2E + personas)
/grid:refine visual    # Visual inspection only
/grid:refine e2e       # E2E testing only
/grid:refine personas  # Persona simulation only
```

### Refinement Flow
```
1. Infer project context (type, likely users)
2. Generate personas dynamically (3-5 based on context)
3. Spawn in parallel:
   |-- Visual Inspector (screenshots all routes)
   |-- E2E Exerciser (clicks everything)
   |-- Persona Simulators (one per persona)
4. Synthesize all findings -> REFINEMENT_PLAN.md
5. Execute fixes by priority (P0 first)
```

### Output
- `.grid/refinement/screenshots/` - All visual captures
- `.grid/refinement/e2e/` - E2E test screenshots
- `.grid/refinement/personas/` - Per-persona reports
- `.grid/REFINEMENT_PLAN.md` - Prioritized fix plan

---

## DEVIATION RULES (EXECUTOR REFERENCE)

Programs can auto-fix certain issues without asking:

### RULE 1: Auto-fix bugs
**Trigger:** Code doesn't work (broken behavior, errors, wrong output)
**Action:** Fix immediately, add tests if appropriate, verify, continue
**Examples:** SQL errors, logic bugs, type errors, validation bugs, security vulnerabilities, race conditions
**Track:** `[Rule 1 - Bug] {description}`

### RULE 2: Auto-add missing critical functionality
**Trigger:** Missing essential features for correctness/security/operation
**Action:** Add immediately, verify, continue
**Examples:** Error handling, input validation, null checks, auth on protected routes, CSRF protection, rate limiting, indexes, logging
**Track:** `[Rule 2 - Missing Critical] {description}`

### RULE 3: Auto-fix blocking issues
**Trigger:** Something prevents task completion
**Action:** Fix immediately to unblock, verify task can proceed
**Examples:** Missing dependency, wrong types, broken imports, missing env vars, database config, build errors
**Track:** `[Rule 3 - Blocking] {description}`

### RULE 4: Ask about architectural changes
**Trigger:** Fix/addition requires significant structural modification
**Action:** STOP and return checkpoint
**Examples:** New database table, major schema changes, new service layer, library switches, auth approach changes
**Requires:** User decision via I/O Tower

**Priority:** Rule 4 first (if applies, STOP). Otherwise Rules 1-3 auto-fix.

Programs document deviations in SUMMARY.md with rule citations.

---

## MODEL SELECTION LOGIC

```python
def get_model(program_type):
    """Get model based on .grid/config.json or default to opus."""
    try:
        config = json.loads(read(".grid/config.json"))
        tier = config.get("model_tier", "quality")
    except:
        tier = "quality"  # Default: Opus

    if tier == "quality":
        return "opus"
    elif tier == "balanced":
        return "sonnet"
    elif tier == "budget":
        # Some programs need reasoning capability
        if program_type in ["planner", "executor", "persona_simulator"]:
            return "sonnet"
        return "haiku"
    return "opus"
```

Pass `model` parameter to Task():
```python
Task(
  prompt="...",
  subagent_type="general-purpose",
  model="opus",  # Default: quality tier
  description="..."
)
```

---

## SCOUT PROTOCOL (ENHANCED)

Scout has been enhanced with intelligent search capabilities for massive codebases.

### Spawning Enhanced Scout

```python
Task(
    prompt=f"""
First, read ~/.claude/agents/grid-scout.md for your role.

MISSION: {recon_objective}
CODEBASE: {project_root}
QUERY TYPE: {NEEDLE|SURVEY|PATTERN|BOUNDED|EXHAUSTIVE}

Return compressed intelligence report.
""",
    subagent_type="general-purpose",
    model="haiku",
    description="Scout recon"
)
```

### Scout Capabilities (v2)

| Capability | Description |
|------------|-------------|
| **Context Budget** | Tracks usage, spawns helper at 40%, never exceeds 50% |
| **Result Compression** | 10:1 compression ratio, patterns over examples |
| **Relevance Scoring** | Prioritizes high-value directories, skips node_modules |
| **Strategy Selection** | NEEDLE/SURVEY/PATTERN/BOUNDED/EXHAUSTIVE modes |
| **Chunked Searching** | Handles 100k+ file codebases via chunking |
| **Early Termination** | Stops when objective achieved, not when exhausted |

### Search Types

| Type | Use When | Time Budget |
|------|----------|-------------|
| NEEDLE | Looking for specific file/function | 30s |
| SURVEY | Understanding architecture | 90s |
| PATTERN | Finding code conventions | 60s |
| BOUNDED | Searching specific scope | 45s |
| EXHAUSTIVE | Complete enumeration needed | 120s |

### Scout Helper Integration

When Scout hits 40% context, it spawns Scout Helper:

```python
# Scout spawns helper automatically when needed
Task(
    prompt=f"""
First, read ~/.claude/agents/grid-scout-helper.md for your role.

search_scope: {remaining_directories}
search_query: {original_query}
search_type: {search_type}
max_output_lines: 50
""",
    subagent_type="general-purpose",
    model="haiku",
    description="Scout helper - overflow"
)
```

Scout Helper:
- Searches remaining directories Scout couldn't reach
- Returns ONLY compressed findings (max 50 lines)
- Cannot spawn further agents (leaf node)
- Runs on Haiku for speed

### Scout Report Expectations

MC should expect Scout reports to include:

```yaml
# Report metadata
scout_id: {timestamp}
search_type: {type}
terminated_early: {yes/no}
termination_reason: {reason}
confidence: {percent}
budget_used: {percent}
helper_spawned: {yes/no}

# Compressed findings
findings:
  summary: "2-3 sentence overview"
  patterns: [{pattern}, ...]
  key_files: [{file}, ...]
  compression_ratio: "N:M"
```

### When to Spawn Scout

| Situation | Spawn Scout? |
|-----------|--------------|
| New codebase, need architecture overview | YES - SURVEY |
| Looking for specific functionality | YES - NEEDLE |
| Understanding conventions before building | YES - PATTERN |
| Small change, know location | NO - direct read |
| Greenfield project | NO - nothing to scout |

### Scout Failure Handling

If Scout returns incomplete results:

1. Check if helper was spawned (may have additional findings)
2. Check termination reason (may have found enough)
3. If confidence < 50%, consider re-running with EXHAUSTIVE type
4. If budget exceeded, spawn additional Scouts for remaining areas

---

*End of Protocols Reference*
