# Subagents Analysis for Grid Integration

## Executive Summary

The Grid is already a sophisticated user of subagents, but several Claude Code capabilities remain underutilized. The biggest opportunities are: (1) leveraging the `model` field in agent frontmatter for cost-optimized routing instead of relying solely on Task prompts, (2) using `permissionMode` to reduce friction for trusted agents, and (3) implementing `SubagentStart`/`SubagentStop` hooks for automated setup/teardown. These changes could reduce costs by 30-40% and improve execution speed significantly.

---

## Underutilized Features

### 1. Agent Frontmatter Model Selection

- **Current Grid Usage**: Grid agents (grid-executor.md, grid-planner.md, etc.) do NOT specify the `model` field in YAML frontmatter. Model routing is handled entirely through MC's spawn logic and `.grid/config.json`.

- **Opportunity**: Claude Code natively supports `model: sonnet | opus | haiku | inherit` in agent frontmatter. This would allow:
  - Default model per agent type (Scout uses `haiku`, Executor uses `opus`)
  - Automatic cost optimization without MC needing to manage it
  - Simpler spawning (no need to specify model in Task prompt)

- **Implementation**:
  ```yaml
  # In ~/.claude/agents/grid-scout.md
  ---
  name: grid-scout
  description: Fast reconnaissance for existing codebases
  model: haiku  # Scout is read-only, speed-optimized
  tools: Read, Glob, Grep, Bash
  ---
  ```

  ```yaml
  # In ~/.claude/agents/grid-executor.md
  ---
  name: grid-executor
  description: Executes tasks, writes code, commits
  model: inherit  # Inherits from MC (respects /grid:model setting)
  ---
  ```

### 2. Permission Modes

- **Current Grid Usage**: Grid agents don't specify `permissionMode`. All agents inherit default permission behavior, requiring user approval for file writes.

- **Opportunity**: Trusted agents like Executor could use `acceptEdits` or even `bypassPermissions` to eliminate approval friction during builds:
  - `acceptEdits`: Auto-approve file edits (major friction reducer)
  - `bypassPermissions`: Skip all checks (for fully autonomous builds)
  - `dontAsk`: Auto-deny prompts but allowed tools still work
  - `plan`: Read-only mode (perfect for Scout, Recognizer)

- **Implementation**:
  ```yaml
  # grid-executor.md
  ---
  name: grid-executor
  permissionMode: acceptEdits  # Auto-approve file writes
  ---
  ```

  ```yaml
  # grid-scout.md
  ---
  name: grid-scout
  permissionMode: plan  # Read-only exploration
  ---
  ```

  ```yaml
  # grid-recognizer.md
  ---
  name: grid-recognizer
  permissionMode: plan  # Verification is read-only
  ---
  ```

### 3. Preloading Skills

- **Current Grid Usage**: Grid agents read their role definition via `First, read ~/.claude/agents/grid-executor.md...` in Task prompts. This consumes context.

- **Opportunity**: Use the `skills` field to inject Grid protocols automatically at agent startup:
  ```yaml
  ---
  name: grid-executor
  skills:
    - grid-protocols
    - grid-commit-conventions
  ---
  ```
  This would inject shared knowledge without MC needing to inline it.

- **Implementation**:
  1. Create `~/.claude/commands/grid-protocols.md` containing shared Grid protocols
  2. Create `~/.claude/commands/grid-commit-conventions.md` for commit rules
  3. Add `skills` field to agent frontmatter

### 4. Subagent Lifecycle Hooks (SubagentStart/SubagentStop)

- **Current Grid Usage**: No lifecycle hooks. Agents initialize themselves and cleanup is manual.

- **Opportunity**: Use `SubagentStart` and `SubagentStop` hooks for:
  - Database connection setup before db-related agents
  - Dev server startup before visual/E2E agents
  - Git branch checkout before executor agents
  - Cleanup after agent completion

- **Implementation**:
  ```json
  // In settings.json
  {
    "hooks": {
      "SubagentStart": [
        {
          "matcher": "grid-executor",
          "hooks": [
            { "type": "command", "command": "git stash --include-untracked" }
          ]
        },
        {
          "matcher": "grid-visual-inspector|grid-e2e-exerciser",
          "hooks": [
            { "type": "command", "command": "npm run dev &" }
          ]
        }
      ],
      "SubagentStop": [
        {
          "matcher": "grid-executor",
          "hooks": [
            { "type": "command", "command": "git stash pop || true" }
          ]
        }
      ]
    }
  }
  ```

### 5. Agent-Scoped Hooks (in frontmatter)

