# /grid:budget - Budget and Cost Management

---
name: grid:budget
description: Configure spending limits, track costs, and view usage reports
disable-model-invocation: true
argument-hint: "[set $N | estimate | report | reset | unlimited]"
allowed-tools:
  - Read
  - Write
  - Edit
  - Glob
  - Grep
  - AskUserQuestion
---

Manage cost tracking, budget limits, and usage reporting for Grid operations.

## USAGE

```
/grid:budget                    # Show current budget status and usage
/grid:budget set <amount>       # Set budget limit (e.g., "set $50" or "set 50")
/grid:budget estimate           # Estimate cost of pending work
/grid:budget report             # Detailed usage report
/grid:budget reset              # Reset usage counters (keeps budget limit)
/grid:budget unlimited          # Remove budget limit (dangerous)
```

## CONCEPTS

### Cost Model

The Grid estimates costs based on Claude API pricing:

| Model | Input (per 1M tokens) | Output (per 1M tokens) |
|-------|----------------------|------------------------|
| **Opus 4.5** | $5.00 | $25.00 |
| **Sonnet 4.5** | $3.00 | $15.00 |
| **Haiku 4.5** | $1.00 | $5.00 |

### Token Estimation

Since The Grid runs within Claude Code (no direct API access), costs are ESTIMATED from:

1. **Prompt size** - Characters in spawn prompts (chars / 4 ~ tokens)
2. **Response patterns** - Typical output ratios per agent type
3. **File operations** - Files read/written add to context
4. **Historical data** - Learn from past executions

**Estimation Formula:**
```
estimated_tokens = prompt_chars / 4
estimated_cost = (input_tokens * input_rate + output_tokens * output_rate) / 1_000_000
```

### Budget Enforcement

When a budget is set, The Grid tracks estimated costs and:

| Threshold | Action |
|-----------|--------|
| 0-75% | Normal operation |
| 75-90% | Warning displayed |
| 90-100% | Confirmation required before each spawn |
| 100%+ | **HARD STOP** - No new spawns until budget increased |

## OUTPUT FORMATS

### Status Display (`/grid:budget`)

```
GRID BUDGET
===========

Budget Limit:  $50.00
Used:          $12.47 (24.9%)
Remaining:     $37.53

[=========-                              ] 24.9%

Session Breakdown:
  Planner spawns:    2 x opus    ~$3.20
  Executor spawns:   4 x opus    ~$8.40
  Recognizer spawns: 1 x sonnet  ~$0.87
  ────────────────────────────────
  Total estimated:               $12.47

Last 24h:
  Spawns: 7
  Tokens: ~498,000 in / ~124,000 out

End of Line.
```

### Budget Warning (75%+)

```
BUDGET WARNING
==============

Budget: $50.00
Used:   $42.15 (84.3%)

[================================--      ] 84.3%

Remaining budget may allow ~2 more agent spawns.

Options:
  1. Continue (carefully)
  2. Increase budget: /grid:budget set $100
  3. Switch to budget tier: /grid:model budget

Proceed with current spawn? [y/N]
```

### Budget Exceeded (100%+)

```
BUDGET EXCEEDED
===============

Budget: $50.00
Used:   $52.34 (104.7%)

[========================================] 104.7% OVER

Current spawn BLOCKED.

To continue:
  /grid:budget set $75      # Increase limit
  /grid:budget reset        # Reset counters (if new session)
  /grid:budget unlimited    # Remove limit (not recommended)

End of Line.
```

### Cost Estimate (`/grid:budget estimate`)

```
COST ESTIMATE
=============

Pending Work:
  Cluster: Authentication System
  Blocks: 3
  Estimated Spawns: 8

Breakdown:
  Planning Phase:
    1x Planner (opus)              ~$1.60

  Execution Phase:
    Wave 1: 2x Executor (opus)     ~$4.20
    Wave 2: 1x Executor (opus)     ~$2.10

  Verification Phase:
    3x Recognizer (sonnet)         ~$2.61

  Refinement Phase:
    1x Visual Inspector (sonnet)   ~$0.87
    1x E2E Exerciser (sonnet)      ~$0.87
    2x Persona Simulator (sonnet)  ~$1.74
    1x Refinement Synth (sonnet)   ~$0.87

────────────────────────────────────────
ESTIMATED TOTAL:                   ~$14.86

Current Budget: $50.00
After completion: ~$35.14 remaining

Model Tier Comparison:
  Quality (opus):   ~$14.86
  Balanced (sonnet): ~$8.92  (40% savings)
  Budget (haiku):    ~$4.46  (70% savings)

End of Line.
```

