claude-pool 0.3.0

Slot pool orchestration library for Claude CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
# claude-pool

Slot pool orchestration library for Claude CLI

[![Crates.io](https://img.shields.io/crates/v/claude-pool.svg)](https://crates.io/crates/claude-pool)
[![Documentation](https://docs.rs/claude-pool/badge.svg)](https://docs.rs/claude-pool)
[![CI](https://github.com/joshrotenberg/claude-wrapper/actions/workflows/ci.yml/badge.svg)](https://github.com/joshrotenberg/claude-wrapper/actions/workflows/ci.yml)
[![License](https://img.shields.io/crates/l/claude-pool.svg)](LICENSE-MIT)

## Overview

`claude-pool` manages N Claude CLI slots behind a unified interface. A coordinator (typically an interactive Claude session) submits work, and the pool routes tasks by availability, tracks budgets, and handles slot lifecycle and session management.

Perfect for:
- Scaling Claude work across multiple slots
- Budget-aware task distribution
- Parallel and sequential task orchestration
- Slot isolation with optional Git worktrees

## Architecture

```
Coordinator (your app or interactive session)
  │
  ├─ pool.run("task")           → synchronous
  ├─ pool.submit("task")        → async, returns task ID
  ├─ pool.fan_out([tasks])      → parallel execution
  └─ execute_chain(steps)       → sequential pipeline
        ├── Pool (task queue, context, budget)
        ├── Slot-0 (Claude instance)
        ├── Slot-1 (Claude instance)
        └── Slot-N (Claude instance)
```

## Installation

```bash
cargo add claude-pool
```

Requires: `claude-wrapper` (included as dependency)

## Quick Start

```rust
use claude_pool::Pool;
use claude_wrapper::Claude;

#[tokio::main]
async fn main() -> claude_pool::Result<()> {
    let claude = Claude::builder().build()?;
    let pool = Pool::builder(claude)
        .slots(4)
        .build()
        .await?;

    let result = pool.run("write a haiku about rust").await?;
    println!("{}", result.output);

    pool.drain().await?;
    Ok(())
}
```

## Core Concepts

### Synchronous vs Asynchronous Tasks

**Synchronous (blocking):**
```rust
let result = pool.run("your task here").await?;
println!("{}", result.output);
```

**Asynchronous (non-blocking):**
```rust
let task_id = pool.submit("long-running task").await?;
// Do other work...
let result = pool.result(&task_id).await??;
```

### Budget Control

Track and limit spending:

```rust
let pool = Pool::builder(claude)
    .slots(4)
    .config(
        PoolConfig::default()
            .with_budget_usd(50.0)  // Pool-level cap
    )
    .build()
    .await?;
```

Budget is tracked atomically per task. When the pool reaches its cap, subsequent tasks are rejected.

### Slot Identity

Each slot has metadata for coordination:

```rust
pool.configure_slot("slot-0", "analyzer", "Code review specialist")
    .await?;
pool.configure_slot("slot-1", "writer", "Code generation specialist")
    .await?;
```

Access slot info:
```rust
let status = pool.status().await?;
for slot in status.slots {
    println!("{}: {} ({} active)", slot.id, slot.role, slot.busy_tasks);
}
```

### Shared Context

Inject key-value pairs into all slot system prompts:

```rust
pool.context_set("language", "rust").await?;
pool.context_set("framework", "tokio").await?;
pool.context_set("style", "idiomatic").await?;

// All slots now see these in their system prompts
```

Access context:
```rust
let value = pool.context_get("language").await??;
pool.context_delete("framework").await?;
let all = pool.context_list().await?;
```

## Pool Builder Configuration

```rust
use claude_pool::{Pool, PoolConfig, Effort, PermissionMode};

let pool = Pool::builder(claude)
    .slots(8)
    .config(
        PoolConfig::default()
            .with_model("sonnet")
            .with_effort(Effort::High)
            .with_budget_usd(100.0)
            .with_permission_mode(PermissionMode::Plan)
            .with_system_prompt("You are a Rust expert")
            .with_worktree(true)
    )
    .build()
    .await?;
```

Available config options:
- `with_model(name)` - Default model for all slots
- `with_effort(level)` - Effort: Min, Low, Medium, High, Max
- `with_budget_usd(amount)` - Total pool budget
- `with_permission_mode(mode)` - Permission defaults
- `with_system_prompt(text)` - Base system prompt
- `with_worktree(true)` - Enable Git worktree per slot

## Execution Patterns

### Single Task (Synchronous)

```rust
let result = pool.run("fix the bug in main.rs").await?;
println!("Output:\n{}", result.output);
println!("Spend: ${}", result.spend_usd);
```

Result includes:
- `output` - Claude's response
- `spend_usd` - Cost of this task
- `tokens_used` - Input and output tokens

### Async Task Submission

```rust
// Submit and get task ID immediately
let task_id = pool.submit("long-running analysis").await?;

// Do other work...

// Poll for result later
let result = pool.result(&task_id).await??;
```

### Parallel Fan-Out

Execute multiple prompts in parallel, all at once:

```rust
let prompts = vec![
    "write a poem",
    "write a haiku",
    "write a limerick",
];

let results = pool.fan_out(&prompts).await?;
for (i, result) in results.iter().enumerate() {
    println!("Result {}: {}", i, result.output);
}
```

All tasks run concurrently. Returns when all complete (or timeout).

### Sequential Chains with Failure Policies

Execute steps in order, with control over failures:

```rust
use claude_pool::{ChainStep, StepAction, StepFailurePolicy};

let steps = vec![
    ChainStep {
        name: "analyze".into(),
        action: StepAction::Prompt { prompt: "analyze the error".into() },
        config: None,
        failure_policy: StepFailurePolicy::default(),
        output_vars: Default::default(),
    },
    ChainStep {
        name: "fix".into(),
        action: StepAction::Prompt { prompt: "write a fix based on {previous_output}".into() },
        config: None,
        failure_policy: StepFailurePolicy { retries: 2, recovery_prompt: None },
        output_vars: Default::default(),
    },
];

let task_id = pool.submit_chain(steps, &skills, ChainOptions::default()).await?;
let result = pool.result(&task_id).await?;
```

Failure policies:
- **retries** - Number of retries before failing (default: 0)
- **recovery_prompt** - Optional prompt to run on failure instead of aborting

Access chain progress:
```rust
let progress = pool.chain_result(&chain_id).await?;
for step in progress.steps {
    println!("{}: {}", step.name, step.status);
}
```

## Skills System

Skills are reusable prompt templates that define how to approach a task. The pool discovers and references them by name in chains or direct calls.

### SKILL.md Format

Skills follow the [Agent Skills](https://agentskills.io) standard. Each skill lives in its own directory with a `SKILL.md` file:

```
.claude-pool/skills/
  code_review/
    SKILL.md          # Required: frontmatter + prompt
    scripts/          # Optional: bundled scripts
      lint.sh
    templates/        # Optional: templates
      report.md
    examples/         # Optional: examples
      input.py
```

The `SKILL.md` file contains YAML frontmatter followed by the prompt body:

```yaml
---
name: code_review
description: Review code for bugs and style issues
argument-hint: "<path> [criteria]"
allowed-tools: Read, Grep, Glob, Bash
metadata:
  arguments:
    - name: path
      description: File path to review
      required: true
    - name: criteria
      description: What to focus on (bugs, style, performance)
      required: false
---

Review the code at {path} for the following criteria: {criteria}

Report issues found with severity and suggestions.
```

Standard fields (`argument-hint`, `allowed-tools`) live at the top level.
Pool-specific extensions (`scope`, `arguments`, `config`) live under `metadata`.
Arguments are available as `{arg_name}` or `$ARGUMENTS` / `$0` / `$1` in the prompt.

### Skill Resolution

Skills are discovered in priority order (first match wins):

1. **Runtime skills** - Added via code (ephemeral, lost on restart)
2. **Project skills** - Loaded from `.claude-pool/skills/` (checked into repo)
3. **Global skills** - Loaded from `~/.claude-pool/skills/` (user-wide)
4. **Builtin skills** - Shipped with the pool binary

### CLAUDE_SKILL_DIR Substitution

Skills can reference supporting files using the `${CLAUDE_SKILL_DIR}` variable:

```
Run linting:
bash ${CLAUDE_SKILL_DIR}/scripts/lint.sh .

Generate report from template:
python -c "..." < ${CLAUDE_SKILL_DIR}/templates/report.md
```

The variable resolves to the skill's directory path at render time. Available for project and global skills only (not builtins or runtime skills).

### Using Skills in Chains

Reference skills in chain steps:

```rust
use claude_pool::{ChainStep, StepAction};

let steps = vec![
    ChainStep {
        name: "review".into(),
        action: StepAction::Skill {
            skill: "code_review".into(),
            arguments: [
                ("path", "src/main.rs"),
                ("criteria", "performance"),
            ].iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
        },
        config: None,
        failure_policy: Default::default(),
        output_vars: Default::default(),
    },
];
```

### Programmatic Registration

Register skills at runtime:

```rust
use claude_pool::{Skill, SkillArgument, SkillRegistry, SkillSource};

let mut registry = SkillRegistry::new();
registry.register(
    Skill {
        name: "code_review".to_string(),
        description: "Review code for bugs and style".to_string(),
        prompt: "Review the code at {path} for {criteria}".to_string(),
        arguments: vec![
            SkillArgument {
                name: "path".to_string(),
                description: "File to review".to_string(),
                required: true,
            },
        ],
        config: None,
        scope: Default::default(),
        argument_hint: Some("<path> [criteria]".to_string()),
        skill_dir: None,
    },
    SkillSource::Runtime,
);
```

## Worktree Isolation

Enable optional Git worktree per slot for safe, isolated execution:

```rust
let pool = Pool::builder(claude)
    .slots(4)
    .config(
        PoolConfig::default()
            .with_worktree(true)
    )
    .build()
    .await?;
```

Each slot gets an isolated worktree:
- Independent filesystem
- Safe for parallel edits
- Cleanup on drain

Benefits:
- Parallel file edits without conflicts
- Isolated git state
- Safe cleanup

## Quality Gates

The pool supports a human-in-the-loop review workflow. Tasks submitted with
`submit_with_review` transition to `PendingReview` on completion instead of
`Completed`, allowing a coordinator to inspect results before accepting them.

```rust
// Submit a task that requires approval before it's considered done.
let task_id = pool.submit_with_review(
    "refactor the auth module",
    None,           // optional SlotConfig override
    vec![],         // tags
    Some(3),        // max_rejections (default: 3)
).await?;

// ... task runs, completes, enters PendingReview ...

// Inspect the result.
let result = pool.result(&task_id).await?;

// Approve: transitions PendingReview -> Completed.
pool.approve_result(&task_id).await?;

// Or reject with feedback: re-queues the task with feedback appended
// to the original prompt. Fails after max_rejections.
pool.reject_result(&task_id, "missing error handling for timeout case").await?;
```

### Via MCP tools

The same workflow is available through the MCP server:

- `pool_submit_with_review` -- submit a task requiring approval
- `pool_approve_result` -- accept the result
- `pool_reject_result` -- reject with feedback, task re-runs

### Task states

```
Pending -> Running -> PendingReview -> Completed  (approved)
                          |
                          +-> Running  (rejected, re-queued with feedback)
                          |
                          +-> Failed   (max rejections reached)
```

Rejection appends feedback to the original prompt so the slot sees what went
wrong and can address it on the next attempt.

## Slot Lifecycle

### Spawning

Slots are created during `build()` and remain alive until `drain()`.

### Session Resumption

Slots automatically resume sessions if available, reducing startup cost.

### Graceful Shutdown

```rust
let summary = pool.drain().await?;
println!("Processed {} tasks", summary.total_tasks);
println!("Total spend: ${}", summary.total_spend_usd);
println!("Errors: {}", summary.error_count);
```

All pending tasks are cancelled. Active tasks complete gracefully.

## Status & Monitoring

Get current pool state:

```rust
let status = pool.status().await?;
println!("Slots: {}", status.slots.len());
println!("Active tasks: {}", status.active_tasks);
println!("Budget: ${} / ${}", status.spend_usd, status.budget_usd);
println!("Remaining: ${}", status.budget_usd - status.spend_usd);
```

Status includes:
- Slot list with ID, status, and active task count
- Active and pending task counts
- Total spend and budget
- Budget remaining

## Error Handling

All operations return `Result<T>`:

```rust
use claude_pool::Error;

match pool.run("task").await {
    Ok(result) => println!("{}", result.output),
    Err(Error::TaskFailed(msg)) => eprintln!("Task error: {}", msg),
    Err(Error::BudgetExceeded) => eprintln!("Out of budget"),
    Err(Error::NoSlotsAvailable) => eprintln!("All slots busy"),
    Err(e) => eprintln!("Other error: {}", e),
}
```

Common errors:
- `TaskFailed` - Task execution failed
- `BudgetExceeded` - Pool exceeded spending cap
- `NoSlotsAvailable` - All slots busy/offline
- `TaskNotFound` - Invalid task ID

## Feature Flags

Currently no optional features. The crate includes full functionality by default.

Future features may include:
- `redis-store` - Redis backend for distributed pool state
- `prometheus` - Metrics export for monitoring

## API Documentation

For detailed API documentation, see [docs.rs/claude-pool](https://docs.rs/claude-pool).

## Testing

Requires the `claude` CLI binary:

```bash
cargo test --lib --all-features
```

## License

MIT OR Apache-2.0