- **Current Grid Usage**: No agent-scoped hooks.

- **Opportunity**: Define hooks that run only while specific agents are active:
  ```yaml
  # grid-executor.md
  ---
  name: grid-executor
  hooks:
    PostToolUse:
      - matcher: "Edit|Write"
        hooks:
          - type: command
            command: "npm run lint --fix"
  ---
  ```
  This would auto-lint after every file edit by Executor.

### 6. disallowedTools for Safety

- **Current Grid Usage**: Grid agents specify `tools` (whitelist) but not `disallowedTools` (blacklist).

- **Opportunity**: More explicit safety guarantees:
  ```yaml
  # grid-recognizer.md
  ---
  name: grid-recognizer
  disallowedTools: Write, Edit, Bash  # Recognizer CANNOT modify files
  ---
  ```
  Even if inherited tools include Write/Edit, they'd be explicitly blocked.

### 7. Background Execution (Ctrl+B / run_in_background)

- **Current Grid Usage**: MC spawns agents in foreground via Task(). All agents block until complete.

- **Opportunity**: Use background execution for:
  - Parallel research while planning continues
  - Long-running builds while user continues working
  - Visual/E2E testing while other agents execute

- **Implementation**: MC could spawn certain agents with background flag:
  ```
  Ask Claude to "run this in the background"
  ```
  Or users could press Ctrl+B during long operations.

### 8. Built-in Explore Agent

- **Current Grid Usage**: Grid has its own Scout agent for codebase exploration.

- **Opportunity**: Claude Code's built-in `Explore` agent is:
  - Pre-optimized for Haiku (fast, low-latency)
  - Read-only by default
  - Supports thoroughness levels (quick/medium/very thorough)

  Grid could leverage this for initial recon instead of Scout, or Scout could delegate to Explore for specific searches.

---

## Quick Wins (< 1 hour each)

### 1. Add `model` field to all Grid agents (15 min)

```yaml
# Cost-optimized defaults
grid-scout.md:        model: haiku
grid-recognizer.md:   model: haiku
grid-researcher.md:   model: sonnet
grid-planner.md:      model: inherit
grid-executor.md:     model: inherit
grid-visual-inspector.md: model: sonnet
```

This immediately enables cost optimization without changing MC logic.

### 2. Add `permissionMode: plan` to read-only agents (10 min)

```yaml
# Read-only agents get plan mode
grid-scout.md:        permissionMode: plan
grid-recognizer.md:   permissionMode: plan
grid-researcher.md:   permissionMode: plan
```

This makes their read-only nature explicit and prevents accidental writes.

### 3. Add `disallowedTools` to safety-critical agents (10 min)

```yaml
# Explicit safety blocks
grid-recognizer.md:   disallowedTools: Write, Edit
grid-scout.md:        disallowedTools: Write, Edit
```

Defense in depth - even if tools are somehow available, they're explicitly blocked.

### 4. Simplify MC spawn pattern (30 min)

Current MC pattern:
```python
Task(prompt="First, read ~/.claude/agents/grid-executor.md for your role...")
```

With proper frontmatter, simplify to:
```python
Task(prompt="Execute plan 01-01...", subagent_type="grid-executor")
```

The agent's frontmatter defines its identity, tools, and model.

### 5. Add PostToolUse lint hook to Executor (15 min)

```yaml
# grid-executor.md
hooks:
  PostToolUse:
    - matcher: "Edit|Write"
      hooks:
        - type: command
          command: "npm run lint --fix 2>/dev/null || true"
```

Auto-fix lint issues after every file modification.

---

## Architecture Opportunities

### 1. Hybrid Agent Resolution

Currently, Grid agents are custom `.md` files in `~/.claude/agents/`. Consider:

- **Use built-in Explore for quick searches** instead of spawning Scout for simple lookups
- **Layer Grid agents on top of built-in behavior** rather than replacing it entirely
- **Allow MC to choose**: "Is this a quick lookup (use Explore) or full recon (use Scout)?"

### 2. Skill-Based Knowledge Injection

Instead of inlining protocols in every Task prompt, create Grid skills:

```
~/.claude/commands/grid/
  protocols.md          # Shared Grid protocols
  commit-conventions.md # Git commit rules
  warmth-transfer.md    # Warmth protocol
```

Then in agent frontmatter:
```yaml
skills:
  - grid/protocols
  - grid/commit-conventions
```

Benefits:
- Reduces prompt size
- Single source of truth for protocols
- Agents get consistent behavior

### 3. Dynamic Model Selection via Hooks

