# Hooks Analysis for The Grid

## Executive Summary

Claude Code's hooks system provides **deterministic lifecycle control** that can transform The Grid from a reactive multi-agent orchestrator into a **proactive, self-monitoring system**. The hooks architecture offers 12 distinct event types that can intercept, log, block, and respond to virtually every aspect of agent execution.

**Key Opportunity**: Hooks execute as shell commands with full access to stdin JSON payloads containing tool inputs, session IDs, and transcript paths. This enables Grid to:
1. Enforce delegation rules at the application level (not just prompt-level)
2. Track costs and budgets deterministically
3. Auto-initialize Grid state on session start
4. Clean up resources on session/subagent termination
5. Provide real-time observability into Program execution

**Bottom Line**: Hooks can enforce Grid's Prime Directive ("spawn, don't execute") at the infrastructure level, making rogue MC behavior impossible rather than merely discouraged.

---

## Detailed Analysis

### 1. Lifecycle Hooks: PreToolUse and PostToolUse

#### PreToolUse - The Delegation Enforcer

**What it does**: Fires BEFORE any tool call, can block with exit code 2.

**Grid Opportunity**: **Enforce MC's delegation rules deterministically.**

Currently, MC relies on prompt-level instructions to avoid direct execution:
```
### Forbidden Actions (MC must NEVER do these directly)
- Writing files (spawned Executors write files)
- Editing files (spawned Executors edit files)
- Running bash commands (spawned Executors run commands)
```

With PreToolUse, Grid can **enforce** this:

```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|Bash",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/commands/grid/hooks/enforce-delegation.sh"
          }
        ]
      }
    ]
  }
}
```

The hook script (`enforce-delegation.sh`) would:
1. Check if current session is MC (via session metadata)
2. If MC tries Write/Edit/Bash directly, return exit code 2 with message:
   ```
   "BLOCKED: MC cannot execute directly. Use Task() to spawn an Executor. End of Line."
   ```
3. Allow Programs (subagents) to execute normally

**Impact**: Makes the "rogue MC" anti-pattern **impossible**, not just discouraged.

#### PostToolUse - The Audit Trail

**What it does**: Fires AFTER tool calls complete.

**Grid Opportunities**:

1. **Cost Tracking** - Log every tool invocation to `.grid/budget.json`:
   ```bash
   jq -c '{tool: .tool_name, time: now, session: .session_id}' >> .grid/tool-usage.log
   ```

2. **Scratchpad Auto-Update** - After significant operations, update `.grid/SCRATCHPAD.md`:
   ```bash
   # After Task completions, extract key findings
   if [ "$TOOL_NAME" = "Task" ]; then
     # Parse result, append to scratchpad
   fi
   ```

3. **Auto-Format** - Ensure code quality after writes:
   ```json
   {
     "matcher": "Write|Edit",
     "hooks": [
       { "type": "command", "command": "prettier --write $FILE 2>/dev/null || true" }
     ]
   }
   ```

---

### 2. Session Hooks: SessionStart and SessionEnd

#### SessionStart - Grid Auto-Initialization

**What it does**: Fires when Claude Code starts or resumes a session.

**Grid Opportunity**: **Automatic Grid state initialization.**

Currently, users must explicitly run `/grid:init`. With SessionStart:

```json
{
  "hooks": {
    "SessionStart": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/commands/grid/hooks/session-start.sh"
          }
        ]
      }
    ]
  }
}
```

The `session-start.sh` script could:
1. Check if `.grid/` directory exists
2. If resuming: load `.grid/STATE.md` and `.grid/CHECKPOINT.md`
3. Set environment variables for Grid context
4. Initialize budget tracking for this session
5. Display resume prompt if interrupted mission detected

**Example output on resume**:
```
THE GRID
========

Interrupted mission detected.

Last checkpoint: Phase 01-foundation, Block 01-03
Progress: 42% complete
Context: Building REST API with authentication

Resume? [Y/n]
```

#### SessionEnd - Cleanup and Persistence

**What it does**: Fires when Claude Code session ends.

**Grid Opportunities**:

1. **Save Final State** - Persist critical context:
   ```bash
   # Save session summary to .grid/sessions/
   cat .grid/SCRATCHPAD.md >> .grid/sessions/$(date +%Y%m%d_%H%M%S).md
   ```

2. **Budget Reconciliation** - Finalize cost tracking:
   ```bash
   # Calculate total tokens/cost for session
   ~/.claude/commands/grid/hooks/finalize-budget.sh
   ```

3. **Cleanup Temporary Resources**:
   ```bash
   rm -f .grid/temp/*
   # Keep important state, clean ephemeral data
   ```

---

### 3. Subagent Hooks: SubagentStart and SubagentStop

**This is the most Grid-relevant hook category.**

#### SubagentStart - Program Initialization

**What it does**: Fires when a subagent (Program) is spawned.

**Grid Opportunities**:

1. **Program Registration** - Track all active Programs:
   ```json
   {
     "hooks": {
       "SubagentStart": [
         {
           "matcher": "*",
           "hooks": [
             {
               "type": "command",
               "command": "~/.claude/commands/grid/hooks/register-program.sh"
             }
           ]
         }
       ]
     }
   }
   ```

2. **Budget Check Before Spawn** - Block if over budget:
   ```bash
   # Check current spend against .grid/config.json limits
   CURRENT=$(jq '.total_tokens' .grid/budget.json)
   LIMIT=$(jq '.max_tokens' .grid/config.json)
   if [ "$CURRENT" -gt "$LIMIT" ]; then
     echo "BLOCKED: Budget limit exceeded. Run /grid:budget to review." >&2
     exit 2
   fi
   ```

3. **Role-Specific Initialization**:
   ```json
   {
     "matcher": "grid-executor",
     "hooks": [
       { "type": "command", "command": "echo 'Executor spawned at $(date)' >> .grid/execution.log" }
     ]
   }
   ```

#### SubagentStop - Program Termination Handling

**What it does**: Fires when a subagent completes.

**Grid Opportunities**:

1. **Warmth Extraction** - Auto-extract learnings:
   ```bash
   # Parse subagent output for lessons_learned
   # Append to .grid/LEARNINGS.md
   ```

2. **Verification Trigger** - Auto-spawn Recognizer:
   ```bash
   # If executor completed successfully, trigger verification
   if [ "$EXIT_STATUS" = "success" ]; then
     ~/.claude/commands/grid/hooks/trigger-verification.sh
   fi
   ```

3. **Wave Progression** - Check if wave is complete:
   ```bash
   # Update .grid/STATE.md with completion
   # Signal MC to proceed to next wave
   ```

4. **Error Escalation** - Handle failures:
   ```bash
   if [ "$EXIT_STATUS" = "error" ]; then
     # Log to .grid/errors/
     # Prepare retry context
     # Notify MC of failure
   fi
   ```

---

### 4. Notification Hook - Grid Alerting

**What it does**: Fires when Claude Code sends notifications.

**Grid Opportunities**:

1. **Custom Grid Notifications**:
   ```json
   {
     "hooks": {
       "Notification": [
         {
           "hooks": [
             {
               "type": "command",
               "command": "osascript -e 'display notification \"Grid: Program complete\" with title \"THE GRID\" sound name \"Glass\"'"
             }
           ]
         }
       ]
     }
   }
   ```

2. **Slack/Discord Integration**:
   ```bash
   # Post to webhook when significant events occur
   curl -X POST "$SLACK_WEBHOOK" -d '{"text": "Grid: Build complete"}'
   ```

3. **Desktop Alerts for Checkpoints**:
   ```bash
   # When checkpoint requires human input
   osascript -e 'display dialog "Grid checkpoint reached. Input required." with title "THE GRID"'
   ```

---

### 5. Stop Hook - Completion Handling

**What it does**: Fires when Claude Code finishes responding.

**Grid Opportunities**:

1. **State Persistence** - Auto-save after every interaction:
   ```bash
   # Ensure .grid/STATE.md is current
   # Backup critical state
   ```

2. **Progress Reporting** - Update status after MC responds:
   ```bash
   # Calculate progress percentage
   # Update .grid/progress.json
   ```

