# Grid JSON Schemas

> Structured schemas for Grid plans, state, budget tracking, and review output.

This document describes the JSON schemas used by The Grid for structured, validated output. These schemas enable reliable data exchange between Grid components, headless CLI invocations, and CI/CD integrations.

## Overview

| Schema | Purpose | Location |
|--------|---------|----------|
| `plan.schema.json` | Mission execution plans | `/schemas/plan.schema.json` |
| `state.schema.json` | Mission progress tracking | `/schemas/state.schema.json` |
| `budget.schema.json` | Cost tracking | `/schemas/budget.schema.json` |
| `review.schema.json` | Code review output | `/schemas/review.schema.json` |

All schemas follow [JSON Schema Draft-07](http://json-schema.org/draft-07/schema#).

---

## Plan Schema

**File:** `schemas/plan.schema.json`

Defines the structure of Grid execution plans with missions, phases, blocks, and threads.

### Structure

```
Plan
├── mission (string, required)
├── complexity (enum: trivial|simple|medium|complex|massive)
├── estimatedAgents (integer)
├── estimatedDuration (string)
├── tags (array of strings)
├── phases (array, required)
│   └── Phase
│       ├── id (string, pattern: "XX")
│       ├── name (string, required)
│       ├── description (string)
│       └── blocks (array, required)
│           └── Block
│               ├── id (string, pattern: "XX-XX")
│               ├── name (string, required)
│               ├── wave (integer, required)
│               ├── checkpoint (enum: human-verify|decision|human-action)
│               └── threads (array, required)
│                   └── Thread
│                       ├── id (string, pattern: "XX-XX-XX")
│                       ├── task (string, required)
│                       ├── agent (enum, default: executor)
│                       ├── files (array, required)
│                       ├── dependencies (array)
│                       └── verification (string)
└── metadata (object)
```

### Usage with Headless CLI

Generate a plan with validated JSON output:

```bash
claude -p "Create an execution plan for adding user authentication" \
  --allowedTools "Read,Glob,Grep" \
  --output-format json \
  --json-schema "$(cat schemas/plan.schema.json)"
```

### Example Output

```json
{
  "mission": "Add JWT authentication to the API",
  "complexity": "medium",
  "estimatedAgents": 3,
  "phases": [
    {
      "id": "01",
      "name": "Setup",
      "blocks": [
        {
          "id": "01-01",
          "name": "Install dependencies",
          "wave": 1,
          "threads": [
            {
              "id": "01-01-01",
              "task": "Add jose and bcrypt packages",
              "agent": "executor",
              "files": ["package.json", "package-lock.json"]
            }
          ]
        }
      ]
    }
  ]
}
```

---

## State Schema

**File:** `schemas/state.schema.json`

Tracks mission progress in `.grid/STATE.md` YAML frontmatter.

### Structure

```
State
├── mission (string, required)
├── cluster (string)
├── status (enum: planning|executing|verifying|checkpoint|paused|complete|failed)
├── phase (string, pattern: "XX")
├── block (string, pattern: "XX-XX")
├── wave (integer)
├── thread (string, pattern: "XX-XX-XX")
├── active_programs (integer)
├── completed_blocks (array)
├── completed_threads (array)
├── progress (object)
│   ├── phases_complete (integer)
│   ├── blocks_complete (integer)
│   ├── threads_complete (integer)
│   └── percentage (number)
├── checkpoint (object) - if status is "checkpoint"
│   ├── type (enum)
│   ├── reason (string)
│   └── awaiting (string)
├── started_at (datetime)
├── updated_at (datetime)
└── error (object) - if status is "failed"
```

### Status Values

| Status | Description |
|--------|-------------|
| `planning` | Planner is creating execution plan |
| `executing` | Programs are executing threads |
| `verifying` | Recognizer is verifying completed work |
| `checkpoint` | Paused awaiting human input |
| `paused` | Mission paused by user |
| `complete` | Mission successfully completed |
| `failed` | Mission failed with error |

### Example

```yaml
---
mission: "Add user authentication"
status: executing
phase: "01"
block: "01-02"
wave: 2
active_programs: 2
progress:
  phases_complete: 0
  phases_total: 2
  blocks_complete: 1
  blocks_total: 5
  percentage: 20
started_at: 2024-01-15T10:30:00Z
updated_at: 2024-01-15T10:45:00Z
---
```

---

## Budget Schema

**File:** `schemas/budget.schema.json`

Tracks spending in `.grid/budget.json` for cost management.

### Structure

```
Budget
├── limit (number) - 0 for unlimited
├── total_spent (number)
├── remaining (number)
├── currency (string, default: "USD")
├── mission (string)
├── spawns (array)
│   └── Spawn
│       ├── id (string)
│       ├── agent (string)
│       ├── model (string)
│       ├── cost (number)
│       ├── input_tokens (integer)
│       ├── output_tokens (integer)
│       ├── timestamp (datetime)
│       ├── block (string)
│       ├── thread (string)
│       └── status (enum: completed|failed|active)
├── summary (object)
│   ├── total_spawns (integer)
│   ├── average_cost_per_spawn (number)
│   ├── cost_by_agent (object)
│   └── cost_by_model (object)
└── alerts (object)
    ├── warn_at_percentage (number, default: 80)
    └── pause_at_percentage (number, default: 100)
```

### Usage

Set budget limit before mission:

```bash
# Set $10 budget limit
echo '{"limit": 10.00, "total_spent": 0}' > .grid/budget.json
```

Query budget status:

```bash
jq '{spent: .total_spent, remaining: .remaining, spawns: (.spawns | length)}' .grid/budget.json
```

### Example

```json
{
  "limit": 25.00,
  "total_spent": 8.47,
  "remaining": 16.53,
  "currency": "USD",
  "mission": "Refactor database layer",
  "spawns": [
    {
      "id": "spawn-001",
      "agent": "grid-executor",
      "model": "claude-sonnet-4-20250514",
      "cost": 2.35,
      "input_tokens": 45000,
      "output_tokens": 12000,
      "timestamp": "2024-01-15T10:32:00Z",
      "block": "01-01",
      "status": "completed"
    }
  ],
  "summary": {
    "total_spawns": 4,
    "average_cost_per_spawn": 2.12,
    "cost_by_agent": {
      "grid-executor": 6.47,
      "grid-recognizer": 2.00
    }
  }
}
```

---

## Review Schema

**File:** `schemas/review.schema.json`

Structured output for `/grid:review` and headless code reviews.

### Structure

```
Review
├── status (enum: pass|warn|fail, required)
├── approved (boolean)
├── summary (string, required)
├── issues (array, required)
│   └── Issue
│       ├── severity (enum: error|warning|info|suggestion)
│       ├── category (enum: security|bug|performance|...)
│       ├── file (string, required)
│       ├── line (integer)
│       ├── message (string, required)
│       ├── suggestion (string)
│       ├── code (string)
│       ├── suggestedCode (string)
│       ├── rule (string)
│       ├── cwe (string, pattern: "CWE-XXX")
│       ├── cvss (number, 0-10)
│       └── autoFixable (boolean)
├── metrics (object)
│   ├── files_reviewed (integer)
│   ├── issues_found (integer)
│   ├── security_issues (integer)
│   └── auto_fixable (integer)
├── coverage (object)
├── recommendations (array of strings)
└── metadata (object)
```

### Status Values

| Status | Exit Code | Meaning |
|--------|-----------|---------|
| `pass` | 0 | Approved, no issues |
| `warn` | 0 | Approved with warnings |
| `fail` | 1 | Changes requested |

### Usage in CI/CD

```bash
#!/bin/bash
# GitHub Actions / GitLab CI example

REVIEW=$(gh pr diff "$PR_NUMBER" | claude -p "Review this PR" \
  --allowedTools "Read,Grep,Glob" \
  --output-format json \
  --json-schema "$(cat schemas/review.schema.json)")

STATUS=$(echo "$REVIEW" | jq -r '.status')
ISSUES=$(echo "$REVIEW" | jq '.metrics.issues_found')

echo "Review status: $STATUS ($ISSUES issues)"

if [ "$STATUS" = "fail" ]; then
  echo "$REVIEW" | jq '.issues[] | "\(.severity): \(.file):\(.line) - \(.message)"'
  exit 1
fi
```

### Example Output

```json
{
  "status": "warn",
  "approved": true,
  "summary": "Generally good code with 2 minor issues and 1 security suggestion",
  "issues": [
    {
      "severity": "warning",
      "category": "security",
      "file": "src/api/auth.ts",
      "line": 45,
      "message": "Password comparison should use constant-time comparison",
      "suggestion": "Use crypto.timingSafeEqual() instead of === for password comparison",
      "cwe": "CWE-208",
      "autoFixable": true
    },
    {
      "severity": "info",
      "category": "style",
      "file": "src/utils/helpers.ts",
      "line": 12,
      "message": "Consider extracting magic number to named constant",
      "suggestion": "const MAX_RETRIES = 3;"
    }
  ],
  "metrics": {
    "files_reviewed": 5,
    "issues_found": 2,
    "security_issues": 1,
    "auto_fixable": 1
  },
  "recommendations": [
    "Consider adding integration tests for the new auth endpoints",
    "Update API documentation with new authentication flow"
  ]
}
```

---

## Schema Validation

### JavaScript/TypeScript

```typescript
import Ajv from 'ajv';
import planSchema from './schemas/plan.schema.json';

const ajv = new Ajv();
const validate = ajv.compile(planSchema);

const plan = JSON.parse(planOutput);
if (!validate(plan)) {
  console.error('Invalid plan:', validate.errors);
}
```

### Python

```python
import json
from jsonschema import validate, ValidationError

with open('schemas/plan.schema.json') as f:
    schema = json.load(f)

plan = json.loads(plan_output)
try:
    validate(instance=plan, schema=schema)
except ValidationError as e:
    print(f"Invalid plan: {e.message}")
```

### CLI with jq

```bash
# Basic validation using jq
jq -e '.mission and .phases' plan.json > /dev/null && echo "Valid" || echo "Invalid"
```

---

## Integration with Claude Code Headless

All schemas work with Claude Code's `--json-schema` flag:

```bash
# Generate validated plan
claude -p "Plan: add caching to API" \
  --output-format json \
  --json-schema "$(cat schemas/plan.schema.json)"

# Run review with structured output
gh pr diff 123 | claude -p "Review this PR" \
  --output-format json \
  --json-schema "$(cat schemas/review.schema.json)"
```

---

## Version History

| Version | Changes |
|---------|---------|
| 1.7.x | Initial schema definitions |

---

*End of Line.*