Instead of hardcoding models, use SubagentStart hooks to check budget:

```json
{
  "hooks": {
    "SubagentStart": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "./scripts/check-budget.sh && echo 'opus' || echo 'sonnet'"
          }
        ]
      }
    ]
  }
}
```

This enables runtime model selection based on remaining budget.

### 4. Agent Chaining via Claude's Native Pattern

The docs mention:
```
Use the code-reviewer subagent to find performance issues,
then use the optimizer subagent to fix them
```

Grid could leverage this for:
- Scout -> Planner (automatic handoff)
- Executor -> Recognizer (automatic verification)
- Visual -> Synth (automatic synthesis)

Currently MC orchestrates all handoffs. Claude could handle some automatically with proper descriptions.

### 5. Resume Pattern Enhancement

The docs show:
```
Continue that code review and now analyze the authorization logic
[Claude resumes the subagent with full context from previous conversation]
```

Grid's warmth transfer pattern is similar but manual. Claude's native resume capability could complement it - allowing mid-session continuation without explicit warmth passing.

---

## Specific Recommendations

### Immediate (This Week)

1. **Add `model` field to all 17 Grid agents** based on their role:
   - `haiku`: Scout, Recognizer (read-only, speed-focused)
   - `sonnet`: Researcher, Visual Inspector, Synth (balanced)
   - `inherit`: Planner, Executor, Debugger (respect user's /grid:model setting)

2. **Add `permissionMode` to read-only agents**:
   - `plan` mode for Scout, Recognizer, Researcher

3. **Add `disallowedTools` as safety layer**:
   - Recognizer: `disallowedTools: Write, Edit, Bash`
   - Scout: `disallowedTools: Write, Edit`

4. **Update MC to use `subagent_type` parameter** instead of "First, read ~/.claude/agents/..." pattern

### Short-term (This Month)

5. **Create Grid skills** for shared protocols:
   - `grid/protocols.md` - Core Grid behavior
   - `grid/commit-conventions.md` - Git commit rules
   - `grid/warmth-transfer.md` - Warmth protocol spec

6. **Add SubagentStart hooks** for common setup:
   - Dev server startup before visual agents
   - Git stash before executor agents
   - npm install check before any build agent

7. **Add PostToolUse hooks** to Executor:
   - Auto-lint after file writes
   - Auto-format after file edits

### Medium-term (Next Quarter)

8. **Experiment with background execution** for:
   - Parallel research during planning
   - Long-running visual tests
   - Non-blocking refinement swarm

9. **Consider leveraging built-in Explore** for:
   - Quick file lookups (replace Scout for simple cases)
   - Initial codebase survey before full Scout recon

10. **Explore Claude's native agent chaining** for:
    - Automatic Scout -> Planner handoff
    - Automatic Executor -> Recognizer verification

---

## Appendix: Grid Agent Inventory

| Agent | Current Tools | Recommended Model | Recommended permissionMode |
|-------|---------------|-------------------|---------------------------|
| grid-accountant | Read, Glob | haiku | plan |
| grid-coordinator | All | inherit | default |
| grid-critic | Read, Glob, Grep | sonnet | plan |
| grid-debugger | All | inherit | default |
| grid-e2e-exerciser | All | sonnet | acceptEdits |
| grid-executor | All | inherit | acceptEdits |
| grid-git-operator | Bash, Read | sonnet | default |
| grid-guard | Read, Glob, Grep | haiku | plan |
| grid-memory | Read, Write | sonnet | acceptEdits |
| grid-persona-simulator | Read, Glob | sonnet | plan |
| grid-planner | Read, Glob, Grep | inherit | plan |
| grid-recognizer | Read, Glob, Grep, Bash | haiku | plan |
| grid-refinement-synth | Read, Write | sonnet | acceptEdits |
| grid-researcher | Read, WebSearch | sonnet | plan |
| grid-scout | Read, Glob, Grep, Bash | haiku | plan |
| grid-updater | All | sonnet | bypassPermissions |
| grid-visual-inspector | All | sonnet | default |

---

## Conclusion

The Grid has excellent subagent architecture, but is leaving Claude Code features on the table. The immediate wins are:

1. **Model routing via frontmatter** - Instant cost reduction with no code changes
2. **Permission modes** - Eliminate approval friction for trusted agents
3. **Safety via disallowedTools** - Defense in depth for read-only agents

The deeper opportunities involve skill-based knowledge injection, lifecycle hooks, and leveraging Claude's native agent behaviors. These would require more significant changes but could substantially improve both cost efficiency and execution speed.

End of Line.
