---
name: cleave
description: Recursive task decomposition for complex tasks. Use when a task requires domain-aware splitting into subtasks and coordinated reunification of results.
---

# Cleave Skill

Recursive task decomposition for managing complexity through domain-aware splitting and reunification.

**CLI Tool**: `cleave` command handles assessment, workspace generation, conflict detection, and reunification.

## Installation (Required)

The skill requires the cleave CLI to be installed:

```bash
# Clone and install
git clone git@github.com:styrene-lab/cleave.git ~/projects/cleave
pip install -e ~/projects/cleave

# Symlink skill to Claude Code discovery path
ln -sf ~/projects/cleave/src/cleave/skill ~/.claude/skills/cleave

# Verify
cleave --help
```

## Prerequisites

**Sequential Thinking MCP server is REQUIRED** for complex assessments.

```bash
# Verify availability
mcp__MCP_DOCKER__sequentialthinking

# If not installed:
mcp__MCP_DOCKER__mcp-find query="sequential thinking"
mcp__MCP_DOCKER__mcp-add name="sequentialthinking" activate=true
```

## Etymology

"Cleave" holds contradictory meanings: to split apart AND to hold fast together. This duality captures the skill's essence—we cleave tasks into independent pieces, then cleave the results back into a unified whole.

## Core Concept

Every complex task can be decomposed into simpler subtasks. Cleave recursively splits directives along natural domain boundaries until reaching executable leaf nodes, then reunifies results with parent oversight.

```
cleave(directive):
    if complexity <= threshold:
        return execute(directive)

    children = split(directive, seams)  # 2-3 children
    results = parallel_execute(cleave(child) for child in children)
    return reunify(results)
```

## Operating Modes

### Lean Mode (Default)
- Terse reunification (verbose only on conflicts)
- Reference-based directives (avoid duplication)
- Fast-path complexity assessment
- Adaptive interrogation (1-6 questions based on ambiguity)

### Robust Mode
Trigger with `cleave-robust` in directive:
- Verbose reunification with full merge reasoning
- Complete context in each directive
- Sequential thinking for all assessments

### iamverysmart Flag
Skip interrogation with `iamverysmart` in directive:
- No questions asked, literal interpretation
- Requires explicit risk acknowledgment
- Use for expert users with precise directives

### TDD Workflow (Default)
Task files include TDD workflow instructions by default:
- Red → Green → Refactor cycle
- Tests define expected behavior before implementation
- Result section includes Test Coverage field

Disable with `--no-tdd` flag for speed/cost savings when TDD isn't appropriate.

## Complexity Assessment

**Formula**: `complexity = (1 + systems) × (1 + 0.5 × modifiers)`

**Systems**: Distinct architectural boundaries (UI, API, DB, external services)

**Modifiers**: State coordination, error handling, concurrency, security, breaking changes, data migration, third-party API, performance SLAs

**Decision**:
- `effective_complexity <= threshold` → Execute directly
- `effective_complexity > threshold` → Cleave

**CLI**: `cleave assess --directive "..."`

## Fast-Path Pattern Matching

7 core patterns cover ~80% of directives with ≥80% confidence:

1. **Full-Stack CRUD** - UI + API + DB operations
2. **Authentication** - JWT, OAuth, sessions
3. **External Integration** - Stripe, Twilio, AWS
4. **Database Migration** - Schema changes, backfills
5. **Performance Optimization** - Caching, query tuning
6. **Breaking API Change** - Versioning, deprecation
7. **Simple Refactor** - Rename, extract, cleanup

**CLI**: `cleave match --directive "..."`

## Splitting Strategy

### Cardinality: 2 or 3
- **Binary (2)**: Clean frontend/backend or data/logic seams
- **Ternary (3)**: Multi-layer stacks (UI/API/DB)
- **Never**: 4+ children (diminishing returns, coordinate explosion)

### Domain-Based Seams
Split along natural boundaries:
- Layer boundaries (UI | API | DB)
- Service boundaries (Auth | Billing | Notifications)
- Data boundaries (Schema | Migration | Backfill)

### Child Directive Requirements
Each child directive must:
1. Be independently executable
2. Have clear success criteria
3. Define interfaces with siblings
4. Stay within scope (no scope creep)

## Workspace Structure