### Usage Report (`/grid:budget report`)

```
GRID USAGE REPORT
=================

Period: 2026-01-20 to 2026-01-23

SUMMARY
-------
Total Sessions:     3
Total Spawns:      24
Est. Input Tokens:  1,847,000
Est. Output Tokens: 461,750
Est. Total Cost:    $47.83

BY SESSION
----------
| Date       | Cluster          | Spawns | Est. Cost |
|------------|------------------|--------|-----------|
| 2026-01-23 | Auth System      |     8  |   $14.86  |
| 2026-01-22 | Dashboard        |    10  |   $21.32  |
| 2026-01-20 | API Endpoints    |     6  |   $11.65  |

BY AGENT TYPE
-------------
| Agent              | Count | Model  | Est. Cost |
|--------------------|-------|--------|-----------|
| Planner            |     3 | opus   |    $4.80  |
| Executor           |    12 | opus   |   $25.20  |
| Recognizer         |     5 | sonnet |    $4.35  |
| Visual Inspector   |     2 | sonnet |    $1.74  |
| E2E Exerciser      |     1 | sonnet |    $0.87  |
| Persona Simulator  |     1 | sonnet |    $0.87  |

BY MODEL TIER
-------------
| Model  | Spawns | Est. Cost | % of Total |
|--------|--------|-----------|------------|
| opus   |     15 |   $30.00  |    62.7%   |
| sonnet |      9 |   $17.83  |    37.3%   |
| haiku  |      0 |    $0.00  |     0.0%   |

COST TREND
----------
           $25 |     *
               |   * *
           $15 | *   * *
               |         *
            $5 |
               +------------------
                Mon Tue Wed Thu

End of Line.
```

## CONFIGURATION

### Budget Config File

`.grid/budget.json`:

```json
{
  "budget_limit": 50.00,
  "currency": "USD",
  "enforcement": "hard",
  "warning_threshold": 0.75,
  "confirmation_threshold": 0.90,
  "current_session": {
    "started": "2026-01-23T10:00:00Z",
    "estimated_cost": 12.47,
    "spawns": [
      {
        "timestamp": "2026-01-23T10:05:00Z",
        "agent": "planner",
        "model": "opus",
        "prompt_chars": 24000,
        "est_input_tokens": 6000,
        "est_output_tokens": 8000,
        "est_cost": 1.60
      }
    ]
  },
  "history": {
    "total_cost": 147.83,
    "total_spawns": 84,
    "sessions": 12
  }
}
```

### Budget Settings

| Setting | Default | Description |
|---------|---------|-------------|
| `budget_limit` | null | Max spending (null = unlimited) |
| `enforcement` | "hard" | "hard" = block, "soft" = warn only |
| `warning_threshold` | 0.75 | Warn at 75% usage |
| `confirmation_threshold` | 0.90 | Require confirmation at 90% |

## INTEGRATION WITH MC

Master Control checks budget before EVERY spawn:

```python
def check_budget_before_spawn(agent_type, model):
    """Returns: (allowed, message)"""
    budget = load_budget_config()

    if budget['budget_limit'] is None:
        return True, None  # Unlimited

    estimated_spawn_cost = estimate_spawn_cost(agent_type, model)
    new_total = budget['current_session']['estimated_cost'] + estimated_spawn_cost
    usage_ratio = new_total / budget['budget_limit']

    if usage_ratio > 1.0:
        if budget['enforcement'] == 'hard':
            return False, "BUDGET EXCEEDED - spawn blocked"
        else:
            return True, "WARNING: Over budget"

    if usage_ratio > budget['confirmation_threshold']:
        # Requires user confirmation (via I/O Tower)
        return 'confirm', f"At {usage_ratio*100:.1f}% of budget"

    if usage_ratio > budget['warning_threshold']:
        # Display warning but continue
        return True, f"WARNING: At {usage_ratio*100:.1f}% of budget"

    return True, None
```

