# /grid:init - Initialize Grid State

---
name: grid:init
description: Initialize Grid state for new mission
disable-model-invocation: true
argument-hint: "[--force]"
allowed-tools:
  - Read
  - Write
  - Bash
  - Glob
---

Initialize the `.grid/` directory structure for the current project. This creates all directories and files needed for state persistence, enabling mission recovery via `/grid:resume`.

## USAGE

```
/grid:init              # Initialize in current directory
/grid:init --force      # Reinitialize (preserves existing state)
```

## DIRECTORY STRUCTURE

Create the complete `.grid/` directory structure:

```bash
mkdir -p .grid/plans .grid/phases .grid/discs .grid/debug .grid/daemon .grid/refinement/screenshots .grid/refinement/e2e .grid/refinement/personas
```

### Directory Purposes

| Directory | Purpose | Persistence |
|-----------|---------|-------------|
| `.grid/` | Root state directory | Session-scoped |
| `.grid/plans/` | Execution plans (PLAN.md files) | Mission-scoped |
| `.grid/phases/` | Execution artifacts (SUMMARY.md files) | Mission-scoped |
| `.grid/discs/` | Identity Discs for Programs | Session-scoped |
| `.grid/debug/` | Debug session state | Survives /clear |
| `.grid/daemon/` | Daemon execution state | Mission-scoped |
| `.grid/refinement/` | Refinement swarm outputs | Mission-scoped |

## CORE STATE FILES

### STATE.md (Central State)

The primary state file - always read first on resume:

```markdown
---
# Identity
cluster: null
session_id: "{timestamp}-init"
status: initialized  # initialized | active | checkpoint | interrupted | completed | failed

# Position tracking
position:
  phase: 0
  phase_total: 0
  phase_name: null
  block: 0
  block_total: 0
  wave: 0
  wave_total: 0

# Progress
progress_percent: 0
energy_remaining: 10000

# Execution mode
mode: autopilot  # autopilot | guided | hands_on

# Timestamps
created_at: "{ISO timestamp}"
updated_at: "{ISO timestamp}"
---

# Grid State

## Current Position
- Active Cluster: none
- Active Block: none
- Status: Initialized

Progress: [----------] 0%

## Session Info
- Initialized: {current date}
- Session ID: {session_id}
- Mode: AUTOPILOT

## Last Activity
Initialized Grid state directory.

## Notes
Ready for /grid to begin a mission.
```

### WARMTH.md (Institutional Knowledge)

Template for accumulated knowledge:

```markdown
---
cluster: null
accumulated_from: []
last_updated: "{ISO timestamp}"
---

# Grid Warmth

Accumulated knowledge from Programs. Survives session death.

## Codebase Patterns
(Patterns discovered about the codebase)

## Gotchas
(Traps and pitfalls to avoid)

## User Preferences
(Inferred user preferences)

## Decisions Made
(Key decisions and their rationale)

## Almost Did
(Approaches considered but rejected)

## Fragile Areas
(Code that breaks easily)
```

### SCRATCHPAD.md (Live Discoveries)

Template for real-time discoveries during execution:

```markdown
---
updated: "{ISO timestamp}"
active_programs: []
---

# Grid Scratchpad

Live discoveries during execution. Programs write here when they learn something others need to know.

## Format

Each entry must follow:
```
### {program-id} | {ISO-timestamp} | {category}

**Finding:** {one clear sentence}
**Impact:** {who needs to know}
**Action:** [INFORM_ONLY | REQUIRES_CHANGE | BLOCKER]
**Details:** {additional context}
```

Categories: PATTERN | DECISION | BLOCKER | PROGRESS | CORRECTION

---

(Entries will appear below)
```

### DECISIONS.md (User Decisions Log)

Template for tracking user decisions:

```markdown
---
cluster: null
decision_count: 0
last_updated: "{ISO timestamp}"
---

# Grid Decisions Log

User decisions made via I/O Tower. Referenced during resume to maintain consistency.

---

(Decisions will appear below in format:)

## Decision {N}: {ISO timestamp}
**Question:** {what was asked}
**Options Presented:**
  - {option_a}: "{description}"
  - {option_b}: "{description}"
**User Choice:** {choice}
**Rationale:** "{user's reason if given}"
**Affects:** {blocks/features affected}
```

### BLOCKERS.md (Blocker Tracking)

Template for tracking blockers:

```markdown
---
cluster: null
active_blockers: 0
resolved_blockers: 0
last_updated: "{ISO timestamp}"
---

# Grid Blockers

Issues that blocked progress. Used for resume and reporting.

---

(Blockers will appear below in format:)

## Blocker {N}: {ACTIVE | RESOLVED}
**Block:** {block_id}
**Thread:** {thread_id}
**Type:** {dependency_missing | human_action_required | external_service | bug}
**Description:** {what's blocking}
**Resolution:** {how it was resolved, if resolved}
**Created At:** {timestamp}
**Resolved At:** {timestamp, if resolved}
```

### config.json (Grid Configuration)

Configuration for Grid behavior:

```json
{
  "model_tier": "quality",
  "model_tier_options": ["quality", "balanced", "budget"],
  "auto_verify": true,
  "scratchpad_heartbeat_minutes": 5,
  "stale_threshold_minutes": 10,
  "max_retry_attempts": 3,
  "created_at": "{ISO timestamp}"
}
```

### budget.json (Budget Tracking)

Initialize from template if not exists:

```bash
if [ ! -f .grid/budget.json ]; then
  cp .grid/budget.template.json .grid/budget.json
fi
```