```
.cleave/
├── manifest.yaml      # Intent, ancestry, children, assessment
├── siblings.yaml      # Sibling coordination, file claims
├── 0-task.md          # Child 0 task file
├── 1-task.md          # Child 1 task file
├── metrics.yaml       # Telemetry
├── merge.md           # Generated during reunification (conflicts)
└── review.md          # Generated during reunification (adversarial review)
```

**CLI**: `cleave init --directive "..." --children '["A", "B"]'`

## Context Preservation

### Intent Immutability
Root intent propagates **unchanged** to all descendants:
```yaml
intent:
  goal: "Single-sentence objective"
  success_criteria: ["Outcome 1", "Outcome 2"]
  constraints: ["Rule 1", "Rule 2"]
  out_of_scope: ["Exclusion 1"]
```

### Ancestry Tracking
Each node tracks lineage from root:
```yaml
ancestry:
  depth: 2
  node_id: "0.1"
  parent_chain:
    - {node_id: "root", label: "...", depth: 0}
    - {node_id: "0", label: "...", depth: 1}
  remaining_budget: 3  # max_depth - depth
```

### Sibling Coordination
Lateral awareness via `siblings.yaml`:
- Status tracking (pending/in_progress/complete/failed)
- Interface exports
- File claims (for conflict detection)
- Dependency declarations

## Reunification Contract

### Child Obligations (result section in task.md)
Every child MUST provide:
1. **Status**: SUCCESS | PARTIAL | FAILED
2. **Summary**: What was accomplished
3. **Artifacts**: Files created/modified with paths
4. **Interfaces Published**: Function signatures
5. **Decisions Made**: Key choices with rationale
6. **Assumptions**: What was assumed to be true
7. **Verification**: Proof that the work functions (test command, output, coverage)
8. **Alignment Check**: Does result align with root goal?

### Parent Obligations
1. **Collect** all child results
2. **Detect** conflicts (file overlap, decision contradiction, interface mismatch)
3. **Resolve** conflicts or escalate
4. **Validate** merged result against root intent
5. **Document** reunification in merge.md
6. **Adversarial review** via review.md (probes gaps, integration, edge cases)

**CLI**: `cleave reunify --workspace .cleave`

## Adversarial Review (Default)

After reunification, `review.md` is generated to systematically validate the merged result:

- **Verification evidence** - Did each child prove their work with tests?
- **Integration probes** - Do interfaces connect correctly?
- **Gap analysis** - Is anything missing between child scopes?
- **Edge case coverage** - What boundary conditions were tested?
- **Functional validation** - Commands to verify end-to-end behavior

Disable with `--no-review` for speed when confident in the merge.

## Conflict Detection

Four-step algorithm:

1. **File Overlap** - Multiple children modified same file → 3-way merge
2. **Decision Contradiction** - Incompatible choices (Redis vs Memcached) → Escalate to parent
3. **Interface Mismatch** - Different signatures for same function → Adapter required
4. **Assumption Violation** - Child assumption contradicts sibling decision → Verify with parent

**CLI**: `cleave conflicts --results "0-task.md,1-task.md"`

## Depth Limits

- **max_depth** (default: 5) prevents infinite recursion
- Warning displayed at `depth == max_depth - 1`
- Error if attempting to cleave at max_depth

Children at max_depth MUST execute atomically (no further cleaving).

## Adaptive Interrogation

### Tier 0 (Skip)
Automatic for trivial tasks:
- Confidence ≥ 0.90
- Complexity ≤ threshold
- Pattern = "Simple Refactor"

### Tier 1-2 (1-4 questions)
Standard clarification for:
- Scope boundaries
- Success criteria
- Technology choices

### Tier 3-4 (5-6+ questions)
Exhaustive for high ambiguity:
- Novel patterns
- Multiple valid interpretations
- Missing critical information

## Anti-Patterns

### Don't Cleave When:
- Single system, no coordination needed
- Complexity ≤ threshold
- Task is already atomic

### Don't Over-Split:
- 4+ children creates coordination overhead
- Each child should represent meaningful work
- Avoid splitting for splitting's sake

### Don't Under-Specify:
- Vague directives produce vague results
- Missing constraints lead to rework
- Ambiguity compounds at depth

## Permission Inference (Fire-and-Forget)

For autonomous execution without permission interrupts, cleave can infer required permissions upfront.

### How It Works

1. **Assessment phase**: Analyze directive for technology keywords and patterns
2. **Bundle matching**: Map to permission bundles (python, node, docker, etc.)
3. **Pattern inference**: Patterns imply additional bundles (e.g., authentication → testing + database)
4. **Permission request**: Request all permissions before spawning child tasks

