# The Grid Hooks System

Hooks enable The Grid to integrate with Claude Code's lifecycle events for budget enforcement, edit verification, and state management.

## Hook Types

| Hook | Trigger | Purpose |
|------|---------|---------|
| `SessionStart` | Claude session begins | Load Grid state, show active mission |
| `SubagentStart` | Before spawning a Program | Enforce budget limits, track spawns |
| `PostToolUse` | After any tool executes | Verify edits, track progress |
| `SubagentStop` | After Program completes | Update budget with actual costs |
| `SessionEnd` | Claude session ends | Archive session, save state |
| `Stop` | Mission explicitly stopped | Ensure state is persisted |

## Files

```
hooks/
├── hooks.json           # Hook configuration for Claude Code
├── budget-check.py      # SubagentStart - budget enforcement
├── verify-edit.sh       # PostToolUse - edit verification
├── session-start.sh     # SessionStart - state restoration
├── session-end.sh       # SessionEnd - state archival
├── track-progress.py    # PostToolUse - operation logging
└── subagent-complete.py # SubagentStop - completion tracking
```

## Budget Enforcement

The `budget-check.py` hook enforces spending limits:

- **Exit 0**: Allow spawn
- **Exit 2**: Block spawn (budget exceeded)

Cost estimates per spawn:
- `opus`: $0.15
- `sonnet`: $0.05
- `haiku`: $0.01

Configure limits in `.grid/budget.json`:
```json
{
  "budget_limit": 5.00,
  "enforcement": "hard"
}
```

## Edit Verification

The `verify-edit.sh` hook ensures edits are substantive:

1. File must exist after Edit/Write
2. File must have content (not empty)
3. Warning if file has <5 lines (potential stub)

## Progress Tracking

All tool operations are logged to `.grid/SCRATCHPAD.md`:

```
[14:32:01] EDIT: edited commands/grid/index.md
[14:32:05] BASH: npm test
[14:32:10] SPAWN: Implement feature X...
```

## Installation

Hooks are automatically registered when The Grid is initialized. To manually install:

```bash
# Copy hooks.json to project root
cp commands/grid/hooks/hooks.json .claude/hooks.json
```

## Testing

```bash
# Test budget enforcement
echo '{"model": "opus"}' | python3 commands/grid/hooks/budget-check.py

# Test edit verification
echo '{"tool_name": "Edit", "tool_input": {"file_path": "test.py"}}' | \
  bash commands/grid/hooks/verify-edit.sh
```
