# Execution Flow — MORPH-SPEC v3.0

This document describes the complete execution flow of a v3.0 feature from first request to sync, including all new v3.0 decision points and automation paths.

---

## High-Level Flow

```
User Request
    │
    ▼
┌─────────────┐
│  WORKFLOW   │  Auto-detect: fast-track / standard / full-morph
│  DETECTION  │  Command: morph-spec detect-workflow "<request>"
└──────┬──────┘
       │
       ▼
┌─────────────┐
│   CONTEXT   │  Load priming file (500 tokens vs 23K CLAUDE.md)
│   PRIMING   │  Command: morph-spec prime feature
└──────┬──────┘
       │
       ▼
┌─────────────┐
│   PROPOSAL  │  Agents detected, workflow confirmed
│    PHASE    │  Gate: proposal approval (auto if trust >= high)
└──────┬──────┘
       │
       ▼
┌─────────────┐
│   DESIGN    │  spec.md + contracts + decisions.md
│    PHASE    │  Gate: design approval (auto if trust >= medium)
└──────┬──────┘
       │
       ▼
┌─────────────┐
│   CLARIFY   │  Resolve ambiguities, update spec
│    PHASE    │  (no gate, auto-continues)
└──────┬──────┘
       │
       ▼
┌─────────────┐
│    TASKS    │  tasks.json: IDs, deps, phases
│    PHASE    │  Gate: tasks approval (auto if trust >= high)
└──────┬──────┘
       │
       ▼
┌─────────────────────────────────────────────────────────┐
│                   IMPLEMENT PHASE                       │
│                                                         │
│   ┌─────────────┐    ┌─────────────┐                   │
│   │  Single     │    │  Parallel   │                   │
│   │  B-Thread   │    │  P-Threads  │                   │
│   │  (simple)   │    │  (complex)  │                   │
│   └──────┬──────┘    └──────┬──────┘                   │
│          │                  │                           │
│          │         ┌────────┴────────┐                  │
│          │         │  Squad Planning │                  │
│          │         │ morph-spec      │                  │
│          │         │ parallel plan   │                  │
│          │         └────────┬────────┘                  │
│          │                  │                           │
│          │    ┌─────────────┼─────────────┐             │
│          │    ▼             ▼             ▼             │
│          │  Backend     Frontend       Infra            │
│          │  P-Thread    P-Thread     P-Thread           │
│          │    │             │             │             │
│          │    └─────────────┴─────────────┘             │
│          │                  │                           │
│          │              Coordinator                     │
│          │              Merges results                  │
│          │                  │                           │
│          └──────────────────┘                           │
│                             │                           │
│                    Every 3 tasks:                       │
│                   CHECKPOINT ──> Validators             │
│                             │    - architecture         │
│                             │    - security             │
│                             │    - packages             │
│                             │                           │
│                   Trust updates automatically           │
└─────────────────────────────┬───────────────────────────┘
                              │
                              ▼
                      ┌─────────────┐
                      │    SYNC     │  Recap + decisions archive
                      │    PHASE    │
                      └──────┬──────┘
                             │
                             ▼
                      ┌─────────────┐
                      │  ARCHIVED   │  Feature complete
                      └─────────────┘
```

---

## v3.0 Decision Points

### 1. Workflow Detection

```
morph-spec detect-workflow "<request>"
   │
   ├─ fast-track  → 2 phases (skip most)
   ├─ standard    → 4 phases (skip UIUX, CLARIFY, SYNC)
   ├─ full-morph  → ALL phases
   ├─ design-impl → prototype-focused
   └─ ui-refresh  → visual-only
```

### 2. Trust-Based Auto-Approval

```
Phase gate reached?
   │
   ├─ Trust: low (<80%)     → Manual approval required
   ├─ Trust: medium (>=80%) → Auto-approve: design gate
   ├─ Trust: high (>=90%)   → Auto-approve: design + tasks gates
   └─ Trust: maximum (>=95%)→ Auto-approve: all gates + zero-touch eligible
```

Check current trust: `morph-spec trust status`

### 3. Parallel vs Sequential Implementation

