**SHOW RUN STATUS**

Display detailed status information for infinite loop runs, including progress, state consistency, and resumability.

---

**USAGE:**
```
/status [run_id]
```

**PARAMETERS:**
- `run_id`: (Optional) Specific run to inspect. If omitted, shows all runs.

**EXAMPLES:**
```bash
# Show all runs
/status

# Show specific run details
/status run_20250310_143022

# Check consistency of specific run
/status run_20250310_143022
```

---

**EXECUTION:**

**Mode 1: List All Runs** (no run_id provided)

```bash
state_dir=".claude/state"

if [ ! -d "$state_dir" ]; then
    echo "No state directory found. No runs have been executed yet."
    exit 0
fi

echo "=== INFINITE LOOP RUNS ==="
echo ""

for state_file in "$state_dir"/run_*.json; do
    if [ -f "$state_file" ]; then
        run_id=$(basename "$state_file" .json)

        # Parse state file
        status=$(jq -r '.status' "$state_file")
        completed=$(jq -r '.completed_iterations' "$state_file")
        total=$(jq -r '.total_count' "$state_file")
        spec=$(jq -r '.spec_path' "$state_file")
        created=$(jq -r '.created_at' "$state_file")
        updated=$(jq -r '.updated_at' "$state_file")

        # Display summary
        echo "Run ID: $run_id"
        echo "  Status: $status"
        echo "  Progress: $completed of $total"
        echo "  Spec: $spec"
        echo "  Created: $created"
        echo "  Updated: $updated"
        echo ""
    fi
done

echo "Use '/status <run_id>' for detailed information"
```

**Mode 2: Detailed Run Status** (run_id provided)

```python
import json
import os
from datetime import datetime
from glob import glob

state_file = f".claude/state/{run_id}.json"

if not os.path.exists(state_file):
    print(f"ERROR: Run not found: {run_id}")
    print("")
    print("Available runs:")
    for f in glob(".claude/state/run_*.json"):
        print(f"  - {os.path.basename(f).replace('.json', '')}")
    exit(1)

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

print("=" * 60)
print("INFINITE LOOP RUN STATUS")
print("=" * 60)
print("")

# Basic Information
print("RUN INFORMATION:")
print(f"  Run ID: {state['run_id']}")
print(f"  Status: {state['status']}")
print(f"  Specification: {state['spec_path']}")
print(f"  Output Directory: {state['output_dir']}")
print(f"  Total Count: {state['total_count']}")
if state.get('url_strategy_path'):
    print(f"  URL Strategy: {state['url_strategy_path']}")
print("")

# Progress
print("PROGRESS:")
print(f"  Completed Iterations: {state['completed_iterations']}")
print(f"  Failed Iterations: {state.get('failed_iterations', 0)}")
if state['total_count'] == 'infinite':
    print(f"  Progress: Infinite mode - {state['completed_iterations']} iterations so far")
else:
    progress_pct = (state['completed_iterations'] / int(state['total_count'])) * 100
    print(f"  Progress: {progress_pct:.1f}%")
print("")

# Timing
print("TIMING:")
print(f"  Created: {state['created_at']}")
print(f"  Last Updated: {state['updated_at']}")
created_dt = datetime.fromisoformat(state['created_at'].replace('Z', '+00:00'))
updated_dt = datetime.fromisoformat(state['updated_at'].replace('Z', '+00:00'))
duration = updated_dt - created_dt
print(f"  Duration: {duration}")
print("")

# State Consistency Validation
print("STATE CONSISTENCY VALIDATION:")
print("")

# Validation 1: File count
output_dir = state['output_dir']
file_count = len(glob(f"{output_dir}/*")) if os.path.exists(output_dir) else 0
expected_count = state['completed_iterations']
file_check = file_count >= expected_count
print(f"  File Count Check: {'PASS' if file_check else 'FAIL'}")
print(f"    Expected: >={expected_count}, Actual: {file_count}")

# Validation 2: Iteration records
iteration_count = len([i for i in state['iterations'] if i['status'] == 'completed'])
iteration_check = iteration_count == expected_count
print(f"  Iteration Records Check: {'PASS' if iteration_check else 'FAIL'}")
print(f"    Expected: {expected_count}, Actual: {iteration_count}")

# Validation 3: URL uniqueness
total_urls = len(state['used_urls'])
unique_urls = len(set(state['used_urls']))
url_check = total_urls == unique_urls
print(f"  URL Uniqueness Check: {'PASS' if url_check else 'FAIL'}")
print(f"    Total: {total_urls}, Unique: {unique_urls}")

# Validation 4: 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'])
existence_check = len(missing_files) == 0
print(f"  File Existence Check: {'PASS' if existence_check else 'FAIL'}")
if missing_files:
    print(f"    Missing: {missing_files[:3]}{'...' if len(missing_files) > 3 else ''}")

# Self-consistency score (majority voting)
validations = [file_check, iteration_check, url_check, existence_check]
consistency_score = sum(validations) / len(validations)
print("")
print(f"  Consistency Score: {consistency_score:.2f} ({consistency_score * 100:.0f}%)")

if consistency_score >= 0.8:
    print(f"  Status: CONSISTENT - State is reliable")
elif consistency_score >= 0.5:
    print(f"  Status: WARNING - Some inconsistencies detected")
else:
    print(f"  Status: CORRUPTED - State may be unreliable")

print("")

# Recent Iterations
print("RECENT ITERATIONS:")
recent = sorted(state['iterations'], key=lambda x: x.get('completed_at', ''), reverse=True)[:5]
for iteration in recent:
    print(f"  Iteration {iteration['number']}: {iteration['status']}")
    print(f"    File: {iteration['output_file']}")
    if iteration.get('web_url'):
        print(f"    URL: {iteration['web_url'][:60]}...")
    if iteration.get('completed_at'):
        print(f"    Completed: {iteration['completed_at']}")
    print("")

# Resumability
print("RESUMABILITY:")
if state['status'] in ['in_progress', 'paused']:
    print(f"  Can Resume: YES")
    print(f"  Next Iteration: {state['completed_iterations'] + 1}")
    print(f"  Resume Command: /resume {state['run_id']}")
elif state['status'] == 'completed':
    print(f"  Can Resume: NO (run completed)")
else:
    print(f"  Can Resume: UNKNOWN (status: {state['status']})")
print("")

# State File Info
print("STATE FILE:")
print(f"  Path: {state_file}")
file_size = os.path.getsize(state_file)
print(f"  Size: {file_size} bytes ({file_size / 1024:.1f} KB)")
print("")

# Used URLs Summary
if state.get('used_urls'):
    print("URL USAGE:")
    print(f"  Total URLs Used: {len(state['used_urls'])}")
    print(f"  Unique URLs: {len(set(state['used_urls']))}")
    print(f"  Sample URLs:")
    for url in state['used_urls'][:3]:
        print(f"    - {url}")
    if len(state['used_urls']) > 3:
        print(f"    ... and {len(state['used_urls']) - 3} more")
    print("")

# Validation History
if state.get('validation'):
    print("VALIDATION HISTORY:")
    print(f"  Last Check: {state['validation'].get('last_check', 'Never')}")
    print(f"  Last Score: {state['validation'].get('consistency_score', 'N/A')}")
    if state['validation'].get('issues'):
        print(f"  Issues: {len(state['validation']['issues'])}")
    print("")

print("=" * 60)
```