### Pre-Spawn Hook

Before spawning ANY agent, MC must:

```python
# In MC spawn protocol
allowed, message = check_budget_before_spawn(agent_type, model)

if allowed == False:
    display_budget_exceeded()
    return  # Block spawn

if allowed == 'confirm':
    response = io_tower_confirm(message)
    if not response:
        return  # User declined

if message:
    display_budget_warning(message)

# Proceed with spawn
record_spawn_cost(agent_type, model, prompt_chars)
```

### Post-Spawn Hook

After spawn completes, record actual usage:

```python
def record_spawn_completion(spawn_id, output_chars):
    """Update estimates with actual output size."""
    budget = load_budget_config()
    spawn = find_spawn(budget, spawn_id)

    spawn['actual_output_chars'] = output_chars
    spawn['est_output_tokens'] = output_chars / 4
    spawn['est_cost'] = calculate_cost(spawn)

    budget['current_session']['estimated_cost'] = sum_spawn_costs(budget)
    save_budget_config(budget)
```

## TYPICAL SPAWN COSTS

**Reference costs per spawn (estimates):**

| Agent | Opus | Sonnet | Haiku |
|-------|------|--------|-------|
| Planner | ~$1.60 | ~$0.96 | - |
| Executor | ~$2.10 | ~$1.26 | - |
| Recognizer | ~$1.45 | ~$0.87 | ~$0.29 |
| Visual Inspector | ~$1.45 | ~$0.87 | ~$0.29 |
| E2E Exerciser | ~$1.45 | ~$0.87 | ~$0.29 |
| Persona Simulator | ~$1.60 | ~$0.96 | ~$0.48 |
| Refinement Synth | ~$1.45 | ~$0.87 | ~$0.44 |

**Typical project costs:**

| Project Type | Est. Spawns | Quality | Balanced | Budget |
|--------------|-------------|---------|----------|--------|
| Quick fix | 1-2 | $2-4 | $1-2 | $0.50-1 |
| Small feature | 3-5 | $5-10 | $3-6 | $1-3 |
| Medium project | 8-12 | $15-25 | $9-15 | $4-8 |
| Large project | 15-25 | $30-50 | $18-30 | $8-15 |

## RULES

1. **Budget check before EVERY spawn** - No exceptions
2. **Estimations, not actuals** - We estimate from prompt/response sizes
3. **Hard stops are hard** - When enforcement=hard and budget exceeded, work stops
4. **Session-based** - Each `/grid` invocation is a session
5. **History persists** - Usage history survives across sessions
6. **Model tier affects cost** - Budget tier can reduce costs 50-70%
7. **Warn early** - 75% threshold gives user time to react

## WORKFLOW INTEGRATION

### With `/grid:model`

```
# Check current costs
/grid:budget

# If over budget, switch to cheaper tier
/grid:model budget

# Continue work at lower cost
/grid:estimate  # Recalculates with new tier
```

### With Planning

During planning, MC spawns Accountant to estimate total cluster cost:

```
CLUSTER: Auth System (3 blocks)

Estimated Cost: ~$14.86 (quality tier)
Current Budget: $50.00
Budget after: ~$35.14

Proceed? [Y/n]
```

### With Refinement Swarm

Refinement phase can be expensive (4-6 spawns). Budget check happens before:

```
REFINEMENT SWARM
================

This will spawn:
  - Visual Inspector (sonnet)     ~$0.87
  - E2E Exerciser (sonnet)        ~$0.87
  - 3x Persona Simulator (sonnet) ~$2.88
  - Refinement Synth (sonnet)     ~$0.87

Total: ~$5.49

Budget remaining: $12.53
After refinement: ~$7.04

Proceed? [Y/n]
```

End of Line.
