# Model Configuration Analysis for The Grid

## Executive Summary

Claude Code provides sophisticated model configuration capabilities that The Grid currently underutilizes. The documentation reveals **four major opportunities**: native model aliases, environment variable overrides, per-subagent model specification, and the `opusplan` hybrid mode. By integrating these features, The Grid can achieve better cost optimization, improved reasoning quality, and reduced configuration complexity.

**Key finding:** The Grid's current model routing (quality/balanced/budget tiers in `.grid/config.json`) duplicates functionality that Claude Code provides natively. The `CLAUDE_CODE_SUBAGENT_MODEL` environment variable and agent frontmatter `model:` field offer direct, built-in solutions for per-agent model selection.

---

## Opportunities Identified

### 1. Native Model Alias System

**Current Grid Approach:**
The Grid maintains its own tier system (`quality`, `balanced`, `budget`) with manual mapping:
```json
{
  "model_tier": "quality",
  "models": {
    "planner": "opus",
    "executor": "opus",
    "recognizer": "haiku"
  }
}
```

**Claude Code Native Capability:**
Claude Code provides built-in aliases:
- `default` - Auto-selects based on account type
- `sonnet` - Latest Sonnet (currently 4.5)
- `opus` - Latest Opus (currently 4.5)
- `haiku` - Fast/efficient model
- `sonnet[1m]` - Extended 1M context window
- `opusplan` - Hybrid mode (opus for planning, sonnet for execution)

**Opportunity:**
- Simplify Grid configuration by leveraging native aliases
- Auto-upgrade: When Anthropic releases Sonnet 5, `sonnet` alias automatically uses it
- No version pinning maintenance required

### 2. Environment Variable Overrides

**Discovered Variables:**

| Variable | Purpose | Grid Application |
|----------|---------|------------------|
| `ANTHROPIC_DEFAULT_OPUS_MODEL` | Override opus alias target | Pin specific opus version |
| `ANTHROPIC_DEFAULT_SONNET_MODEL` | Override sonnet alias target | Pin specific sonnet version |
| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | Override haiku alias target | Pin specific haiku version |
| `CLAUDE_CODE_SUBAGENT_MODEL` | **Default model for all subagents** | Set Grid-wide agent default |

**Critical Finding:** `CLAUDE_CODE_SUBAGENT_MODEL` sets the default model for ALL spawned agents. This is exactly what The Grid needs for its tier system.

### 3. Per-Agent Model Specification

**Native Capability (from documentation):**
```yaml
---
name: my-agent
model: sonnet
---
```

Agent frontmatter supports:
- `haiku` - Fast, efficient
- `opus` - Most capable
- `sonnet` - Balanced
- `inherit` - Use main conversation model (default)

**Direct Integration Point:** Grid agents (`/Users/jacweath/grid/agents/*.md`) can specify their model directly in frontmatter.

### 4. Opusplan Mode Deep Dive

**How it works:**
- In **plan mode**: Uses `opus` for complex reasoning and architecture decisions
- In **execution mode**: Automatically switches to `sonnet` for code generation

**Grid Parallel:**
This is essentially what The Grid's `balanced` tier attempts manually:
- Planner uses opus (complex reasoning)
- Executor uses sonnet (implementation)

**Key Insight:** `opusplan` automates this at the Claude Code level, potentially making Grid's manual routing unnecessary for many cases.

### 5. Prompt Caching Configuration

**Discovered Variables:**

| Variable | Effect |
|----------|--------|
| `DISABLE_PROMPT_CACHING` | Disable for all models |
| `DISABLE_PROMPT_CACHING_HAIKU` | Disable for Haiku only |
| `DISABLE_PROMPT_CACHING_SONNET` | Disable for Sonnet only |
| `DISABLE_PROMPT_CACHING_OPUS` | Disable for Opus only |

**Grid Opportunity:** For debugging or specific cloud provider compatibility, The Grid could expose these as options in `.grid/config.json`.

---

## Quick Wins

### 1. Add `model:` to Agent Frontmatter (Low Effort, High Impact)

