# Getting Started with Cleave

Complete guide to installing, understanding, and running your first cleave session.

## Table of Contents

1. [Installation](#installation)
2. [Understanding Cleave](#understanding-cleave)
3. [Your First Assessment](#your-first-assessment)
4. [Your First Cleave Session](#your-first-cleave-session)
5. [Reading .cloven Reports](#reading-cloven-reports)
6. [Next Steps](#next-steps)

## Installation

### Quick Start (Recommended)

```bash
# Install via pipx (isolated environment)
pipx install styrene-cleave

# Install the Claude Code skill
cleave install-skill

# Verify installation
cleave --version
cleave --help
```

### With TUI Support

```bash
# Install with interactive terminal UI
pipx install styrene-cleave[tui]

# Install the skill
cleave install-skill

# Launch TUI
cleave tui
```

See the main [README](../../README.md) for additional installation options (pip, development).

## Understanding Cleave

### What is Cleave?

Cleave is a **recursive task decomposition system** for managing complexity in software development. It:

1. **Assesses** directive complexity using a formula
2. **Splits** complex directives into 2-3 independent children
3. **Executes** children in parallel or sequence
4. **Reunifies** results with conflict detection

### When to Use Cleave

Use cleave when your task involves:
- **Multiple systems**: UI + API + DB + external services
- **Multiple modifiers**: State coordination, migrations, breaking changes
- **High complexity**: Score > 5.0 (typically)

**Don't use cleave** for:
- Single-system changes
- Simple refactors
- Atomic tasks (already leaf-level)

### Core Concepts

#### Complexity Formula

```
complexity = (1 + systems) × (1 + 0.5 × modifiers)
```

- **Systems**: Architectural boundaries (UI, API, DB, external services)
- **Modifiers**: Complexity factors (state coordination, security, migrations, etc.)

#### Pattern Matching

Cleave recognizes 7 core patterns:
1. Full-Stack CRUD
2. Authentication System
3. External Integration
4. Database Migration
5. Performance Optimization
6. Breaking API Change
7. Simple Refactor

Pattern matching provides fast-path assessment with high confidence.

#### Workspace Structure

Every cleave run creates a `.cleave/` workspace:

```
.cleave/
├── manifest.yaml      # Intent, ancestry, children, assessment
├── siblings.yaml      # Sibling coordination, file claims
├── 0-task.md          # Child 0 directive + result
├── 1-task.md          # Child 1 directive + result
├── metrics.yaml       # Assessment metrics
├── merge.md           # Reunification report (if conflicts)
└── review.md          # Adversarial review
```

## Your First Assessment

Let's assess a directive to understand its complexity.

### Simple Example

```bash
# Create a simple directive
cat > simple.calf << 'EOF'
Add user profile page with avatar upload. Users should be able
to update their display name, bio, and upload a profile picture.
EOF

# Assess complexity
cleave assess --directive "$(cat simple.calf)"
```

**Expected Output**:
```yaml
assessment:
  pattern: "Full-Stack CRUD"
  confidence: 0.80
  systems: 2  # UI, API
  modifiers: 0
  complexity: 2.0
  decision: "execute"  # No cleaving needed
  reasoning: "Straightforward CRUD operation with file upload"
```

### Complex Example

```bash
# Create a complex directive
cat > complex.calf << 'EOF'
Implement real-time collaboration with WebSocket support.
Users should see live cursors, text edits, and presence indicators.
Support conflict resolution for simultaneous edits. Add offline mode
with sync on reconnect.
EOF

# Assess complexity
cleave assess --directive "$(cat complex.calf)"
```

**Expected Output**:
```yaml
assessment:
  pattern: "Full-Stack CRUD"  # Partial match
  confidence: 0.65
  systems: 4  # UI, API, WebSocket infrastructure, conflict resolution
  modifiers: 2  # State coordination, concurrency
  complexity: 7.5
  decision: "cleave"  # Splitting recommended
  reasoning: "Multiple systems with state coordination across websockets"
```

## Your First Cleave Session

Let's run a complete cleave session using Claude Code.

### Step 1: Create Your Directive

Create a CALF file (`.calf` extension) with your directive:

```bash
cat > auth-migration.calf << 'EOF'
Implement JWT-based authentication alongside existing session auth.
Sessions should remain valid during 30-day migration window.
Add /auth/token endpoint for JWT issuance. Update middleware to
accept both auth methods. Include migration guide for API consumers.
EOF
```

### Step 2: Invoke Cleave via Claude Code

Open Claude Code in your project directory:

```bash
claude-code
```

Then invoke the cleave skill with your directive:

```
/cleave
$(cat auth-migration.calf)
```

Or type it directly:

```
/cleave

Implement JWT-based authentication alongside existing session auth.
Sessions should remain valid during 30-day migration window.
Add /auth/token endpoint for JWT issuance. Update middleware to
accept both auth methods. Include migration guide for API consumers.
```

### Step 3: Follow the Conversation

Claude will:

1. **Assess complexity**: Pattern match, calculate score
2. **Ask clarifying questions** (if needed):
   ```
   Q: Should refresh tokens be stored in database or as signed JWTs?
   Options: database (revocable), signed JWTs (stateless)
   ```
3. **Propose decomposition**:
   ```
   Parent: JWT Authentication Implementation
   ├── Child 0: Token Infrastructure
   ├── Child 1: API Integration
   └── Child 2: Migration Documentation
   ```
4. **Execute children**: Each child runs independently
5. **Reunify results**: Merge and detect conflicts

### Step 4: Review Results

After completion, check the workspace:

```bash
# View workspace structure
ls -la .cleave/

# Read child task results
cat .cleave/0-task.md
cat .cleave/1-task.md

# Read reunification report
cat .cleave/merge.md

# Read adversarial review
cat .cleave/review.md
```

## Reading .cloven Reports

After a cleave run, several reports are generated in `.cleave/`.

### manifest.yaml

Captures the directive, assessment, and decomposition strategy:

```yaml
intent:
  goal: "Implement JWT authentication"
  success_criteria:
    - "/auth/token endpoint returns valid JWT"
    - "Middleware accepts both JWT and session auth"
  constraints:
    - "Maintain backwards compatibility for 30 days"

assessment:
  pattern: "Authentication System"
  confidence: 0.85
  complexity: 6.0
  decision: "cleave"

children:
  - label: "Token Infrastructure"
    node_id: "0"
  - label: "API Integration"
    node_id: "1"
```

### siblings.yaml

Tracks coordination between children:

```yaml
siblings:
  - node_id: "0"
    label: "Token Infrastructure"
    status: "complete"
    files_claimed:
      - "src/auth/tokens.py"
      - "tests/test_tokens.py"
    interfaces_published:
      - name: "generate_jwt"
        signature: "generate_jwt(user_id: int) -> str"

  - node_id: "1"
    label: "API Integration"
    status: "complete"
    files_claimed:
      - "src/middleware/auth.py"
    interfaces_consumed:
      - "generate_jwt"  # From sibling 0
```

### Child Task Files (0-task.md, 1-task.md)

Each child has a task file with:

**Directive Section**:
```markdown
## Directive

Implement token generation, validation, and refresh flow for JWT authentication.
```

**Result Section** (filled by child):
```markdown
## Result

**Status**: SUCCESS

**Summary**: Token infrastructure implemented with generation, validation, and refresh.

**Artifacts**:
- `src/auth/tokens.py` - Token generation and validation
- `tests/test_tokens.py` - Unit tests for token lifecycle

**Interfaces Published**:
- `generate_jwt(user_id: int, expires_delta: timedelta) -> str`
- `validate_jwt(token: str) -> dict`

**Decisions Made**:
- Using HS256 algorithm (HMAC with SHA-256)
- Access token expiry: 15 minutes
- Refresh token expiry: 7 days

**Verification**:
```bash
pytest tests/test_tokens.py -v
# All tests pass: 12/12
```
```

### merge.md

Generated during reunification, documents conflict resolution:

```markdown
## Reunification Report

**Status**: MERGED

**Conflicts Detected**: 1

### File Overlap: src/middleware/auth.py

Both Child 0 and Child 1 modified this file.

**Resolution**: 3-way merge
- Child 0 added `validate_jwt` import
- Child 1 added middleware logic
- Combined both changes, no semantic conflict

**Merged File**: src/middleware/auth.py
```

### review.md

Adversarial review probes gaps and validates integration:

```markdown
## Adversarial Review

### Verification Evidence
- ✓ Child 0: Tests pass (12/12)
- ✓ Child 1: Middleware tests pass (8/8)

### Integration Probes
1. Do JWT and session auth both work in middleware?
   - **Test**: curl with both Authorization header and Cookie
   - **Expected**: Both accepted

2. Does token refresh flow work end-to-end?
   - **Test**: Request with expired access token + valid refresh token
   - **Expected**: New access token issued

### Gap Analysis
- Documentation for API consumers: Child 2 incomplete (missing examples)

### Edge Cases
- What happens if JWT secret rotates?
- How are tokens invalidated on logout?

### Functional Validation
```bash
# Test JWT auth
curl -H "Authorization: Bearer <token>" http://localhost:8000/api/protected

# Test session auth
curl -b "session_id=<session>" http://localhost:8000/api/protected
```
```

## Next Steps

Now that you've completed your first cleave session:

1. **Explore patterns**: Review [examples/patterns/](../../examples/patterns/) for real-world examples
2. **Try the TUI**: Interactive terminal UI for task decomposition (`cleave tui`)
3. **Study the CALF format**: [docs/calf-format.md](../calf-format.md)
4. **Learn advanced techniques**: [docs/guides/advanced-patterns.md](advanced-patterns.md)
5. **Understand architecture**: [docs/architecture/overview.md](../architecture/overview.md)

## Common Questions

### When should I use cleave vs direct execution?

Use cleave when:
- Directive touches 3+ systems
- Multiple concerns (state, security, migration)
- Unclear how to split the work

Execute directly when:
- Single system change
- Clear, focused task
- Already atomic

### How do I know if my directive is good?

A good directive:
- Single-sentence goal
- Clear success criteria
- Explicit constraints
- Lists what's out of scope

### What if cleave splits incorrectly?

You can override:
1. Provide more context in the directive
2. Use `cleave-robust` mode for verbose reasoning
3. Manually adjust the split in manifest.yaml

### How deep can cleave recurse?

Default max depth is 5. Each child can cleave again if needed, up to the depth limit.

## Troubleshooting

### Cleave won't split my complex directive

Check assessment output:
```bash
cleave assess --directive "$(cat directive.calf)"
```

If complexity < threshold (default 5.0), no split occurs. You can:
- Add more detail to increase recognized systems
- Manually initialize with specific children: `cleave init --children '["A", "B"]'`

### Child tasks are too vague

Use `cleave-robust` mode in your directive:
```
cleave-robust

Implement JWT authentication...
```

This enables verbose reasoning and complete context in child directives.

### Reunification has conflicts

Review `.cleave/merge.md` for details. Common resolutions:
- **File Overlap**: 3-way merge (automated)
- **Interface Mismatch**: Adapter or refactor one child
- **Decision Contradiction**: Parent decides between options

For more help, see:
- [Advanced Patterns](advanced-patterns.md)
- [TUI Usage](tui-usage.md)
- [Contributing Guide](contributing.md)
