# Architecture Overview

High-level architecture of the Cleave system.

## Table of Contents

1. [System Components](#system-components)
2. [Architecture Diagram](#architecture-diagram)
3. [Component Relationships](#component-relationships)
4. [Data Flow](#data-flow)
5. [Execution Models](#execution-models)

## System Components

Cleave consists of three main components:

### 1. CLI Tool (`cleave` command)

**Purpose**: Standalone command-line tool for assessment, workspace management, and reunification.

**Key Modules**:
- `cli.py` - Command-line interface and argument parsing
- `core/assessment.py` - Complexity calculation and pattern matching
- `core/workspace.py` - Workspace initialization and validation
- `core/conflicts.py` - Conflict detection algorithms
- `core/reunify.py` - Reunification logic
- `core/metrics.py` - Assessment metrics and calibration
- `core/probe.py` - Codebase probing and question generation
- `core/settings.py` - Configuration management

**Commands**:
```
cleave assess      - Assess directive complexity
cleave match       - Match against known patterns
cleave probe       - Probe codebase for context-aware questions
cleave init        - Initialize workspace
cleave validate    - Validate workspace structure
cleave status      - Update child task status
cleave context     - Reconstruct context from manifest
cleave conflicts   - Detect conflicts between child results
cleave reunify     - Reunify child results
cleave metrics     - View assessment metrics
cleave config      - Manage configuration
cleave tui         - Launch interactive TUI
```

### 2. Claude Code Skill (`/cleave`)

**Purpose**: Integration with Claude Code for conversational task decomposition.

**Key Files**:
- `skill/__init__.py` - Skill entry point (orchestration)
- `skill/SKILL.md` - Skill documentation (loaded by Claude Code)

**Workflow**:
1. User invokes `/cleave` with directive
2. Skill orchestrates assessment → splitting → execution → reunification
3. Calls CLI tool as needed (`cleave assess`, `cleave init`, etc.)
4. Manages conversation flow (questions, confirmations, status updates)

**Key Features**:
- Socratic interrogation (clarifying questions)
- Adaptive question count (0-6 based on ambiguity)
- Robust mode (verbose reasoning)
- TDD workflow (default, can disable with `--no-tdd`)
- Adversarial review (default, can disable with `--no-review`)

### 3. TUI (Terminal User Interface)

**Purpose**: Interactive chat interface for task decomposition with live streaming.

**Key Modules**:
- `tui/app.py` - Main Textual application
- `tui/screens/main.py` - Main screen layout
- `tui/widgets/` - Custom widgets (chat panel, control panel, etc.)
- `tui/services/` - Services (session, history, SDK, CALF)
- `tui/backends/` - LLM backend integrations (Claude, Ollama, OpenAI, etc.)

**Features**:
- Multi-backend support (Claude, Ollama, OpenAI, vLLM, llama.cpp)
- Live streaming of LLM responses
- Session persistence
- CALF file loading
- Input history
- Tool use display

## Architecture Diagram

```
┌─────────────────────────────────────────────────────────────┐
│                         User Layer                          │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐     │
│  │ Claude Code  │  │   CLI Tool   │  │     TUI      │     │
│  │  (/cleave)   │  │   (cleave)   │  │ (cleave tui) │     │
│  └──────┬───────┘  └──────┬───────┘  └──────┬───────┘     │
│         │                 │                  │             │
│         └─────────────────┼──────────────────┘             │
│                           │                                │
└───────────────────────────┼────────────────────────────────┘
                            │
┌───────────────────────────┼────────────────────────────────┐
│                      Core Logic                            │
├───────────────────────────┼────────────────────────────────┤
│                           │                                │
│  ┌────────────────────────▼─────────────────────────┐      │
│  │           Assessment Pipeline                    │      │
│  ├──────────────────────────────────────────────────┤      │
│  │  1. Probe (codebase context)                     │      │
│  │  2. Pattern Matching (keyword, confidence)       │      │
│  │  3. Complexity Calculation (systems, modifiers)  │      │
│  │  4. Decision (execute | cleave)                  │      │
│  └──────────────────────────────────────────────────┘      │
│                           │                                │
│  ┌────────────────────────▼─────────────────────────┐      │
│  │         Workspace Management                     │      │
│  ├──────────────────────────────────────────────────┤      │
│  │  - Initialize .cleave/ directory                 │      │
│  │  - Generate manifest.yaml                        │      │
│  │  - Generate siblings.yaml                        │      │
│  │  - Generate child task files (N-task.md)         │      │
│  │  - Validate workspace structure                  │      │
│  └──────────────────────────────────────────────────┘      │
│                           │                                │
│  ┌────────────────────────▼─────────────────────────┐      │
│  │          Execution (Parallel/Sequential)         │      │
│  ├──────────────────────────────────────────────────┤      │
│  │  - Execute child tasks                           │      │
│  │  - Track status in siblings.yaml                 │      │
│  │  - Collect results in task files                 │      │
│  └──────────────────────────────────────────────────┘      │
│                           │                                │
│  ┌────────────────────────▼─────────────────────────┐      │
│  │         Reunification Pipeline                   │      │
│  ├──────────────────────────────────────────────────┤      │
│  │  1. Collect child results                        │      │
│  │  2. Detect conflicts                             │      │
│  │     - File overlap                               │      │
│  │     - Decision contradiction                     │      │
│  │     - Interface mismatch                         │      │
│  │     - Assumption violation                       │      │
│  │  3. Generate merge.md (if conflicts)             │      │
│  │  4. Generate review.md (adversarial review)      │      │
│  │  5. Validate against root intent                 │      │
│  └──────────────────────────────────────────────────┘      │
│                           │                                │
│  ┌────────────────────────▼─────────────────────────┐      │
│  │            Metrics & Calibration                 │      │
│  ├──────────────────────────────────────────────────┤      │
│  │  - Record assessment predictions                 │      │
│  │  - Capture actual outcomes                       │      │
│  │  - Calculate accuracy scores                     │      │
│  │  - Generate calibration recommendations          │      │
│  └──────────────────────────────────────────────────┘      │
│                                                            │
└────────────────────────────────────────────────────────────┘
                            │
┌───────────────────────────┼────────────────────────────────┐
│                       Data Layer                           │
├───────────────────────────┼────────────────────────────────┤
│                           │                                │
│  ┌────────────────────────▼─────────────────────────┐      │
│  │          .cleave/ Workspace                      │      │
│  ├──────────────────────────────────────────────────┤      │
│  │  manifest.yaml    - Intent, assessment, children │      │
│  │  siblings.yaml    - Coordination, status, claims │      │
│  │  0-task.md        - Child 0 directive + result   │      │
│  │  1-task.md        - Child 1 directive + result   │      │
│  │  metrics.yaml     - Assessment metrics           │      │
│  │  merge.md         - Conflict resolution report   │      │
│  │  review.md        - Adversarial review           │      │
│  └──────────────────────────────────────────────────┘      │
│                           │                                │
│  ┌────────────────────────▼─────────────────────────┐      │
│  │         ~/.cleave/ Configuration                 │      │
│  ├──────────────────────────────────────────────────┤      │
│  │  settings.yaml    - Backend config, execution    │      │
│  │  sessions/        - TUI session storage          │      │
│  └──────────────────────────────────────────────────┘      │
│                                                            │
└────────────────────────────────────────────────────────────┘
```

## Component Relationships

### CLI ↔ Skill

- **Skill orchestrates**, CLI executes
- Skill calls CLI commands: `cleave assess`, `cleave init`, `cleave reunify`
- CLI returns structured data (YAML, JSON)
- Skill interprets results and manages conversation

### TUI ↔ CLI

- **TUI uses CLI** for core logic
- TUI provides interactive interface
- CLI provides assessment, workspace, reunification
- TUI adds chat, streaming, session management

### TUI ↔ Backends

- **TUI abstracts** LLM backend
- Backend interface: `send_message()`, `stream_response()`
- Backends: Claude (Anthropic), Ollama, OpenAI, vLLM, llama.cpp
- Backend switching at runtime

## Data Flow

### Assessment Flow

```
User Directive
    │
    ▼
┌───────────────┐
│ Probe Phase   │  (optional: codebase scanning)
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Pattern Match │  (keyword matching, confidence scoring)
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Complexity    │  (count systems, modifiers)
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Decision      │  (execute | cleave)
└───────┬───────┘
        │
        ▼
Assessment Result
(pattern, confidence, complexity, decision)
```

### Execution Flow (Cleave)

```
Assessment (decision: cleave)
    │
    ▼
┌───────────────┐
│ Interrogation │  (clarifying questions)
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Decomposition │  (split into 2-3 children)
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Init Workspace│  (create .cleave/, manifest, siblings, tasks)
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Execute Child │  (parallel or sequential)
│   Task 0      │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Execute Child │
│   Task 1      │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Execute Child │  (if ternary split)
│   Task 2      │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Collect       │  (read results from task files)
│ Results       │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Detect        │  (file overlap, decision contradiction, etc.)
│ Conflicts     │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Generate      │  (merge.md, review.md)
│ Reports       │
└───────┬───────┘
        │
        ▼
Parent Task Complete
```

### Nested Cleaving Flow

```
Parent Task (complexity > threshold)
    │
    ▼
Child 0 (complexity > threshold) → Cleaves
    │
    ├─ Child 0.0 → Executes
    ├─ Child 0.1 → Executes
    └─ Child 0.2 → Executes
    │
    └─ Reunify 0.* → Child 0 Complete
    │
    ▼
Child 1 (complexity ≤ threshold) → Executes directly
    │
    ▼
Reunify 0, 1 → Parent Complete
```

## Execution Models

### Direct Execution

**When**: `complexity ≤ threshold`

```
Directive → Execute → Result
```

No workspace created, no splitting.

### Binary Split (2 children)

**When**: Clean architectural seams (frontend/backend, data/logic)

```
Parent
├── Child 0
└── Child 1
```

Example: JWT authentication
- Child 0: Backend (token generation, validation)
- Child 1: Frontend (API integration, UI)

### Ternary Split (3 children)

**When**: Multi-layer stacks, distinct subsystems

```
Parent
├── Child 0
├── Child 1
└── Child 2
```

Example: Full-stack CRUD
- Child 0: UI (forms, tables, validation)
- Child 1: API (endpoints, business logic)
- Child 2: Database (schema, migrations, queries)

### Parallel Execution

**When**: Children are independent (no dependencies)

```
Parent
├── Child 0 ────┐
├── Child 1 ────┼─→ Reunify
└── Child 2 ────┘
```

All children execute simultaneously.

### Sequential Execution

**When**: Children have dependencies (B depends on A)

```
Parent
├── Child 0 ──→ Child 1 ──→ Child 2 ──→ Reunify
```

Each child waits for previous to complete.

### Hybrid Execution

**When**: Some children are independent, some depend on others

```
Parent
├── Child 0 ────────┐
├── Child 1 (after 0) ─┼─→ Reunify
└── Child 2 ────────┘
```

Child 0 and Child 2 execute in parallel, Child 1 waits for Child 0.

## Key Design Principles

### 1. Intent Immutability

Root intent propagates **unchanged** to all descendants. Children operate within the context of the original goal.

### 2. Loose Coupling

Children are independently executable. No direct communication between siblings (coordination via `siblings.yaml`).

### 3. Parent Oversight

Parent is responsible for conflict detection and resolution. Children report results, parent validates.

### 4. Recursive Structure

Every node (parent or child) follows the same pattern: assess → execute/cleave → reunify.

### 5. Observable Artifacts

All decisions, results, and conflicts are documented in workspace files (manifest, task files, merge report, review).

## Extension Points

### 1. Custom Patterns

Add patterns to `src/cleave/core/assessment.py` for domain-specific recognition.

### 2. Custom Backends

Implement `TUIBackend` interface in `src/cleave/tui/backends/` for new LLM providers.

### 3. Custom Conflict Detectors

Extend `src/cleave/core/conflicts.py` with new conflict types.

### 4. Custom Metrics

Add metrics collectors in `src/cleave/core/metrics.py` for calibration.

## Next Steps

- **Backend Interface**: [Backend contract specification](backend-interface.md)
- **Assessment Pipeline**: [Pattern matching and complexity calculation](assessment-pipeline.md)
- **Contributing**: [How to extend Cleave](../guides/contributing.md)
