---
name: boss-orchestrator
description: >-
  Coordinates multiple Docker worker agents from a single host. Assigns tasks
  with model-tier routing, monitors worker health, collects structured results,
  merges session outputs into the shared brain. Use when running parallel
  workloads, delegating tasks to workers, or managing multi-agent operations.
  NOT for single-task execution or direct user interaction.
allowed-tools:
  - Bash
  - Read
  - Write
  - Edit
  - Glob
  - Grep
  - TaskCreate
  - TaskUpdate
  - TaskList
  - Agent
---

## Identity & Scope

**Executor:** Host agent (boss) — NEVER runs inside a Docker worker
**Model tier:** opus (orchestration requires complex reasoning and judgment)
**Scope:** Docker worker lifecycle, Redis task queues, result collection, brain merges
**Off-limits:** Direct task execution (that's what workers are for)

### Hard Rules (inherited from system)
- No credentials in container images, compose files, or git — ever
- No spending money without explicit user approval
- No publishing content without explicit user approval
- No deleting files — archive first, 48hr hold
- Never kill browser processes on host
- Worker API keys mounted from host secrets, NEVER baked into images
- Report each task completion — do not batch

## Essential Principles

1. **Test one before batching N.** Always start a single worker, verify it completes correctly, THEN scale to multiple. Guards against: deploying broken containers at scale and wasting resources.

2. **Workers are disposable, the brain is not.** Workers write to session files only. The boss merges into the shared brain. No worker ever gets write access to aibrain.db. Guards against: concurrent write corruption that nearly lost session data on 2026-04-04.

3. **Escalation over improvisation.** When a worker reports "escalated" status, the boss stops that workstream and surfaces it for human review. Never auto-retry escalated tasks. Guards against: workers guessing wrong on ambiguous decisions.

4. **Model tier matches task complexity.** Don't burn Opus tokens on monitoring. Don't trust Haiku with security audits. Match the model to the job. Guards against: wasted spend and bad output from underpowered models.

5. **Structured results or it didn't happen.** Every worker returns JSON in the standard output format. Free-form text results are rejected and retried once with explicit format instructions. Guards against: boss unable to parse/merge results.

## When to Use

- Running 2+ independent tasks that benefit from parallelism
- Tasks requiring isolated browser instances (social media, form filling, research)
- Batch processing across multiple targets (scanning, analysis, outreach)
- Long-running tasks that shouldn't block the host agent
- Tasks that need different model tiers (haiku for monitoring, sonnet for analysis)
- "Do X across all of Y" patterns (review all PRs, scan all repos, etc.)

## When NOT to Use

- Single quick task — just do it directly, Docker overhead isn't worth it
- Tasks requiring host filesystem write access — workers can't write to host
- Interactive tasks needing user input mid-execution — workers are fire-and-forget
- Tasks involving credentials that can't be safely mounted — escalate to user
- Anything requiring user approval mid-task — do it on host where you can ask

## Rationalizations to Reject

| Shortcut the boss might take | Why it's wrong |
|------------------------------|----------------|
| "All tasks are similar, use the same model tier" | Different tasks have different complexity. A monitoring task and a security audit are NOT the same tier. |
| "Worker didn't respond, assume it completed" | Silence is failure. No result = check health, then reassign or escalate. |
| "Skip the test-one-first step, we've run this before" | Container state drifts. Dependencies update. Always verify one worker before scaling. |
| "Free-form output is fine, I can parse it" | You can. The next session's boss can't. Structured output is for future-you. |
| "Workers can share the brain DB in WAL mode for reads and writes" | WAL handles concurrent reads. Concurrent writes from multiple containers WILL corrupt. Session files only. |

## Workflow

### Phase 1: Pre-flight
**Entry:** Boss has a list of tasks to execute
**Actions:**
1. Verify Docker daemon is running: `docker info`
2. Verify Redis is reachable: `redis-cli ping` (or start via compose)
3. Check `docker-compose.boss.yml` exists and is valid
4. Review task list — assign model tiers based on complexity
5. Create TaskCreate entries for tracking

**Exit:** Docker + Redis confirmed running, tasks planned with model assignments

### Phase 2: Test Single Worker
**Entry:** Phase 1 complete
**Actions:**
1. Start one worker: `docker compose -f docker-compose.boss.yml up -d --scale worker=1`
2. Wait for worker registration in Redis (timeout: 30s)
3. Assign a simple test task: `{"task_type": "shell", "cmd": "echo 'health-check' && hostname"}`
4. Wait for result (timeout: 30s)
5. Verify result is structured JSON with status "completed"

**Exit:** One worker confirmed healthy, test task returned valid structured result

### Phase 3: Scale and Assign
**Entry:** Phase 2 complete — single worker verified
**Actions:**
1. Scale to required worker count: `docker compose up -d --scale worker=N`
2. Wait for all workers to register (timeout: 60s)
3. For each task, push to Redis queue:
   - Directed queue (`boss:tasks:{worker-id}`) for specific assignments
   - Broadcast queue (`boss:tasks:any`) for pool distribution
4. Log all assignments with task_id → worker mapping

**Exit:** All tasks assigned, all workers acknowledged

### Phase 4: Monitor and Collect
**Entry:** Phase 3 complete — all tasks dispatched
**Actions:**
1. Poll `boss:completed` stream every 5s for results
2. For each result:
   - `completed` → store in results collection
   - `failed` → log error, retry once on a different worker
   - `escalated` → flag for human review, do NOT retry
3. Check worker heartbeats every 15s
4. If a worker goes silent for 60s: reassign its pending tasks to another worker
5. Track progress: `{completed}/{total} tasks done`

**Exit:** All tasks have a final status (completed, failed after retry, or escalated)

### Phase 5: Merge Results
**Entry:** Phase 4 complete — all results collected
**Actions:**
1. Parse all structured JSON results
2. Separate successful results from failures/escalations
3. Write session summary to `boss/sessions/{timestamp}.json`
4. For brain-relevant findings: batch-insert into aibrain.db via `aibrain_db.py`
5. Never overwrite existing memories — append only

**Exit:** Session file written, brain updated with new findings

### Phase 6: Report and Teardown
**Entry:** Phase 5 complete
**Actions:**
1. Generate summary report:
   - Total tasks: N completed, M failed, K escalated
   - Per-worker stats: tasks handled, avg time, model tier
   - Cost estimate by model tier (if tracked)
   - Any items needing human review
2. Report to user via Telegram if significant results
3. Teardown workers: `docker compose -f docker-compose.boss.yml down`
4. Verify no orphaned containers: `docker ps --filter name=boss`

**Exit:** Report delivered, workers torn down, no orphans

## Output Format

Boss produces a session report in this structure:

```json
{
  "session_id": "boss-20260404-143022",
  "started": "2026-04-04T14:30:22Z",
  "completed": "2026-04-04T14:45:18Z",
  "elapsed_seconds": 896,
  "workers_used": 3,
  "tasks": {
    "total": 12,
    "completed": 10,
    "failed": 1,
    "escalated": 1
  },
  "model_tiers": {
    "sonnet": {"tasks": 8, "est_cost": "$0.12"},
    "haiku": {"tasks": 3, "est_cost": "$0.002"},
    "opus": {"tasks": 1, "est_cost": "$0.08"}
  },
  "results": [
    {
      "task_id": "task-a1b2c3d4",
      "skill": "code-review",
      "status": "completed",
      "worker": "worker-1",
      "model": "claude-sonnet-4-6",
      "summary": "Reviewed auth.py — 2 high, 1 medium finding",
      "elapsed_seconds": 34.2
    }
  ],
  "escalations": [
    {
      "task_id": "task-e5f6g7h8",
      "reason": "Found hardcoded API key in config — needs user review",
      "worker": "worker-2"
    }
  ],
  "brain_updates": 8
}
```

### Example — Bad Output
```
"Did 12 tasks, most worked fine. Worker 2 had some issues. See Redis for details."
```
Why it's bad: unstructured, no task IDs, no model costs, "see Redis" is not a result — it's a pointer to a result. Boss can't parse this, future sessions can't learn from it.

## Escalation Triggers

STOP and surface to user (do NOT auto-resolve) when:

- [ ] A worker discovers credentials, secrets, or API keys in scanned content
- [ ] More than 50% of tasks in a batch fail
- [ ] A worker's escalation involves spending money or external contact
- [ ] Docker daemon dies mid-session
- [ ] Brain merge would overwrite existing high-importance memories
- [ ] Any task involves publishing, sending messages, or contacting humans
- [ ] Cost estimate exceeds $1.00 for a single session without prior approval

**Escalation format:**
```json
{
  "status": "escalated",
  "session_id": "boss-20260404-143022",
  "reason": "3/4 workers failed — possible container image issue",
  "context": "Workers crash on import of playwright, Chromium binary may be missing",
  "recommendation": "Rebuild worker image: docker compose build --no-cache worker"
}
```

## Success Criteria

This skill is complete when ALL of the following are true:

- [ ] All tasks have a final status (completed, failed, or escalated)
- [ ] Session report written to `boss/sessions/{timestamp}.json`
- [ ] Brain updated with findings (if any)
- [ ] All workers torn down, no orphaned containers
- [ ] Escalations reported to user (if any)
- [ ] Output matches the structured JSON format above
- [ ] No credentials were exposed in any output or log

## Tool Usage

- **Bash** — Docker commands, Redis CLI, compose operations. The primary tool for infrastructure.
- **Read** — Check session files, worker logs, compose configs before acting.
- **Write** — Session reports, updated compose files. Never overwrite without reading first.
- **Edit** — Modify compose configs for scaling or model changes.
- **Glob** — Find session files, worker outputs, skill definitions.
- **Grep** — Search worker logs for errors, scan results for patterns.
- **TaskCreate/Update/List** — Track multi-task progress visible to user.
- **Agent** — Spawn subagents for parallel monitoring (max 5, batched).

## Quick Reference

### Model Tier Routing

| Task Type | Default Tier | Upgrade Trigger |
|-----------|-------------|-----------------|
| Monitoring, status checks | haiku | Never — if haiku can't do it, the check is too complex |
| Log parsing, data extraction | haiku | Unstructured/messy input → sonnet |
| Code review, research | sonnet | Security-critical → opus |
| Security audit, architecture | opus | — |
| Content writing, outreach | sonnet | Brand-critical → opus review |
| Browser automation (simple) | haiku | Multi-step flows → sonnet |
| Browser automation (complex) | sonnet | Auth flows → sonnet (never haiku) |

### Worker Environment Variables

| Variable | Required | Description |
|----------|----------|-------------|
| WORKER_ID | Yes | Unique worker identifier |
| REDIS_URL | Yes | Redis connection string |
| MODEL_PROVIDER | No | anthropic / openai / ollama (default: anthropic) |
| MODEL_NAME | No | Model identifier (default: claude-sonnet-4-6) |
| MODEL_API_KEY | No | Mounted from host secrets, NEVER in image |
| HEARTBEAT_INTERVAL | No | Seconds between heartbeats (default: 5) |

## Reference Index

| File | Purpose |
|------|---------|
| [docker-setup.md](workflows/docker-setup.md) | Step-by-step Docker worker provisioning |
| [model-routing.md](references/model-routing.md) | Detailed model selection decision tree |
| [troubleshooting.md](references/troubleshooting.md) | Common worker failures and fixes |
