# Thread Management — MORPH-SPEC v3.0

Thread management is the v3.0 system for coordinating multi-agent execution within a single feature. Threads allow parallel, sequential, and hybrid agent workflows with full lifecycle tracking.

---

## Thread Types

| Thread | Code | Purpose | Auto-kill? |
|--------|------|---------|------------|
| **Base Thread** | B | Single agent, sequential implementation | No |
| **Parallel Thread** | P | Isolated domain worker in a parallel squad | No |
| **Fusion Thread** | F | One of N agents solving the same problem | No |
| **Long-Running** | L | Persistent background agent with stop hooks | Yes (on stop hook) |
| **Zero-Touch** | Z | Autonomous agent with auto-approval (requires max trust) | No |

### Choosing a Thread Type

```
Is this a single, sequential implementation?
  └─ YES → B-Thread (Base)

Do you want N agents working on different domains simultaneously?
  └─ YES → P-Thread (Parallel) per domain

Do you want N agents solving the SAME problem (pick best result)?
  └─ YES → F-Thread (Fusion)

Will the agent run for >30 minutes or need periodic check-ins?
  └─ YES → L-Thread (Long-Running)

Is trust level "maximum" (>95% checkpoint pass rate)?
  └─ YES → Z-Thread (Zero-Touch) eligible
```

---

## Thread Lifecycle

```
pending → running → completed
                 └→ failed
                 └→ killed
```

Each thread stores its state in `.morph/state.json` under `threads`:

```json
{
  "threads": {
    "thr_abc12345": {
      "id": "thr_abc12345",
      "type": "parallel",
      "feature": "user-auth",
      "agent": "dotnet-senior",
      "status": "running",
      "startedAt": "2026-02-19T10:00:00Z",
      "completedAt": null,
      "metrics": {
        "tasksCompleted": 3,
        "filesCreated": 5,
        "filesModified": 2,
        "checkpointsPassed": 1,
        "checkpointsFailed": 0
      }
    }
  }
}
```

---

## CLI Reference

### List threads

```bash
morph-spec threads list
morph-spec threads list --feature user-auth
morph-spec threads list --status running
morph-spec threads list --type parallel
```

### Thread status

```bash
morph-spec threads status thr_abc12345
```

### Kill a thread

```bash
morph-spec threads kill thr_abc12345
```

### Analytics

```bash
morph-spec threads analytics --feature user-auth
```

### Wait for completion

```bash
# Wait for ALL threads in a feature
morph-spec threads wait-all user-auth --timeout 60

# Wait for ANY thread to complete
morph-spec threads wait-any user-auth --timeout 30
```

---

## P-Thread Isolation Rules

Parallel threads (P-Threads) MUST follow strict isolation:

| Rule | Description |
|------|-------------|
| **File ownership** | Each P-Thread writes ONLY to its assigned file set |
| **Read-only shared** | Shared files (spec.md, contracts, standards) are READ-ONLY |
| **No cross-writes** | Never write to another thread's files |
| **Report on done** | Submit PARALLEL WORKER REPORT when complete |
| **No external calls** | Don't spawn additional threads |

### P-Thread Report Format

```
## PARALLEL WORKER REPORT

**Thread ID:** {id}
**Status:** completed | failed | blocked

**Files Created:**
- path/to/file1.cs
- path/to/file2.cs

**Tasks Completed:** T001, T002, T003

**Blockers (if any):** None

**Notes:** Any important implementation decisions
```

---

## L-Thread Stop Hooks

Long-running threads respond to stop hooks. Configure in `.claude/settings.local.json`:

```json
{
  "hooks": {
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "node framework/hooks/agent-teams/validate-and-continue.js {feature}"
          }
        ]
      }
    ]
  }
}
```

Stop hooks run every N seconds (configurable in `zero-touch.json`):

```json
{
  "monitoring": {
    "stopHooks": {
      "enabled": true,
      "interval": 30,
      "hooks": ["validate-and-continue", "validate-checkpoints"]
    }
  }
}
```

---

## Thread Metrics Tracking

Each feature tracks aggregate thread metrics in `state.json`:

```json
{
  "features": {
    "user-auth": {
      "threadMetrics": {
        "totalThreads": 3,
        "completedThreads": 2,
        "failedThreads": 0,
        "parallelBatches": 1
      }
    }
  }
}
```

Access via:

```bash
morph-spec analytics feature user-auth
```

---

## Decision Tree: When to Use Threads

```
Feature complexity?
  SIMPLE (1-5 files) → B-Thread only, no parallelization
  MEDIUM (6-15 files) → Consider P-Threads by domain
  HIGH (>15 files) → P-Threads mandatory for speed

Multiple independent domains?
  YES → Spawn P-Thread per domain (backend, frontend, infra)
  NO  → Single B-Thread is fine

Need best-quality output from N attempts?
  YES → F-Thread (Fusion) with aggregation

Long implementation (>30 mins estimated)?
  YES → L-Thread with stop hooks for periodic validation

Trust level maximum + fully automated pipeline?
  YES → Z-Thread (check with: morph-spec trust status)
```

---

## Related

- [Parallel Execution](PARALLEL-EXECUTION.md) — Squad templates and P-Thread coordination
- [Context Optimization](CONTEXT-OPTIMIZATION.md) — Token efficiency during thread execution
- [Migration Guide](MIGRATION-GUIDE.md) — Upgrading state.json to v3.0 thread schema