3. **Context Monitoring** - Track context usage:
   ```bash
   # Log context size estimates
   # Warn if approaching limits
   ```

---

### 6. PreCompact Hook - Context Management

**What it does**: Fires before Claude Code runs a compact operation.

**Grid Opportunities**:

1. **Preserve Critical Context** - Before compaction:
   ```bash
   # Ensure .grid/CHECKPOINT.md is updated
   # Save current warmth to disk
   # Backup in-flight decisions
   ```

2. **Alert User** - Notify of context pressure:
   ```bash
   echo "Grid: Context compaction imminent. State saved to .grid/"
   ```

---

### 7. UserPromptSubmit Hook - Input Processing

**What it does**: Fires when user submits a prompt, before Claude processes it.

**Grid Opportunities**:

1. **Command Detection** - Intercept `/grid` commands:
   ```bash
   # Parse user input for Grid commands
   # Pre-load relevant state
   ```

2. **Context Injection** - Auto-include Grid state:
   ```bash
   # If Grid is active, inject current STATE.md context
   ```

---

### 8. PermissionRequest Hook - Security Control

**What it does**: Fires when permission dialog is shown, can allow or deny.

**Grid Opportunities**:

1. **Auto-Approve Grid Operations**:
   ```bash
   # If operation is within Grid's known scope, auto-approve
   # Block operations outside project directory
   ```

2. **Budget-Based Permissions**:
   ```bash
   # Require approval for expensive operations when near budget
   ```

---

### 9. Setup Hook - Maintenance Mode

**What it does**: Fires when invoked with `--init`, `--init-only`, or `--maintenance`.

**Grid Opportunity**: Hook into Claude Code's maintenance cycle:
```bash
# Sync Grid state
# Clean old session data
# Update Grid version if needed
```

---

## Quick Wins (Immediate Implementation)

### 1. Delegation Enforcement (HIGH IMPACT)

Create `~/.claude/commands/grid/hooks/enforce-delegation.sh`:

```bash
#!/bin/bash
# Block MC from direct execution

INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
SESSION_ID=$(echo "$INPUT" | jq -r '.session_id')

# Check if this is MC session (via session tracking)
if [ -f ".grid/mc_session_id" ]; then
  MC_SESSION=$(cat .grid/mc_session_id)
  if [ "$SESSION_ID" = "$MC_SESSION" ]; then
    if [[ "$TOOL_NAME" =~ ^(Write|Edit|Bash)$ ]]; then
      echo "BLOCKED: MC cannot execute directly. Spawn an Executor via Task(). End of Line." >&2
      exit 2
    fi
  fi
fi

exit 0
```

Register in settings:
```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|Bash",
        "hooks": [
          { "type": "command", "command": "~/.claude/commands/grid/hooks/enforce-delegation.sh" }
        ]
      }
    ]
  }
}
```

### 2. Tool Usage Logging (MEDIUM IMPACT)

```json
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "jq -c '{tool: .tool_name, time: (now | todate), session: .session_id}' >> .grid/tool-usage.log"
          }
        ]
      }
    ]
  }
}
```

### 3. Session Resume Detection (MEDIUM IMPACT)

Create `~/.claude/commands/grid/hooks/session-start.sh`:

```bash
#!/bin/bash
# Check for interrupted Grid session

if [ -f ".grid/CHECKPOINT.md" ]; then
  CHECKPOINT=$(cat .grid/CHECKPOINT.md | head -5)
  echo "Grid: Interrupted session detected"
  echo "$CHECKPOINT"
fi
```

### 4. Program Completion Notification (LOW EFFORT)

```json
{
  "hooks": {
    "SubagentStop": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Program complete\" with title \"THE GRID\"' 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}
```

---

## Architecture Changes Required

### 1. Hook Infrastructure Directory

Create standardized hook location:
```
~/.claude/commands/grid/hooks/
├── enforce-delegation.sh      # PreToolUse: Block MC direct execution
├── track-costs.sh             # PostToolUse: Budget tracking
├── session-start.sh           # SessionStart: Resume detection
├── session-end.sh             # SessionEnd: State persistence
├── program-start.sh           # SubagentStart: Register programs
├── program-stop.sh            # SubagentStop: Extract warmth
├── budget-check.sh            # PreToolUse: Budget enforcement
└── notify.sh                  # Notification: Custom alerts
```

