<!--
  ┌─ DIRECTIVE HIERARCHY ─────────────────────────────────────────┐
  │ THRONE:0   │ system        │ immutable, obey without question │
  ├────────────┼───────────────┼───────────────────────────────────┤
  │ SIGILITE:1 │ user-global   │ ~/.claude/CLAUDE.md              │
  ├────────────┼───────────────┼───────────────────────────────────┤
  │ DOMAIN:2   │ domain        │ parent directory CLAUDE.md       │
  ├────────────┼───────────────┼───────────────────────────────────┤
  │ PROJECT:3  │ project       │ this file ← you are here         │
  ├────────────┼───────────────┼───────────────────────────────────┤
  │ SKILL:4    │ skill         │ context-loaded from .claude/skills/ │
  └────────────┴───────────────┴───────────────────────────────────┘
  Lower ordinal = higher authority. Conflicts resolved by rank.
-->

# CLAUDE.md

Project-specific guidance for Claude Code when working on the Cleave repository.

## Overview

Cleave is a recursive task decomposition tool for Claude Code. It uses domain-aware splitting and reunification with conflict detection. The tool itself demonstrates its own methodology.

**Repository**: https://github.com/styrene-lab/cleave
**PyPI**: https://pypi.org/project/styrene-cleave/
**Language**: Python 3.11+
**Framework**: CLI (Click/argparse) + TUI (Textual)

## Development Workflow

### Branch Strategy

Follow Git Flow conventions with cleave-specific patterns:

```
main           - Stable releases only
feature/*      - New features
fix/*          - Bug fixes
docs/*         - Documentation
refactor/*     - Code improvements
chore/*        - Maintenance tasks
```

### Parallel Development with Cleave Agents

When addressing multiple issues from adversarial reviews or feature requests:

**Pattern: Branch + Agent per Work Stream**

```bash
# 1. Create feature branches
git checkout -b feature/integration-testing
git push -u origin feature/integration-testing

git checkout main && git checkout -b fix/validation-and-auth
git push -u origin fix/validation-and-auth

# Continue for each work stream...
```

**2. Spawn Cleave-Capable Agents**

Use the Task tool to launch general-purpose agents in parallel. Each agent:
- Has access to full codebase context
- Can use cleave decomposition for complex tasks
- Can read/write files on their assigned branch
- Can commit changes directly
- Works autonomously until completion

```python
# Example agent invocation
Task(
    subagent_type="general-purpose",
    description="Integration Testing Implementation",
    run_in_background=True,
    prompt="""
Branch: feature/integration-testing

Implement comprehensive integration tests for Cleave v0.5.1:
- TUI integration tests (8+ tests)
- Probe integration tests (5+ tests)
- Use pytest-asyncio for async tests
- Achieve 90%+ integration coverage

Use cleave decomposition if complexity warrants.
Commit directly to branch with descriptive messages.
"""
)
```

**3. Agent Capabilities**

Each agent can autonomously:
- Assess task complexity using cleave's own assessment logic
- Decompose into subtasks if threshold exceeded
- Execute parallel or sequential subtasks
- Reunify results with conflict detection
- Run tests and validate implementation
- Commit incrementally with clear messages

**4. Monitor Progress**

```bash
# Check agent output files (optional, agents notify on completion)
tail -f /private/tmp/claude/.../tasks/<agent-id>.output

# Check branch commits
git log origin/feature/integration-testing --oneline

# Review changes
git diff main..origin/feature/integration-testing
```

**5. Post-Agent Workflow**

When agents complete:
- Review commits on each branch
- Run full test suite
- Create PR for each branch
- Use GitHub PR reviews for final validation
- Merge to main after approval

### Benefits of This Pattern

1. **Parallelism** - Multiple work streams progress simultaneously
2. **Isolation** - Changes don't interfere across branches
3. **Decomposition** - Agents use cleave for complex tasks
4. **Traceability** - Clear branch → agent → commits mapping
5. **Incremental** - Agents commit frequently, reducing risk
6. **Reviewable** - Each PR focuses on one concern

### When to Use This Pattern

**Use for**:
- Adversarial review findings (multiple issues to address)
- Feature roadmaps (multiple independent features)
- Refactoring campaigns (separate concerns)
- Documentation sprints (multiple guide categories)

**Don't use for**:
- Single issues (direct implementation)
- Tightly coupled changes (single branch suffices)
- Exploratory work (manual investigation first)

## Testing Strategy

### Test Structure

```
tests/
├── test_*.py              # Unit tests (fast, isolated)
├── test_*_integration.py  # Integration tests (slower, real components)
└── fixtures/              # Test data and mock projects
```