**Current agent files:**
```markdown
# Grid Planner Program

You are a **Planner Program** on The Grid...
```

**Enhanced with native model specification:**
```markdown
---
name: grid-planner
model: opus
---

# Grid Planner Program

You are a **Planner Program** on The Grid...
```

**Implementation:**
Update all 17 agent files in `/Users/jacweath/grid/agents/`:
- `grid-planner.md` - `model: opus`
- `grid-executor.md` - `model: sonnet` (or `inherit`)
- `grid-recognizer.md` - `model: haiku`
- `grid-visual-inspector.md` - `model: haiku`
- `grid-e2e-exerciser.md` - `model: haiku`
- `grid-persona-simulator.md` - `model: sonnet`
- etc.

### 2. Use `opusplan` as Default (Zero Effort)

For balanced quality/cost without configuration:

```bash
# Launch Claude Code with opusplan
claude --model opusplan

# Or set in environment
export ANTHROPIC_MODEL=opusplan
```

This gives opus-quality planning and sonnet-efficiency execution automatically.

### 3. Leverage `CLAUDE_CODE_SUBAGENT_MODEL` for Tier System

**Current approach:** Read `.grid/config.json`, manually route models
**Better approach:** Set environment variable based on tier

```bash
# Quality tier
export CLAUDE_CODE_SUBAGENT_MODEL=opus

# Balanced tier (let opusplan handle it)
export ANTHROPIC_MODEL=opusplan

# Budget tier
export CLAUDE_CODE_SUBAGENT_MODEL=haiku
```

---

## Architecture Changes

### Current Grid Model Routing Architecture

```
User runs /grid:model quality
    |
    v
.grid/config.json updated
    |
    v
MC reads config on spawn
    |
    v
MC manually selects model per agent type
    |
    v
Task() spawned with model context
```

**Problems:**
1. Manual routing logic in MC
2. Config file as source of truth (not env vars)
3. No leverage of native Claude Code features
4. Model versions hardcoded

### Proposed Architecture (Native Integration)

```
User runs /grid:model quality
    |
    v
Grid sets environment variables:
  CLAUDE_CODE_SUBAGENT_MODEL=opus
  (or ANTHROPIC_MODEL=opusplan for balanced)
    |
    v
Agent frontmatter specifies model: if override needed
    |
    v
Claude Code handles routing natively
```

**Benefits:**
1. Claude Code handles model selection
2. Auto-upgrades when new models release
3. Per-agent overrides via frontmatter
4. MC simplified (no model routing logic)

### Migration Path

**Phase 1: Add Frontmatter (Non-Breaking)**
- Add `model:` to all agent files
- Grid continues to work as before
- Claude Code now has native hints

**Phase 2: Environment Variable Integration**
- `/grid:model` sets `CLAUDE_CODE_SUBAGENT_MODEL`
- Fallback to config.json for backward compatibility

**Phase 3: Simplify MC**
- Remove model routing logic from MC
- Let Claude Code handle it
- MC focuses on orchestration only

---

## Specific Recommendations

### Recommendation 1: Implement `opusplan` as `balanced` Default

**Rationale:** `opusplan` provides exactly what `balanced` tier attempts:
- Opus for planning/reasoning
- Sonnet for execution

**Implementation:**
```bash
# In /grid:model balanced
export ANTHROPIC_MODEL=opusplan
# Remove manual planner/executor model assignment
```

### Recommendation 2: Add Frontmatter to All Agents

**Template:**
```yaml
---
name: grid-{agent-type}
description: {agent description}
model: {opus|sonnet|haiku|inherit}
allowed-tools:
  - {tools}
---
```

**Suggested Model Assignments:**

| Agent | Model | Rationale |
|-------|-------|-----------|
| grid-planner | opus | Complex reasoning, architecture |
| grid-executor | inherit | Match MC's model (opusplan optimizes this) |
| grid-recognizer | haiku | Fast verification, simple checks |
| grid-visual-inspector | haiku | Image analysis, quick |
| grid-e2e-exerciser | haiku | Click testing, repetitive |
| grid-persona-simulator | sonnet | Needs reasoning for personas |
| grid-refinement-synth | sonnet | Synthesis requires reasoning |
| grid-debugger | opus | Complex bug investigation |
| grid-researcher | sonnet | Research + synthesis |
| grid-scout | haiku | Quick file discovery |
| grid-accountant | haiku | Cost calculations, simple |
| grid-git-operator | haiku | Git operations, simple |