Budget configuration for cost tracking (see `/grid:budget` for details):

```json
{
  "budget_limit": null,
  "currency": "USD",
  "enforcement": "hard",
  "warning_threshold": 0.75,
  "confirmation_threshold": 0.90,
  "current_session": {
    "estimated_cost": 0,
    "spawns": []
  },
  "history": {
    "total_cost": 0,
    "total_spawns": 0
  }
}
```

## INITIALIZATION BEHAVIOR

### Step 1: Check Existing State

```python
if file_exists(".grid/STATE.md"):
    state = parse_yaml(read(".grid/STATE.md"))
    if state.get("status") not in ["completed", "failed", "initialized"]:
        # Active mission exists
        display("""
WARNING: Active Grid mission detected.

Cluster: {state['cluster']}
Status: {state['status']}
Progress: {state['progress_percent']}%

Use /grid:resume to continue, or /grid:init --force to reinitialize.
""")
        return
```

### Step 2: Create Directories

```bash
mkdir -p .grid/plans
mkdir -p .grid/phases
mkdir -p .grid/discs
mkdir -p .grid/debug
mkdir -p .grid/daemon
mkdir -p .grid/refinement/screenshots
mkdir -p .grid/refinement/e2e
mkdir -p .grid/refinement/personas
```

### Step 3: Create State Files

Create each core state file with its template.

### Step 4: Create .gitignore Entry

If `.gitignore` exists, suggest adding `.grid/`:

```python
if file_exists(".gitignore"):
    gitignore = read(".gitignore")
    if ".grid/" not in gitignore:
        suggest("""
Consider adding to .gitignore:

# Grid state (local only)
.grid/
""")
```

### Step 5: Display Confirmation

```
GRID INITIALIZED
================

Directory structure created:

.grid/
├── STATE.md              Central state file (read first on resume)
├── WARMTH.md             Institutional knowledge
├── SCRATCHPAD.md         Live discoveries during execution
├── DECISIONS.md          User decisions log
├── BLOCKERS.md           Blocker tracking
├── config.json           Grid configuration
├── budget.json           Budget tracking (cost management)
│
├── plans/                Execution plans
├── phases/               Execution artifacts (SUMMARY.md files)
├── discs/                Identity Discs for Programs
├── debug/                Debug session state
├── daemon/               Daemon execution state (long-running tasks)
└── refinement/           Refinement swarm outputs
    ├── screenshots/
    ├── e2e/
    └── personas/

PERSISTENCE ENABLED
-------------------
Your mission state will survive session death.
Use /grid:resume to continue an interrupted mission.

Ready to build. Run /grid to begin.

End of Line.
```

## FORCE REINITIALIZATION

With `--force` flag:

1. Archive existing state (if active):
   ```bash
   mv .grid/STATE.md .grid/STATE.md.{timestamp}.bak
   mv .grid/WARMTH.md .grid/WARMTH.md.{timestamp}.bak
   ```

2. Preserve completed work:
   - Keep `.grid/phases/` (SUMMARY.md files)
   - Keep `.grid/plans/` (for reference)

3. Create fresh state files

4. Display:
   ```
   GRID REINITIALIZED
   ==================

   Archived:
   - STATE.md -> STATE.md.{timestamp}.bak
   - WARMTH.md -> WARMTH.md.{timestamp}.bak

   Preserved:
   - phases/ (completed work)
   - plans/ (execution plans)

   Fresh state created. Ready to build.

   End of Line.
   ```

## STATE FILE SCHEMAS

### STATE.md YAML Frontmatter Schema

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `cluster` | string | Yes | Cluster name |
| `session_id` | string | Yes | Unique session identifier |
| `status` | enum | Yes | initialized/active/checkpoint/interrupted/completed/failed |
| `position.phase` | integer | Yes | Current phase number |
| `position.phase_total` | integer | Yes | Total phases |
| `position.phase_name` | string | No | Phase name |
| `position.block` | integer | Yes | Current block number |
| `position.block_total` | integer | Yes | Total blocks |
| `position.wave` | integer | Yes | Current wave number |
| `position.wave_total` | integer | Yes | Total waves |
| `progress_percent` | integer | Yes | 0-100 |
| `energy_remaining` | integer | Yes | Energy budget |
| `mode` | enum | Yes | autopilot/guided/hands_on |
| `created_at` | ISO8601 | Yes | Creation timestamp |
| `updated_at` | ISO8601 | Yes | Last update timestamp |

### config.json Schema

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `model_tier` | enum | "quality" | quality/balanced/budget |
| `auto_verify` | boolean | true | Auto-spawn Recognizer |
| `scratchpad_heartbeat_minutes` | integer | 5 | Expected write frequency |
| `stale_threshold_minutes` | integer | 10 | When to consider session dead |
| `max_retry_attempts` | integer | 3 | Max retries on failure |

## PERSISTENCE GUARANTEES

After initialization, the Grid guarantees:

1. **State survives session death** - All progress recorded in files
2. **Warmth accumulates** - Knowledge transfers across Programs
3. **Decisions persist** - User choices never need repeating
4. **Commits are verified** - Git hashes enable state validation
5. **Plans are preserved** - Full execution plans available for resume

## RELATED COMMANDS

- `/grid` - Begin a mission (auto-initializes if needed)
- `/grid:resume` - Resume an interrupted mission
- `/grid:status` - Display current Grid state
- `/grid:model` - Configure model tier

End of Line.
