<!--
  ┌─ 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 (argparse)

## 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:
- Probe integration tests (5+ 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_probe_integration.py

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

### Test Requirements

Integration tests require:
- `pytest>=8.0`

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

### 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
def test_probe_codebase():
    result = probe_codebase(directive="Add authentication", codebase_path=".")
    assert result.stack
    assert result.relevant_files
```

## 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. Determine version number
# Review git log and changes since last release
git log --oneline $(git describe --tags --abbrev=0)..HEAD
# PATCH: Bug fixes only
# MINOR: New features, backward compatible
# MAJOR: Breaking changes

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

# 3. Update CHANGELOG
edit CHANGELOG.md  # Add [0.x.y] section with comprehensive notes

# 4. 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

# 5. Build and publish to PyPI
make upload  # Builds wheel/sdist and uploads via twine

# 6. Post-release validation (see next section)
# REQUIRED: Verify installation and functionality

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

**Notes:**
- Step 1: Use git log to assess scope of changes and choose appropriate version bump
- Step 3: CHANGELOG should document all new features, fixes, and breaking changes
- Step 5: `make upload` handles both build and twine upload
- Step 6: Always validate before announcing the release
- Step 7: GitHub releases are optional; tag is sufficient for most releases

### Post-Release Validation

**IMPORTANT**: Always validate the release before announcing or closing the release workflow.

```bash
# 1. Wait for PyPI propagation (5-10 seconds)
sleep 5
pip index versions styrene-cleave

# 2. Install from PyPI (may need retry if propagation incomplete)
pipx install --force styrene-cleave==0.x.y

# 3. Update local skill
cleave install-skill

# 4. Run functional test for key improvements
# Example: Test the feature that triggered the release
cleave match --directive "Fix workspace scanning in CleaveWorkspaceView.ts"
```

**Validation Checklist:**
- [ ] PyPI shows correct version
- [ ] pipx installation succeeds
- [ ] Skill updated in ~/.claude/skills/cleave/
- [ ] Functional test demonstrates the improvement works
- [ ] Basic commands work (assess, match, init)

### Version Bump Assessment

**CRITICAL**: Always assess the scope of changes before choosing a version number.

```bash
# Review all commits since last release
git log --oneline $(git describe --tags --abbrev=0)..HEAD

# Count commits by type
git log --oneline $(git describe --tags --abbrev=0)..HEAD | grep -E "^[a-f0-9]+ (feat|fix|refactor|chore|docs):" | wc -l

# Check for breaking changes
git log --oneline $(git describe --tags --abbrev=0)..HEAD | grep -i "BREAKING"
```

**Decision Matrix:**
- **PATCH (0.x.Y)**: Only bug fixes, no new functionality
- **MINOR (0.X.0)**: New features, backward compatible, enhancements
- **MAJOR (X.0.0)**: Breaking changes, API incompatibility

**Red Flags for Under-Versioning:**
- Multiple new patterns or major features → MINOR not PATCH
- New modules or significant architecture changes → MINOR not PATCH
- Breaking API changes → MAJOR not MINOR
- 5+ commits with diverse changes → Probably not PATCH

If uncertain after committing, it's acceptable to:
1. Delete the tag: `git tag -d vX.Y.Z && git push origin :refs/tags/vX.Y.Z`
2. Correct version in files
3. Amend commit: `git commit --amend`
4. Re-tag with correct version
5. Force push: `git push -f origin main && git push origin vX.Y.Z`

### 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.
"""
)
```

### Complete Release Checklist

Use this checklist for all releases to ensure consistency and completeness.

**Pre-Release:**
- [ ] Run full test suite: `pytest`
- [ ] Run adversarial review for major/minor releases
- [ ] Fix all critical issues found
- [ ] Assess version bump using git log (PATCH vs MINOR vs MAJOR)

**Version Update:**
- [ ] Update `pyproject.toml` version
- [ ] Update `src/cleave/__init__.py` __version__
- [ ] Update CHANGELOG.md with comprehensive notes
- [ ] Document all new features, fixes, breaking changes

**Commit & Tag:**
- [ ] Stage files: `git add pyproject.toml src/cleave/__init__.py CHANGELOG.md`
- [ ] Commit: `git commit -m "chore: bump version to X.Y.Z"`
- [ ] Push: `git push origin main`
- [ ] Tag: `git tag -a vX.Y.Z -m "Release vX.Y.Z: <summary>"`
- [ ] Push tag: `git push origin vX.Y.Z`

**Publish:**
- [ ] Build and upload: `make upload`
- [ ] Verify upload succeeded (check terminal output)

**Post-Release Validation:**
- [ ] Wait for PyPI propagation: `sleep 5 && pip index versions styrene-cleave`
- [ ] Install from PyPI: `pipx install --force styrene-cleave==X.Y.Z`
- [ ] Update skill: `cleave install-skill`
- [ ] Run functional test demonstrating key improvement
- [ ] Test basic commands: `cleave assess -d "test"`

**Optional:**
- [ ] Create GitHub release: `gh release create vX.Y.Z --title "vX.Y.Z - <title>" --notes-file RELEASE_NOTES.md`
- [ ] Announce in relevant channels

**If Version Number Was Wrong:**
- [ ] Delete tag locally and remotely
- [ ] Correct version in files
- [ ] Amend commit: `git commit --amend`
- [ ] Re-tag with correct version
- [ ] Force push main and new tag

## 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
└── skill/              # Claude Code skill
    ├── __init__.py     # Skill implementation
    └── SKILL.md        # Skill documentation
```

## Documentation

### Documentation Structure

```
docs/
├── guides/              # User guides
│   ├── getting-started.md
│   └── advanced-patterns.md
├── architecture/        # Technical docs
│   ├── overview.md
│   └── assessment-pipeline.md
└── calf-format.md      # CALF file specification
```

### Examples

```
examples/
├── basic-usage/        # Simple examples
├── patterns/           # Pattern-specific examples
└── cli/                # CLI workflow examples
```

## 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 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
]
```

### Optional Dependencies

```toml
[project.optional-dependencies]
dev = ["pytest>=8.0", "pytest-cov>=4.0", "ruff>=0.1", "mypy>=1.8", "types-PyYAML"]
```

### Managing Dependencies

- Keep dependencies minimal
- 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

**Tests failing**:
- Install dev dependencies: `pip install -e ".[dev]"`
- 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.