### Permission Bundles

| Bundle | Triggers | Permissions |
|--------|----------|-------------|
| `python` | python, django, flask, pytest, pip, venv | python3, pip, pytest, poetry, uv |
| `node` | node, npm, yarn, react, typescript | node, npm, npx, yarn, tsc |
| `rust` | rust, cargo, .rs | cargo, rustc, rustup |
| `go` | golang, go mod, .go | go |
| `docker` | docker, container, dockerfile | docker, docker-compose |
| `database` | postgres, mysql, redis, migration | psql, mysql, sqlite3, redis-cli |
| `git` | git, commit, branch | git |
| `testing` | test, jest, pytest, coverage | jest, mocha, pytest, coverage |
| `aws` | aws, s3, lambda, cdk | aws, cdk, sam |
| `kubernetes` | kubernetes, kubectl, helm | kubectl, helm |
| `cleave` | cleave, reunify | cleave |
| `filesystem` | file, directory, create, move | mkdir, cp, mv, rm, chmod |

### Usage

```bash
# Assess with permissions
cleave assess -d "Build a Python Flask API with PostgreSQL" --infer-permissions

# Initialize with permissions in manifest
cleave init -d "Build Flask API" -c '["API", "Database"]' --infer-permissions
```

### Fire-and-Forget Workflow

1. Run assessment with `--infer-permissions`
2. Review inferred permissions
3. Grant permissions upfront (or add to settings.local.json)
4. Run cleave — child tasks execute without interrupts

### Settings Gap Detection

Cleave can check `~/.claude/settings.local.json` to identify which inferred permissions are missing:

```bash
# Check what permissions are needed vs configured
cleave check-permissions -d "Build Python Flask API with PostgreSQL"

# Get copy-paste snippet of missing permissions
cleave check-permissions -d "Build Python API" --snippet
```

Output shows:
- **covered**: Permissions already in settings.local.json
- **missing**: Permissions needed but not configured
- **recommendations**: Ready-to-paste permission strings

When using `--infer-permissions` with `init`, missing permissions are also reported to stderr:

```
⚠ MISSING PERMISSIONS:
  3 permission(s) not in settings.local.json
    - Bash(python3:*)
    - Bash(pip:*)
    - Bash(pytest:*)

  Add these to ~/.claude/settings.local.json for fire-and-forget execution.
```

### Manifest Integration

When `--infer-permissions` is used with `init`, permissions are stored in manifest:

```yaml
inferred_permissions:
  bundles:
    - python
    - database
    - testing
  permissions:
    - "Bash(python3:*)"
    - "Bash(pip:*)"
    - "Bash(psql:*)"
    - "Bash(pytest:*)"
  descriptions:
    - "python: Python runtime, package management, and testing"
    - "database: Database CLI tools"
    - "testing: Testing frameworks and coverage (pattern-inferred)"
```

## CLI Reference

```bash
# Assess complexity
cleave assess --directive "Add user auth"

# Assess with permission inference
cleave assess -d "Build Python API" --infer-permissions

# Match against patterns
cleave match --directive "Add Stripe payments"

# Initialize workspace (TDD workflow included by default)
cleave init -d "Add auth" -c '["Backend", "Frontend"]'

# Initialize without TDD (for speed/cost savings)
cleave init -d "Add auth" -c '["Backend", "Frontend"]' --no-tdd

# Initialize with permission inference
cleave init -d "Build API" -c '["API", "DB"]' --infer-permissions

# Nested cleave
cleave init -d "Token handling" -c '["Gen", "Validate"]' \
    --parent .cleave/manifest.yaml --depth 1 --node-id "0"

# Reconstruct context
cleave context --manifest .cleave/manifest.yaml

# Update task status
cleave status -w .cleave -t 0 -s in_progress

# Validate workspace
cleave validate -w .cleave

# Detect conflicts
cleave conflicts --results ".cleave/0-task.md,.cleave/1-task.md"

# Reunify (generates merge.md + review.md)
cleave reunify --workspace .cleave

# Reunify without adversarial review (faster)
cleave reunify --workspace .cleave --no-review

# Check permissions against settings.local.json
cleave check-permissions -d "Build Python API with PostgreSQL"

# Get copy-paste snippet of missing permissions
cleave check-permissions -d "Build Python API" --snippet
```