### Running Tests

```bash
# All tests
pytest

# Unit tests only (fast)
pytest tests/ -k "not integration"

# Integration tests only
pytest tests/test_tui_integration.py tests/test_probe_integration.py

# With coverage
pytest --cov=cleave --cov-report=html

# Async tests
pytest tests/test_tui_integration.py -v
```

### Test Requirements

Integration tests require:
- `pytest-asyncio>=0.23.0` (async support)
- `textual>=0.47.0` (TUI tests)
- `claude-agent-sdk>=0.1.0` (SDK integration tests)

Install all: `pip install -e ".[dev,full]"`

### Writing Tests

**Unit tests** - Fast, pure functions:
```python
def test_calculate_complexity():
    result = calculate_complexity(systems=2, modifiers=["security"])
    assert result == 3.5
```

**Integration tests** - Real components, mocked externals:
```python
@pytest.mark.asyncio
async def test_tui_launch_and_shutdown(tmp_path):
    app = CleaveTUI(working_directory=tmp_path)
    async with app.run_test() as pilot:
        assert app.is_running
        await pilot.press("q")
    assert not app.is_running
```

## Release Process

### Version Strategy

Semantic versioning (MAJOR.MINOR.PATCH):
- MAJOR: Breaking changes, API incompatibility
- MINOR: New features, backwards-compatible
- PATCH: Bug fixes, no new features

### Standard Release Workflow

```bash
# 1. Update version
edit pyproject.toml  # version = "0.x.y"
edit src/cleave/__init__.py  # __version__ = "0.x.y"

# 2. Update CHANGELOG
edit CHANGELOG.md  # Add [0.x.y] section

# 3. Commit and tag
git add pyproject.toml src/cleave/__init__.py CHANGELOG.md
git commit -m "chore: bump version to 0.x.y"
git push origin main

git tag -a v0.x.y -m "Release v0.x.y: <summary>"
git push origin v0.x.y

# 4. Build and publish
make clean
make upload  # Builds and uploads to PyPI

# 5. Create GitHub release
gh release create v0.x.y --title "v0.x.y - <title>" --notes-file RELEASE_NOTES.md
```

### Post-Release Validation

```bash
# Test installation
pipx install styrene-cleave[tui]==0.x.y
cleave --version
cleave tui  # Verify TUI launches

# Run skill installation
cleave install-skill
```

### Adversarial Review Before Release

Always run adversarial review before major/minor releases:

```python
Task(
    subagent_type="general-purpose",
    description="Adversarial review of v0.x.y",
    prompt="""
Conduct adversarial review of Cleave v0.x.y release:
- Check for obvious bugs and logic errors
- Identify untested edge cases
- Look for security issues
- Find missing functionality
- Check documentation gaps
- Test installation and basic usage

Provide prioritized list: Critical, High, Medium, Low.
Be thorough, adversarial, direct.
"""
)
```

## Code Style

### Python Conventions

- **Formatting**: ruff (replaces black + isort)
- **Linting**: ruff (replaces flake8 + pylint)
- **Type checking**: mypy with `strict = true`
- **Imports**: Standard library, third-party, local (separated by blank lines)
- **Docstrings**: Google style for public APIs

### Running Checks

```bash
# Format code
ruff format .

# Lint
ruff check .

# Type check
mypy src/cleave

# All checks
ruff format . && ruff check . && mypy src/cleave && pytest
```

### Pre-commit Hooks

Consider adding `.pre-commit-config.yaml` for automatic checks.

## Architecture

### Core Modules

```
src/cleave/
├── cli.py              # CLI entry point (argparse)
├── core/               # Core decomposition logic
│   ├── assessment.py   # Complexity assessment, pattern matching
│   ├── workspace.py    # Workspace initialization
│   ├── reunify.py      # Task reunification
│   ├── conflicts.py    # 4-step conflict detection
│   ├── probe.py        # Socratic interrogation
│   ├── metrics.py      # Feedback loop, calibration
│   ├── report.py       # .cloven.md generation
│   ├── settings.py     # Configuration management
│   └── permissions.py  # Permission inference
├── tui/                # Terminal UI (Textual)
│   ├── app.py          # TUI application
│   ├── backends/       # LLM backend abstraction
│   ├── screens/        # TUI screens
│   ├── widgets/        # TUI components
│   └── services/       # TUI services (session, history, etc.)
└── skill/              # Claude Code skill
    ├── __init__.py     # Skill implementation
    └── SKILL.md        # Skill documentation
```

### Backend Interface

