Claude Code Trees
Production-ready Python library for managing Claude Code instances on git worktrees
Claude Code Trees enables you to orchestrate multiple Claude Code instances across different git worktrees, allowing for parallel development workflows and sophisticated AI-powered coding tasks. Perfect for managing complex projects, running parallel experiments, or coordinating multi-faceted development work.
Quick Start
Installation
# Step 1: Install Claude Code CLI (required)
npm install -g @anthropic-ai/claude-code
# Step 2: Install claude-code-trees
pip install claude-code-trees
# Or install from source with PDM (recommended for development)
git clone https://github.com/rizome-dev/claude-code-trees.git
cd claude-code-trees
pdm install
Basic Usage
import asyncio
from pathlib import Path
from claude_code_trees import Orchestrator, Config
async def main():
# Configure the orchestrator
config = Config(
claude_api_key="your-api-key-here",
max_concurrent_instances=3,
worktree_base_path=Path.cwd() / ".worktrees"
)
# Initialize orchestrator with your git repository
orchestrator = Orchestrator("/path/to/your/repo", config)
try:
# Create a Claude Code instance
instance = await orchestrator.create_instance(
worktree_name="feature-branch",
branch="feature/new-functionality"
)
# Start the instance and run a task
await instance.start()
result = await instance.run_task(
"Create a new Python module with comprehensive documentation"
)
if result["success"]:
print(f"Task completed: {result['output']}")
else:
print(f"Task failed: {result['error']}")
finally:
await orchestrator.shutdown()
# Run the example
asyncio.run(main())
CLI Usage
# Create a new Claude Code instance
clct create --name my-instance --branch feature/new-work
# List all instances
clct list
# Run a task on an instance
clct run-task <instance-id> "Implement user authentication system"
# Run multiple tasks in parallel
clct parallel tasks.json --session-name "parallel-dev-work"
# Monitor system health
clct health
# Clean up old resources
clct cleanup --max-age-hours 24
Documentation
Core Components
Orchestrator
The main coordination hub that manages instances, worktrees, and sessions.
orchestrator = Orchestrator(
base_repo_path="/path/to/repo",
config=config
)
# Create instances
instance = await orchestrator.create_instance()
# Run parallel tasks
result = await orchestrator.run_parallel_tasks(tasks)
# Health monitoring
health = await orchestrator.health_check()
ClaudeCodeInstance
Wrapper for individual Claude Code instances running in specific worktrees.
# Execute commands
result = await instance.execute_command("create new file")
# Run high-level tasks
result = await instance.run_task("Implement feature X", context={})
# Health checks
health = await instance.health_check()
WorktreeManager
Manages git worktrees for isolated development environments.
# Create worktrees
worktree = manager.create_worktree("feature-wt", "feature-branch")
# List and manage worktrees
worktrees = manager.list_worktrees()
success = manager.remove_worktree("old-worktree")
SessionManager
Handles persistent sessions with task tracking and execution.
# Create sessions
session = manager.create_session("Development Session")
# Add tasks with dependencies
task = manager.add_task(
session_id,
"Implement feature",
dependencies=["setup-task"]
)
# Execute sessions
success = await manager.execute_session(session_id, instances)
Configuration
Claude Code Trees uses a flexible configuration system:
from claude_code_trees import Config
config = Config(
# Claude settings
claude_api_key="your-key",
claude_model="claude-3-sonnet-20240229",
max_tokens=4096,
# Orchestration settings
max_concurrent_instances=3,
instance_timeout=300,
# Database settings
database_url="sqlite:///claude_trees.db",
# Worktree settings
worktree_base_path=Path("/tmp/worktrees"),
default_branch="main"
)
Environment variables are also supported with the CLCT_ prefix:
export CLCT_CLAUDE_API_KEY="your-key"
export CLCT_MAX_CONCURRENT_INSTANCES=5
export CLCT_WORKTREE_BASE_PATH="/custom/path"
Use Cases
Parallel Feature Development
# Run multiple feature implementations simultaneously
tasks = [
{"name": "User Auth", "description": "Implement user authentication"},
{"name": "API Endpoints", "description": "Create REST API endpoints"},
{"name": "Database Schema", "description": "Design and implement database schema"}
]
result = await orchestrator.run_parallel_tasks(tasks)
Sequential Workflow
# Run tasks in sequence with dependencies
workflow = [
{"name": "Setup", "description": "Initialize project structure"},
{"name": "Core Logic", "description": "Implement core business logic"},
{"name": "Tests", "description": "Create comprehensive test suite"},
{"name": "Documentation", "description": "Generate documentation"}
]
result = await orchestrator.run_sequential_workflow(workflow)
Code Review and Analysis
# Analyze code across multiple worktrees
analysis_tasks = [
{"name": "Security Audit", "description": "Perform security analysis"},
{"name": "Performance Review", "description": "Identify performance bottlenecks"},
{"name": "Code Quality", "description": "Check code quality and standards"}
]
results = await orchestrator.run_parallel_tasks(analysis_tasks)
Features
Error Handling & Resilience
The library includes comprehensive error handling for common failure scenarios:
# Automatic retry with exponential backoff
result = await instance.execute_query(
prompt="Create a new module",
max_retries=3 # Retries on transient failures
)
# Handles specific Claude Code SDK errors
try:
await instance.start()
except CLINotFoundError:
print("Claude Code CLI not installed. Run: npm install -g @anthropic-ai/claude-code")
except CLIConnectionError:
print("Failed to connect to Claude Code service")
Logging
Built-in structured logging for debugging and monitoring:
import logging
# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
# Logs include:
# - Task execution status
# - Retry attempts
# - Performance metrics
# - Error details
Thread Safety
Safe for concurrent use with async/await patterns:
# Run multiple instances concurrently
async with orchestrator:
tasks = [
orchestrator.create_instance(f"instance-{i}")
for i in range(5)
]
instances = await asyncio.gather(*tasks)
Development
Setup
# Clone the repository
git clone https://github.com/rizome-dev/claude-code-trees.git
cd claude-code-trees
# Install dependencies with PDM
pdm install -d
# Run tests (all 96 tests passing)
pdm run test
# Run linting
pdm run lint
# Format code
pdm run format
# Type checking
pdm run typecheck
# Test coverage
pdm run test-cov
Running Examples
# Basic usage
python examples/basic_usage.py
# Parallel tasks
python examples/parallel_tasks.py
# Advanced orchestration
python examples/advanced_orchestration.py
Built with ❤️ by Rizome Labs
Metadata
Release files for claude-code-trees 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| claude_code_trees-0.1.0.tar.gz | 35.4 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| claude_code_trees-0.1.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 62.5 kB
Release files / claude_code_trees-0.1.0.tar.gz
| Download URL | claude_code_trees-0.1.0.tar.gz |
|---|---|
| Size | 35.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
fac743d7d887d6c680e04e720b4af07ee2244fccd842c0bb2403ec12e02dea1f
|
|
BLAKE2b-256 checksum How to use checksums |
4c323ca1e88d57ec5fcef742da373b713d462afce8d7869b4433c353eb1c22fa
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.12.9
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 19, 2025.
Transparency logRelease files / claude_code_trees-0.1.0-py3-none-any.whl
| Download URL | claude_code_trees-0.1.0-py3-none-any.whl |
|---|---|
| Size | 27.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
758f9cd8fa4f32812c74321d01092aa28b7187eeea9df52f51f020e8d988e07c
|
|
BLAKE2b-256 checksum How to use checksums |
4d2cdadd1c0a5575589fb66ce66427ee7bdb51f24c7d36f806bba736669a48fc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/6.1.0 CPython/3.12.9
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Aug 19, 2025.
Transparency log