### Recommendation 3: Add Extended Context Option

**Use Case:** Long-running missions accumulate context. The `[1m]` suffix enables 1M token context.

**Implementation in `/grid:model`:**
```
/grid:model extended    # Uses sonnet[1m] or equivalent
```

**When to use:**
- Missions with 50+ files
- Multi-phase architecture changes
- Long-running daemon operations

### Recommendation 4: Expose Prompt Caching Controls

**Add to `.grid/config.json`:**
```json
{
  "prompt_caching": {
    "enabled": true,
    "disable_for": []  // or ["haiku", "opus", "sonnet"]
  }
}
```

**Use cases:**
- Debugging model behavior
- Cloud provider compatibility
- Cost analysis (see non-cached costs)

### Recommendation 5: Smart Model Escalation

**Concept:** Start cheap, escalate when needed.

```
Initial spawn: haiku
    |
    v
Agent detects complexity? Report to MC
    |
    v
MC respawns with: sonnet
    |
    v
Still struggling? Escalate to: opus
```

**Implementation:**
- Agents include `complexity_detected: true` in checkpoint returns
- MC reads this and spawns fresh agent with higher-tier model
- Tracks escalations in `.grid/budget.json`

---

## Cost Optimization Strategies

### Strategy 1: Model-Aware Task Sizing

| Task Type | Recommended Model | Rationale |
|-----------|------------------|-----------|
| File discovery | haiku | Simple glob/grep |
| Code analysis | sonnet | Needs understanding |
| Architecture decisions | opus | Complex reasoning |
| Bug fixes | sonnet | Balanced |
| Test writing | haiku | Formulaic |
| Documentation | haiku | Simple generation |

### Strategy 2: Opusplan for Mixed Workloads

When a mission has both planning and execution:
- Use `opusplan` as base model
- Override specific agents with frontmatter if needed
- Result: Optimal model for each phase automatically

### Strategy 3: Context Window Optimization

| Mission Size | Model Suffix | Context |
|--------------|--------------|---------|
| Small (<10 files) | Standard | 200k |
| Medium (10-30 files) | Standard | 200k |
| Large (30-100 files) | Consider `[1m]` | 1M |
| Massive (100+ files) | `[1m]` required | 1M |

**Note:** Extended context has different pricing. Track in budget.

---

## Integration with Existing Grid Features

### Budget System Integration

Current budget tracking in `.grid/budget.json` should include:
```json
{
  "model_costs": {
    "opus": {"spawns": 5, "estimated_cost": "$2.50"},
    "sonnet": {"spawns": 12, "estimated_cost": "$0.60"},
    "haiku": {"spawns": 25, "estimated_cost": "$0.10"}
  }
}
```

### Daemon Mode Integration

For `/grid:daemon` long-running operations:
- Start with `sonnet` for efficiency
- Agent can request escalation via checkpoint
- Track model switches in daemon log

### Debug Mode Integration

For `/grid:debug` systematic investigation:
- Use `opus` by default (complex reasoning)
- Or `opusplan` to get opus thinking, sonnet execution

---

## Summary

The Grid can significantly improve its model routing by leveraging Claude Code's native capabilities:

1. **Use `opusplan` as default** - Free optimization
2. **Add model frontmatter to agents** - Per-agent control without MC logic
3. **Leverage `CLAUDE_CODE_SUBAGENT_MODEL`** - Grid-wide default
4. **Consider `[1m]` for large missions** - Extended context when needed
5. **Smart escalation** - Start cheap, escalate when complexity detected

These changes simplify MC (less routing logic), improve cost efficiency (right model for right task), and ensure automatic upgrades when new models release.

---

*End of Line.*