---

**OUTPUT INTERPRETATION:**

**Consistency Score Meanings:**
- `1.00 (100%)`: Perfect consistency, all checks pass
- `0.75-0.99`: Good consistency, minor issues
- `0.50-0.74`: Moderate issues, review recommended
- `0.00-0.49`: Significant problems, state may be corrupted

**Status Values:**
- `in_progress`: Currently running
- `paused`: Stopped but can resume
- `completed`: Finished successfully
- `failed`: Encountered unrecoverable error

**Check Interpretations:**

**File Count Check:**
- Verifies output directory has expected number of files
- FAIL may indicate manual deletion or partial cleanup

**Iteration Records Check:**
- Verifies state tracking matches completion count
- FAIL indicates state corruption

**URL Uniqueness Check:**
- Ensures no duplicate URLs used
- FAIL means deduplication failed

**File Existence Check:**
- Verifies all tracked files still exist
- FAIL means files were deleted after creation

---

**ACTIONS BASED ON STATUS:**

**If Consistency Score >= 0.8:**
```
State is reliable. Safe to resume or analyze.
```

**If Consistency Score 0.5-0.79:**
```
Review specific failed checks.
Consider running: /reset-state <run_id> --verify
Manual inspection recommended.
```

**If Consistency Score < 0.5:**
```
State likely corrupted.
Options:
1. /reset-state <run_id> --rebuild
2. Start new run
3. Manual state repair
```

---

**EXAMPLES:**

**Example 1: Healthy Run**
```
Consistency Score: 1.00 (100%)
All checks: PASS
Can Resume: YES
Action: Safe to resume with /resume run_20250310_143022
```

**Example 2: Missing Files**
```
Consistency Score: 0.75 (75%)
File Existence Check: FAIL (3 missing files)
Other checks: PASS
Action: Regenerate missing files or accept loss and continue
```

**Example 3: Corrupted State**
```
Consistency Score: 0.25 (25%)
Multiple checks: FAIL
Action: Reset state or start new run
```

---

**SELF-CONSISTENCY VALIDATION:**

This command applies the self-consistency principle by:
1. Sampling multiple validation approaches (4 different checks)
2. Computing consistency score via majority voting
3. Providing high-confidence status based on consensus
4. Highlighting discrepancies for user review

Multiple independent validation methods ensure reliable state assessment even if one method has errors.