### 2. Hook Registration

Add to Grid installer (`npx the-grid-cc`):
```bash
# Register Grid hooks in user settings
SETTINGS_FILE="$HOME/.claude/settings.json"
jq '.hooks = {...}' "$SETTINGS_FILE" > tmp.json && mv tmp.json "$SETTINGS_FILE"
```

### 3. Session Tracking

Modify MC to register its session:
```bash
echo "$SESSION_ID" > .grid/mc_session_id
```

This enables hooks to distinguish MC from Programs.

### 4. State File Updates

Update `.grid/` structure:
```
.grid/
├── mc_session_id         # Current MC session
├── active_programs.json  # Running program registry
├── tool-usage.log        # All tool invocations
├── hook_events.log       # Hook trigger history
└── budget.json           # Enhanced with hook data
```

---

## Specific Recommendations

### Priority 1: Delegation Enforcement
- **Why**: Solves the "rogue MC" problem permanently
- **Effort**: Low (single hook script)
- **Impact**: High (enforces Prime Directive)

### Priority 2: SubagentStop for Verification
- **Why**: Auto-triggers Recognizer without MC intervention
- **Effort**: Medium (requires wave tracking)
- **Impact**: High (streamlines workflow)

### Priority 3: Budget Enforcement via Hooks
- **Why**: Prevents runaway costs deterministically
- **Effort**: Medium (requires budget tracking integration)
- **Impact**: High (cost control)

### Priority 4: Session Resume
- **Why**: Seamless continuation of interrupted work
- **Effort**: Low (checkpoint detection)
- **Impact**: Medium (UX improvement)

### Priority 5: Observability/Logging
- **Why**: Debugging, auditing, optimization
- **Effort**: Low (simple logging hooks)
- **Impact**: Medium (operational visibility)

---

## Subagent-Specific Hooks (Frontmatter Pattern)

The hooks documentation reveals that hooks can be defined in subagent frontmatter:

```yaml
---
name: grid-executor
description: Execute Grid tasks
hooks:
  PreToolUse:
    - matcher: "Bash"
      hooks:
        - type: command
          command: "~/.claude/commands/grid/hooks/validate-bash.sh"
  PostToolUse:
    - matcher: "Write|Edit"
      hooks:
        - type: command
          command: "prettier --write $FILE 2>/dev/null || true"
---
```

**Grid Opportunity**: Define role-specific hooks per Program type:

| Program | PreToolUse Hook | PostToolUse Hook |
|---------|-----------------|------------------|
| Executor | Validate commands | Format code, update scratchpad |
| Planner | Block execution tools | Save plans to `.grid/phases/` |
| Recognizer | Block writes | Log verification results |
| Visual Inspector | Validate screenshot paths | Archive screenshots |

---

## Environment Variables

Hooks receive these environment variables:
- `$FILE` - File being edited (Write/Edit tools)
- `$TOOL_INPUT` - Full tool input as JSON string

**Grid Enhancement**: Set custom Grid environment variables in SessionStart:
```bash
export GRID_STATE_DIR=".grid"
export GRID_ACTIVE="true"
export GRID_BUDGET_FILE=".grid/budget.json"
```

---

## Conclusion

The hooks system provides infrastructure-level control that perfectly complements The Grid's orchestration model. The highest-value opportunities are:

1. **Delegation Enforcement** - Make rogue MC impossible
2. **Subagent Lifecycle Management** - Automate warmth transfer and verification
3. **Budget Control** - Deterministic cost limits
4. **Session Continuity** - Seamless resume from interruption

Implementation requires minimal architecture changes but delivers significant improvements in reliability, observability, and user experience.

**Recommended First Step**: Implement delegation enforcement hook to validate the pattern, then expand to SubagentStop hooks for verification triggers.

---

*Analysis by Grid Enhancement Analyst | Section: 06-hooks.md*
*Generated: 2026-01-23*