```
Task count > 10 AND multi-domain?
   YES → morph-spec parallel plan {feature}
         → Spawn P-Threads per domain
         → Wait: morph-spec threads wait-all {feature}
         → Merge results
   NO  → Single B-Thread sequential implementation
```

### 4. Fusion Decision

```
Need highest-quality output for critical component?
   YES → morph-spec agents-fuse run --count 3 --strategy best-of-n
         → 3 F-Threads run independently
         → Aggregator picks best result
   NO  → Standard single-agent approach
```

### 5. Checkpoint Gate

```
Task 3, 6, 9, ... completed?
   │
   ├─ Run validators (architecture, security, packages)
   ├─ ALL PASS → Continue, update trust metrics
   └─ FAIL     → Block progress
                  → Attempt 2: fix violations
                  → Attempt 3: fix violations
                  → Attempt 4: AskUserQuestion
```

---

## Zero-Touch Path (Maximum Trust)

When trust level is `maximum` (>95% checkpoint pass rate across 10+ checkpoints):

```
Feature request
    │
    ▼ morph-spec feature create --auto
┌──────────────────────────────────────┐
│         ZERO-TOUCH EXECUTION         │
│                                      │
│  Proposal auto-approved              │
│  Design auto-approved                │
│  Tasks auto-approved                 │
│  Commits auto-signed                 │
│  Rollback auto-triggered on fail     │
│                                      │
│  Escalation triggers:                │
│  - Checkpoint fails 3x → pause       │
│  - Architecture error → pause        │
│  - Security error → BLOCK            │
│  - Out-of-scope change → pause       │
└──────────────────────────────────────┘
    │
    ▼
Feature complete (no human intervention)
```

Configure zero-touch: `framework/workflows/configs/zero-touch.json`

---

## Analytics & Observability

At every step, analytics events are logged to `.morph/analytics/`:

| Event | Log File | When |
|-------|----------|------|
| Phase advanced | `threads-log.jsonl` | Each phase transition |
| Task completed | `threads-log.jsonl` | Each `task done` |
| Checkpoint passed/failed | `threads-log.jsonl` | Every 3 tasks |
| Trust level changed | `trust-log.jsonl` | After each checkpoint |
| Auto-approval used | `trust-log.jsonl` | When gate auto-approved |
| Thread created/killed | `threads-log.jsonl` | Thread lifecycle events |

View analytics: `morph-spec analytics feature {feature-name}`

---

## Context Efficiency at Each Phase

Recommended context loading per phase:

| Phase | Context Budget | Load |
|-------|---------------|------|
| Proposal | 5K tokens | `morph-spec prime feature` output only |
| Design | 15K tokens | Prime + relevant 2-3 standards |
| Clarify | 10K tokens | Spec summary + decisions |
| Tasks | 8K tokens | Spec summary + existing tasks |
| Implement | 20K/thread | Bundle + task-specific standards |
| Sync | 5K tokens | Recap + new decisions |

---

## CLI Quick Reference (v3.0 New Commands)

```bash
# Workflow detection
morph-spec detect-workflow "implement X"

# Context
morph-spec prime feature
morph-spec context bundle create {feature}

# Threads
morph-spec threads list
morph-spec threads wait-all {feature}

# Trust
morph-spec trust status
morph-spec trust auto-calculate {feature}

# Parallel
morph-spec parallel plan {feature}
morph-spec squad-template list

# Fusion
morph-spec agents-fuse run --count 3 --prompt "..."

# HOPs
morph-spec hop list
morph-spec hop render hop-backend-squad output.md --variables '{...}'

# Migration
morph-spec migrate status
morph-spec migrate v2-to-v3

# Analytics
morph-spec analytics feature {feature}
morph-spec core-four {feature}

# Doctor
morph-spec doctor --v3
```

---

## Related

- [Thread Management](THREAD-MANAGEMENT.md) — Thread types and lifecycle
- [Context Optimization](CONTEXT-OPTIMIZATION.md) — Token efficiency techniques
- [Meta-Prompts](META-PROMPTS.md) — HOP template system
- [Migration Guide](MIGRATION-GUIDE.md) — Upgrading from v2.x
