**RESUME INTERRUPTED RUN**

Resume a previously interrupted or paused infinite loop run using its run ID.

---

**USAGE:**
```
/resume <run_id>
```

**PARAMETERS:**
- `run_id`: The run identifier (format: run_YYYYMMDD_HHMMSS)

**EXAMPLES:**
```bash
# Resume specific run
/resume run_20250310_143022

# Find available runs first with /status, then resume
/status
/resume run_20250310_143022
```

---

**EXECUTION STEPS:**

**Step 1: Locate Run State**

```bash
state_file=".claude/state/${run_id}.json"

if [ ! -f "$state_file" ]; then
    echo "ERROR: Run state file not found: $state_file"
    echo ""
    echo "Available runs:"
    ls -1 .claude/state/run_*.json | xargs -n1 basename
    exit 1
fi
```

**Step 2: Load and Validate State**

```python
import json

# Load state
with open(state_file, 'r') as f:
    state = json.load(f)

# Extract parameters
spec_path = state["spec_path"]
output_dir = state["output_dir"]
total_count = state["total_count"]
url_strategy_path = state.get("url_strategy_path", None)

# Validate state integrity
print(f"Run ID: {state['run_id']}")
print(f"Status: {state['status']}")
print(f"Progress: {state['completed_iterations']} of {total_count}")
print(f"Created: {state['created_at']}")
print(f"Last Updated: {state['updated_at']}")
```

**Step 3: Pre-Resume Validation**

Apply self-consistency checks before resuming:

```python
# Validation 1: File existence
missing_files = []
for iteration in state["iterations"]:
    if iteration["status"] == "completed":
        if not os.path.exists(iteration["output_file"]):
            missing_files.append(iteration["output_file"])

# Validation 2: Count consistency
file_count = len(glob.glob(f"{output_dir}/*"))
completed_count = len([i for i in state["iterations"] if i["status"] == "completed"])

# Validation 3: State schema
required_fields = ["run_id", "spec_path", "output_dir", "status", "iterations", "used_urls"]
schema_valid = all(field in state for field in required_fields)

# Compute consistency score
validations = [
    len(missing_files) == 0,
    file_count >= completed_count,
    schema_valid
]
consistency_score = sum(validations) / len(validations)

if consistency_score < 0.8:
    print(f"WARNING: State consistency score: {consistency_score:.2f}")
    print(f"Issues detected:")
    if missing_files:
        print(f"  - Missing files: {missing_files}")
    if file_count < completed_count:
        print(f"  - File count mismatch: {file_count} vs {completed_count}")
    if not schema_valid:
        print(f"  - Invalid state schema")

    response = input("Continue anyway? (yes/no): ")
    if response.lower() != "yes":
        exit(1)
```

**Step 4: Invoke Infinite Loop with Resume**

```bash
# Construct resume command
if url_strategy_path:
    command = f"/infinite-stateful {spec_path} {output_dir} {total_count} {url_strategy_path} {run_id}"
else:
    command = f"/infinite-stateful {spec_path} {output_dir} {total_count} - {run_id}"

print(f"Resuming with: {command}")
print("")

# Execute
{command}
```

**Step 5: Post-Resume Verification**

After resume completes:

```python
# Reload state
with open(state_file, 'r') as f:
    updated_state = json.load(f)

# Compare progress
old_progress = state["completed_iterations"]
new_progress = updated_state["completed_iterations"]
iterations_added = new_progress - old_progress

print(f"Resume completed: {iterations_added} new iterations generated")
print(f"Total progress: {new_progress} of {total_count}")
```

---

**SAFETY FEATURES:**

**State Validation:**
- Verify state file exists before resume
- Check state consistency before execution
- Warn on inconsistencies with option to abort

**Non-Destructive:**
- Never deletes or overwrites completed iterations
- Preserves all existing state data
- Adds only new iterations

**Error Handling:**
- Clear error messages for missing run IDs
- List available runs if ID not found
- Validate state schema before proceeding

**Consistency Checks:**
- File existence validation
- Count matching verification
- Schema completeness check
- Self-consistency scoring

---

**COMMON SCENARIOS:**

**Scenario 1: Context Limit Reached**
```
Original: /infinite-stateful specs/example.md out infinite
# ... generates 50 iterations, hits context limit
# State saved at: .claude/state/run_20250310_143022.json

Resume: /resume run_20250310_143022
# Continues from iteration 51
```

**Scenario 2: Interrupted by Error**
```
Original: /infinite-stateful specs/example.md out 100
# ... completes 73 iterations, error occurs
# State saved at: .claude/state/run_20250310_150000.json

Resume: /resume run_20250310_150000
# Continues from iteration 74, completes remaining 27
```

**Scenario 3: Manual Pause**
```
Original: /infinite-stateful specs/example.md out infinite
# ... generates 20 iterations, user stops
# State saved at: .claude/state/run_20250310_160000.json

Later: /resume run_20250310_160000
# Continues from iteration 21
```

---

**TROUBLESHOOTING:**

**Problem: State file not found**
```
Solution: Use /status to list available runs
```

**Problem: Low consistency score**
```
Solution:
1. Use /status <run_id> to inspect state
2. Manually verify output files exist
3. Use /reset-state <run_id> if corrupted
```

**Problem: Output directory modified**
```
Solution:
1. State tracks expected files
2. Resume will detect mismatches
3. Choose to continue or reset
```

**Problem: Spec file changed**
```
Solution:
Resume uses spec_path from state
If spec changed, consider new run instead
```

---

**NOTES:**

- Resume is safe and non-destructive
- All validation checks use self-consistency principle
- State is single source of truth
- Original run parameters are preserved
- Can resume multiple times if needed