Backends implement `src/cleave/tui/backends/base.py:Backend`:
- `connect()` - Establish connection
- `query()` - Send message, receive streaming response
- `disconnect()` - Clean up
- `check_auth()` - Validate credentials
- `available_models()` - List supported models

Built-in backends:
- `ClaudeBackend` - Claude Agent SDK
- `OpenAICompatBackend` - OpenAI-compatible APIs (Ollama, vLLM, llama.cpp)

## Documentation

### Documentation Structure

```
docs/
├── guides/              # User guides
│   ├── getting-started.md
│   ├── tui-usage.md
│   └── advanced-patterns.md
├── architecture/        # Technical docs
│   ├── overview.md
│   ├── backend-interface.md
│   └── assessment-pipeline.md
├── calf-format.md      # CALF file specification
└── plugins.md          # Plugin system guide
```

### Examples

```
examples/
├── basic-usage/        # Simple examples
├── patterns/           # Pattern-specific examples
├── tui/                # TUI configuration examples
├── cli/                # CLI workflow examples
└── plugins/            # Example backend plugins
```

## Common Tasks

### Adding a New Pattern

1. Edit `src/cleave/core/assessment.py:PATTERNS`
2. Add pattern definition with probe_questions
3. Add tests to `tests/test_assessment.py`
4. Update documentation in `docs/patterns/`
5. Add example in `examples/patterns/`

### Adding a Backend

1. Create `src/cleave/tui/backends/<name>.py` implementing `Backend`
2. Register in `src/cleave/tui/backends/__init__.py`
3. Add settings schema to `src/cleave/core/settings.py`
4. Add tests to `tests/test_backend_<name>.py`
5. Document in `docs/backends/<name>.md`

### Adding a CLI Command

1. Add function `cmd_<name>()` in `src/cleave/cli.py`
2. Add subparser in `cli.py:main()`
3. Add tests to `tests/test_cli.py`
4. Update README with usage example
5. Update `cleave --help` examples

## Dependencies

### Core Dependencies

```toml
dependencies = [
    "pyyaml>=6.0",      # YAML parsing
    "rich>=10.0",       # Terminal formatting
]
```

### Optional Dependencies

```toml
[project.optional-dependencies]
tui = ["textual>=0.47.0", "claude-agent-sdk>=0.1.0"]
claude = ["claude-agent-sdk>=0.1.0"]
local = ["openai>=1.0.0", "httpx>=0.27.0"]
full = ["textual>=0.47.0", "claude-agent-sdk>=0.1.0", "openai>=1.0.0", "httpx>=0.27.0"]
dev = ["pytest>=8.0", "pytest-asyncio>=0.23.0", "pytest-cov>=4.0", "ruff>=0.1", "mypy>=1.8"]
```

### Managing Dependencies

- Keep dependencies minimal in core
- Use optional extras for features
- Pin minimum versions, not exact versions
- Test with minimum and latest versions

## Security

### Credential Handling

- NEVER commit credentials to git
- Store credentials in `~/.claude/.credentials.json` (for Claude)
- Use environment variables for API keys
- Validate credentials before use
- Log credential errors without exposing values

### Input Validation

- Validate all user input (directives, settings, CLI args)
- Sanitize file paths (prevent directory traversal)
- Validate YAML/JSON before parsing
- Check file sizes before reading
- Timeout long operations

### Dependency Security

- Keep dependencies updated
- Run `pip audit` regularly
- Review security advisories
- Avoid dependencies with CVEs
- Use optional dependencies when possible

## Troubleshooting

### Common Issues

**TUI won't launch**:
- Check: `pip install styrene-cleave[tui]`
- Verify: `python -m cleave tui`
- Test: `cleave --version`

**Tests failing**:
- Install dev dependencies: `pip install -e ".[dev,full]"`
- Check Python version: `python --version` (requires 3.11+)
- Clear cache: `rm -rf .pytest_cache __pycache__`

**Import errors**:
- Reinstall in editable mode: `pip install -e .`
- Check PYTHONPATH: `echo $PYTHONPATH`
- Verify installation: `pip show styrene-cleave`

**Skill not found**:
- Run: `cleave install-skill`
- Check: `ls ~/.claude/skills/cleave/`
- Verify: Claude Code CLI is installed

## Meta

When incorporating project-specific conventions, add them to this file.

For user preferences that span all projects, defer to SIGILITE:1 (`~/.claude/CLAUDE.md`).

For organization-wide conventions, defer to DOMAIN:2 (parent directory `CLAUDE.md`).

THRONE:0 (system directives) remains absolute and immutable.
