# Claude Code Trees
**Production-ready Python library for managing Claude Code instances on git worktrees**
[](https://www.python.org/downloads/)
[](https://opensource.org/licenses/MIT)
[](https://pypi.org/project/claude-code-sdk/)
[](https://github.com/rizome-dev/claude-code-trees)
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
```bash
# 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
```python
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
```bash
# 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.
```python
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.
```python
# 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.
```python
# 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.
```python
# 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:
```python
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:
```bash
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
```python
# 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
```python
# 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
```python
# 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:
```python
# 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:
```python
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:
```python
# 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
```bash
# 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
```bash
# 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](https://rizome.dev)
Raw data
{
"_id": null,
"home_page": null,
"name": "claude-code-trees",
"maintainer": null,
"docs_url": null,
"requires_python": "<4.0,>=3.10",
"maintainer_email": null,
"keywords": "claude, code, git, worktree, ai, orchestration, development",
"author": null,
"author_email": "samjtro <hi@samjtro.com>",
"download_url": "https://files.pythonhosted.org/packages/4c/32/3ca1e88d57ec5fcef742da373b713d462afce8d7869b4433c353eb1c22fa/claude_code_trees-0.1.0.tar.gz",
"platform": null,
"description": "# Claude Code Trees\n\n**Production-ready Python library for managing Claude Code instances on git worktrees**\n\n[](https://www.python.org/downloads/)\n[](https://opensource.org/licenses/MIT)\n[](https://pypi.org/project/claude-code-sdk/)\n[](https://github.com/rizome-dev/claude-code-trees)\n\nClaude 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.\n\n## Quick Start\n\n### Installation\n\n```bash\n# Step 1: Install Claude Code CLI (required)\nnpm install -g @anthropic-ai/claude-code\n\n# Step 2: Install claude-code-trees\npip install claude-code-trees\n\n# Or install from source with PDM (recommended for development)\ngit clone https://github.com/rizome-dev/claude-code-trees.git\ncd claude-code-trees\npdm install\n```\n\n### Basic Usage\n\n```python\nimport asyncio\nfrom pathlib import Path\nfrom claude_code_trees import Orchestrator, Config\n\nasync def main():\n # Configure the orchestrator\n config = Config(\n claude_api_key=\"your-api-key-here\",\n max_concurrent_instances=3,\n worktree_base_path=Path.cwd() / \".worktrees\"\n )\n \n # Initialize orchestrator with your git repository\n orchestrator = Orchestrator(\"/path/to/your/repo\", config)\n \n try:\n # Create a Claude Code instance\n instance = await orchestrator.create_instance(\n worktree_name=\"feature-branch\",\n branch=\"feature/new-functionality\"\n )\n \n # Start the instance and run a task\n await instance.start()\n result = await instance.run_task(\n \"Create a new Python module with comprehensive documentation\"\n )\n \n if result[\"success\"]:\n print(f\"Task completed: {result['output']}\")\n else:\n print(f\"Task failed: {result['error']}\")\n \n finally:\n await orchestrator.shutdown()\n\n# Run the example\nasyncio.run(main())\n```\n\n### CLI Usage\n\n```bash\n# Create a new Claude Code instance\nclct create --name my-instance --branch feature/new-work\n\n# List all instances\nclct list\n\n# Run a task on an instance\nclct run-task <instance-id> \"Implement user authentication system\"\n\n# Run multiple tasks in parallel\nclct parallel tasks.json --session-name \"parallel-dev-work\"\n\n# Monitor system health\nclct health\n\n# Clean up old resources\nclct cleanup --max-age-hours 24\n```\n\n## Documentation\n\n### Core Components\n\n#### Orchestrator\nThe main coordination hub that manages instances, worktrees, and sessions.\n\n```python\norchestrator = Orchestrator(\n base_repo_path=\"/path/to/repo\",\n config=config\n)\n\n# Create instances\ninstance = await orchestrator.create_instance()\n\n# Run parallel tasks\nresult = await orchestrator.run_parallel_tasks(tasks)\n\n# Health monitoring\nhealth = await orchestrator.health_check()\n```\n\n#### ClaudeCodeInstance\nWrapper for individual Claude Code instances running in specific worktrees.\n\n```python\n# Execute commands\nresult = await instance.execute_command(\"create new file\")\n\n# Run high-level tasks\nresult = await instance.run_task(\"Implement feature X\", context={})\n\n# Health checks\nhealth = await instance.health_check()\n```\n\n#### WorktreeManager\nManages git worktrees for isolated development environments.\n\n```python\n# Create worktrees\nworktree = manager.create_worktree(\"feature-wt\", \"feature-branch\")\n\n# List and manage worktrees\nworktrees = manager.list_worktrees()\nsuccess = manager.remove_worktree(\"old-worktree\")\n```\n\n#### SessionManager\nHandles persistent sessions with task tracking and execution.\n\n```python\n# Create sessions\nsession = manager.create_session(\"Development Session\")\n\n# Add tasks with dependencies\ntask = manager.add_task(\n session_id, \n \"Implement feature\",\n dependencies=[\"setup-task\"]\n)\n\n# Execute sessions\nsuccess = await manager.execute_session(session_id, instances)\n```\n\n### Configuration\n\nClaude Code Trees uses a flexible configuration system:\n\n```python\nfrom claude_code_trees import Config\n\nconfig = Config(\n # Claude settings\n claude_api_key=\"your-key\",\n claude_model=\"claude-3-sonnet-20240229\",\n max_tokens=4096,\n \n # Orchestration settings\n max_concurrent_instances=3,\n instance_timeout=300,\n \n # Database settings\n database_url=\"sqlite:///claude_trees.db\",\n \n # Worktree settings\n worktree_base_path=Path(\"/tmp/worktrees\"),\n default_branch=\"main\"\n)\n```\n\nEnvironment variables are also supported with the `CLCT_` prefix:\n\n```bash\nexport CLCT_CLAUDE_API_KEY=\"your-key\"\nexport CLCT_MAX_CONCURRENT_INSTANCES=5\nexport CLCT_WORKTREE_BASE_PATH=\"/custom/path\"\n```\n\n## Use Cases\n\n### Parallel Feature Development\n```python\n# Run multiple feature implementations simultaneously\ntasks = [\n {\"name\": \"User Auth\", \"description\": \"Implement user authentication\"},\n {\"name\": \"API Endpoints\", \"description\": \"Create REST API endpoints\"},\n {\"name\": \"Database Schema\", \"description\": \"Design and implement database schema\"}\n]\n\nresult = await orchestrator.run_parallel_tasks(tasks)\n```\n\n### Sequential Workflow\n```python\n# Run tasks in sequence with dependencies\nworkflow = [\n {\"name\": \"Setup\", \"description\": \"Initialize project structure\"},\n {\"name\": \"Core Logic\", \"description\": \"Implement core business logic\"},\n {\"name\": \"Tests\", \"description\": \"Create comprehensive test suite\"},\n {\"name\": \"Documentation\", \"description\": \"Generate documentation\"}\n]\n\nresult = await orchestrator.run_sequential_workflow(workflow)\n```\n\n### Code Review and Analysis\n```python\n# Analyze code across multiple worktrees\nanalysis_tasks = [\n {\"name\": \"Security Audit\", \"description\": \"Perform security analysis\"},\n {\"name\": \"Performance Review\", \"description\": \"Identify performance bottlenecks\"},\n {\"name\": \"Code Quality\", \"description\": \"Check code quality and standards\"}\n]\n\nresults = await orchestrator.run_parallel_tasks(analysis_tasks)\n```\n\n## Features\n\n### Error Handling & Resilience\n\nThe library includes comprehensive error handling for common failure scenarios:\n\n```python\n# Automatic retry with exponential backoff\nresult = await instance.execute_query(\n prompt=\"Create a new module\",\n max_retries=3 # Retries on transient failures\n)\n\n# Handles specific Claude Code SDK errors\ntry:\n await instance.start()\nexcept CLINotFoundError:\n print(\"Claude Code CLI not installed. Run: npm install -g @anthropic-ai/claude-code\")\nexcept CLIConnectionError:\n print(\"Failed to connect to Claude Code service\")\n```\n\n### Logging\n\nBuilt-in structured logging for debugging and monitoring:\n\n```python\nimport logging\n\n# Enable debug logging\nlogging.basicConfig(level=logging.DEBUG)\n\n# Logs include:\n# - Task execution status\n# - Retry attempts\n# - Performance metrics\n# - Error details\n```\n\n### Thread Safety\n\nSafe for concurrent use with async/await patterns:\n\n```python\n# Run multiple instances concurrently\nasync with orchestrator:\n tasks = [\n orchestrator.create_instance(f\"instance-{i}\")\n for i in range(5)\n ]\n instances = await asyncio.gather(*tasks)\n```\n\n## Development\n\n### Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/rizome-dev/claude-code-trees.git\ncd claude-code-trees\n\n# Install dependencies with PDM\npdm install -d\n\n# Run tests (all 96 tests passing)\npdm run test\n\n# Run linting\npdm run lint\n\n# Format code\npdm run format\n\n# Type checking\npdm run typecheck\n\n# Test coverage\npdm run test-cov\n```\n\n### Running Examples\n\n```bash\n# Basic usage\npython examples/basic_usage.py\n\n# Parallel tasks\npython examples/parallel_tasks.py\n\n# Advanced orchestration\npython examples/advanced_orchestration.py\n```\n\n---\n\nBuilt with \u2764\ufe0f by [Rizome Labs](https://rizome.dev)\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Production-ready Python library for managing Claude Code instances on git worktrees",
"version": "0.1.0",
"project_urls": {
"Changelog": "https://github.com/rizome-dev/claude-code-trees/blob/main/CHANGELOG.md",
"Documentation": "https://github.com/rizome-dev/claude-code-trees#readme",
"Homepage": "https://github.com/rizome-dev/claude-code-trees",
"Issue Tracker": "https://github.com/rizome-dev/claude-code-trees/issues",
"Repository": "https://github.com/rizome-dev/claude-code-trees"
},
"split_keywords": [
"claude",
" code",
" git",
" worktree",
" ai",
" orchestration",
" development"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "4d2cdadd1c0a5575589fb66ce66427ee7bdb51f24c7d36f806bba736669a48fc",
"md5": "25acf9b611ecac41869171a73f04d364",
"sha256": "758f9cd8fa4f32812c74321d01092aa28b7187eeea9df52f51f020e8d988e07c"
},
"downloads": -1,
"filename": "claude_code_trees-0.1.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "25acf9b611ecac41869171a73f04d364",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": "<4.0,>=3.10",
"size": 27075,
"upload_time": "2025-08-19T23:28:42",
"upload_time_iso_8601": "2025-08-19T23:28:42.022801Z",
"url": "https://files.pythonhosted.org/packages/4d/2c/dadd1c0a5575589fb66ce66427ee7bdb51f24c7d36f806bba736669a48fc/claude_code_trees-0.1.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "4c323ca1e88d57ec5fcef742da373b713d462afce8d7869b4433c353eb1c22fa",
"md5": "63a4aff4fa37a47c34de8650bb4f97c6",
"sha256": "fac743d7d887d6c680e04e720b4af07ee2244fccd842c0bb2403ec12e02dea1f"
},
"downloads": -1,
"filename": "claude_code_trees-0.1.0.tar.gz",
"has_sig": false,
"md5_digest": "63a4aff4fa37a47c34de8650bb4f97c6",
"packagetype": "sdist",
"python_version": "source",
"requires_python": "<4.0,>=3.10",
"size": 35380,
"upload_time": "2025-08-19T23:28:43",
"upload_time_iso_8601": "2025-08-19T23:28:43.801927Z",
"url": "https://files.pythonhosted.org/packages/4c/32/3ca1e88d57ec5fcef742da373b713d462afce8d7869b4433c353eb1c22fa/claude_code_trees-0.1.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-08-19 23:28:43",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "rizome-dev",
"github_project": "claude-code-trees",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "claude-code-trees"
}