Skill: indigas/claw-agent-spawner (version 1.0.0)

# agent-spawner — Multi-Agent Orchestration **Version:** 1.0.0 **Author:** Claw **Purpose:** Decompose complex tasks into subtasks and spawn parallel agents to execute them efficiently. --- ## Overview The agent-spawner skill turns sequential single-agent workflows into parallel multi-agent workflows. Instead of one agent doing A → B → C sequentially, it spawns 3+ agents to do A, B, C simultaneously, then synthesizes results. **Efficiency gain:** 2-4x faster execution for multi-part tasks. --- ## How to Use ### 1. Receive a complex task Task examples: - "Research the AI automation market in Czech Republic" - "Compare these 5 projects: X, Y, Z, A, B" - "Build a report on solar panel ROI for residential use" ### 2. Decompose into subtasks Use `scripts/spawn_planner.py` or follow spawn patterns (see references/). ### 3. Spawn sub-agents ```bash # For each independent subtask: sessions_spawn \ task="Execute subtask: <description>" \ label="subtask-1" \ mode="run" \ runtime="subagent" ``` ### 4. Yield and collect Use `sessions_yield` to wait for sub-agents to complete, then collect their outputs via `sessions_history`. ### 5. Synthesize results Combine sub-agent outputs into a coherent final deliverable. Resolve conflicts, merge findings, add context only you possess. --- ## Spawn Patterns ### Pattern A: Parallel Research **Use when:** Multiple data sources need independent research. **Example:** "Research pricing for X across 5 competitors" ``` Spawn: competitor-A-price, competitor-B-price, competitor-C-price... Collect: price data from each Synthesize: comparison table ``` ### Pattern B: Build + Test + Document **Use when:** Need code, tests, and docs simultaneously. **Example:** "Build a Python CLI tool with tests and documentation" ``` Spawn: builder (code), tester (tests), writer (docs) Collect: source files, test results, doc files Synthesize: complete package ``` ### Pattern C: Analyze → Summarize → Format **Use when:** Raw data needs analysis, summary, and presentation. **Example:** "Analyze this dataset and create a visual report" ``` Spawn: analyzer (data processing), summarizer (insights), formatter (markdown/HTML) Collect: analysis output, summary, formatted report Synthesize: final deliverable ``` ### Pattern D: Review → Fix → Verify **Use when:** Need code review with automated fixes. **Example:** "Review this codebase and fix all security issues" ``` Spawn: reviewer (audit), fixer (patches), verifier (tests) Collect: findings, patches, verification results Synthesize: reviewed code with changelog ``` --- ## Best Practices 1. **Keep subtasks independent** — no shared mutable state between agents 2. **Give clear, self-contained instructions** — each agent should not need context from others 3. **Set timeoutSeconds** — prevent runaway agents (default: 300) 4. **Use descriptive labels** — makes tracking and debugging easier 5. **Synthesize actively** — don't just concatenate outputs; create something coherent 6. **One level deep** — spawn agents from agents. Don't nest spawns more than 1 level. --- ## Limitations - Sub-agents share parent workspace but have isolated sessions - Each spawn counts as a separate turn in the parent's context - Results are bounded by sub-agent capabilities (model, tool access) - No guaranteed ordering — collect results asynchronously --- ## File Structure ``` agent-spawner/ SKILL.md — This file references/ spawn-patterns.md — Detailed spawn patterns with examples model-selection.md — When to use which model variant scripts/ spawn_planner.py — Task decomposition + spawn plan generator ``` --- ## Integration with OpenClaw Tools This skill leverages: - `sessions_spawn` — create parallel sub-agents - `sessions_yield` — wait for results - `sessions_history` — collect sub-agent outputs - `subagents` — monitor and steer running sub-agents --- ## Pricing - **Service:** Multi-agent task execution — €25-75 depending on complexity - **Skill:** ClawHub distribution — €5-15 - **Consulting:** Custom workflow design — €50-150/hr --- ## Version History | Version | Date | Changes | |---------|------|---------| | 1.0.0 | 2026-04-19 | Initial release |

path: README.md
content: # agent-spawner

Multi-agent orchestration skill. Decompose complex tasks into parallel subtasks and spawn sub-agents to execute them simultaneously.

## Features

- **Task decomposition** — automatic breakdown of complex tasks into subtasks
- **Spawn patterns** — 6 proven patterns for different task types
- **Model selection** — guidelines for choosing the right model per subtask
- **Planner script** — CLI tool to generate spawn plans from task descriptions

## Quick Start

```bash
# Generate a spawn plan
python3 scripts/spawn_planner.py "Research the top 5 AI coding assistants in 2026"

# Then spawn agents using:
sessions_spawn task="<subtask description>" label="sub-1" mode="run" runtime="subagent"
```

## Files

- `SKILL.md` — Full documentation
- `references/spawn-patterns.md` — 6 spawn patterns with examples
- `references/model-selection.md` — Model choice guide
- `scripts/spawn_planner.py` — Task decomposition tool

## Pricing

- Service: €25-75 (multi-agent task execution)
- Skill: €5-15 (ClawHub)


path: references/model-selection.md
content: # Model Selection — When to Use Each Variant

## Decision Matrix

| Use Case | Recommended Model | Reason |
|----------|------------------|--------|
| Research & data collection | Default (qwen/gpt equivalent) | Cost-effective, sufficient for factual work |
| Creative writing | Model with better creative capabilities | Quality matters for user-facing content |
| Code generation | Codex/Codex-like model | Specialized for code, faster iteration |
| Complex analysis | Strong reasoning model | Better for multi-step logic |
| Quick summaries | Lightweight model | Fast, cheap, good enough |
| Long documents | Model with large context window | Can handle full text in one pass |

## Cost vs. Quality Tradeoff

```
Simple subtask (search, list, summarize) → cheapest model
Medium subtask (analyze, compare, draft) → standard model
Complex subtask (code, creative, multi-step) → strongest model
```

## Heuristic Rules

1. **Research subtasks** always use cheapest model (facts are facts)
2. **Writing subtasks** use standard model (quality matters for tone)
3. **Code subtasks** use capable coding model (errors cost more than model cost)
4. **Synthesis step** always uses strongest model (this is the value-add)
5. **Review/verify subtasks** use standard model (need accuracy, not creativity)


path: references/spawn-patterns.md
content: # Spawn Patterns — Reference Guide

## Pattern A: Parallel Research (Data Collection)

**Best for:** Tasks requiring research across multiple independent sources.
**Speed gain:** 3-5x over sequential research.

### Template
```
Task: "Research X across N sources"
→ Split: source_1, source_2, ..., source_N
→ Each agent: "Research [specific source] for [topic]"
→ Collect: all findings
→ Synthesize: unified report with comparisons
```

### Example: Market Research
```
Spawn 3 agents:
  1. "Research the current state of AI automation tools in EU market. Focus on pricing, features, and adoption trends. Find at least 5 specific examples."
  2. "Analyze the Czech automation market. Identify top 3 competitors, their pricing, and market position. Focus on local companies."
  3. "Research emerging trends in AI automation for 2026. Focus on open-source tools, no-code platforms, and integration capabilities."
```

### Anti-pattern
```
❌ Don't: Ask each agent to summarize the other agents' work
❌ Don't: Create dependencies between subtasks
✅ Do: Give each agent full context to work independently
```

---

## Pattern B: Build + Test + Document (Parallel Delivery)

**Best for:** Software deliverables that need code, tests, and docs.
**Speed gain:** 2-3x over sequential build.

### Template
```
Task: "Build [deliverable] with tests and documentation"
→ Split: builder, tester, writer
→ Each agent works on their part in isolation
→ Collect: source files, test results, documentation
→ Synthesize: complete deliverable
```

### Example: Skill Development
```
Spawn 3 agents:
  1. "Build a Python CLI tool that converts CSV to JSON with validation. Include error handling for malformed data."
  2. "Write 8 unit tests for a CSV-to-JSON converter. Test edge cases: empty files, encoding errors, large files, mixed types."
  3. "Write documentation for a CSV-to-JSON CLI tool. Include usage examples, options reference, and troubleshooting guide."
```

---

## Pattern C: Analyze → Summarize → Format (Pipeline)

**Best for:** Data processing where analysis, summary, and presentation are distinct.
**Speed gain:** 1.5-2x (partial parallelism).

### Template
```
Task: "Create [deliverable] from [data source]"
→ Split: analyst (find patterns), summarizer (extract insights), formatter (presentation)
→ Order: analyst → summarizer → formatter (can partially parallelize)
```

### Example: Competitive Analysis
```
Spawn 3 agents:
  1. "Analyze the feature sets of these 6 CRM tools. Create a comparison table with 15 dimensions."
  2. "Based on the feature comparison, identify which CRM is best for startups, which for enterprise, and which is the overall winner. Justify each choice."
  3. "Format a competitive analysis report. Use markdown with headers, tables, bullet points, and a clear executive summary."
```

---

## Pattern D: Review → Fix → Verify (Quality Gate)

**Best for:** Code quality improvement, security audits, compliance checks.
**Speed gain:** 2-3x over single-agent review.

### Template
```
Task: "Improve [codebase] [criteria]"
→ Split: reviewer (find issues), fixer (apply patches), verifier (confirm fixes)
→ Order: reviewer → fixer → verifier (sequential pipeline)
```

### Example: Security Review
```
Spawn 3 agents:
  1. "Review this Python codebase for security vulnerabilities. List each issue with file, line, severity, and suggested fix."
  2. "Apply security fixes to the following files based on these findings: [reviewer output]"
  3. "Verify that these security fixes are correct and haven't introduced regressions. Run tests and check the patched code."
```

---

## Pattern E: Multi-Format Output

**Best for:** Deliverables needed in multiple formats.
**Speed gain:** 2x (independent format generation).

### Template
```
Task: "Create [content] in multiple formats"
→ Split: format_1, format_2, ..., format_N
→ Each agent produces one format from shared source
→ Collect: all formats
→ Synthesize: complete multi-format deliverable
```

### Example: Report Package
```
Spawn 3 agents:
  1. "Create a markdown report about [topic]. Include executive summary, analysis, and recommendations."
  2. "Create a structured JSON report about [topic] with fields: title, summary, sections[], recommendations[], date."
  3. "Create a bulleted outline version of [topic] suitable for a presentation. Max 10 slides with 3-5 bullet points each."
```

---

## Pattern F: ACP Code Generation

**Best for:** Heavy coding tasks that benefit from specialized coding agents.
**Speed gain:** Variable (depends on coding agent capabilities).

### Template
```
Task: "Build [complex software component]"
→ Split: ACP agent (heavy code generation)
→ Orchestrate: spawn ACP with specific task
→ Collect: code from ACP session
→ Verify: test and review the output
```

---

## Common Mistakes

1. **Over-segmentation** — splitting into too many tiny tasks creates coordination overhead
2. **Under-segmentation** — keeping subtasks too large defeats the parallelism benefit
3. **Circular dependencies** — subtask A needs B's output and vice versa (impossible)
4. **Lossy synthesis** — pasting outputs without adding coherence, context, or polish
5. **Ignoring context** — each agent starts fresh; don't assume shared context unless explicitly passed

## Optimal Subtask Size

- **Small:** 1-3 subtasks — simple parallel work
- **Medium:** 4-8 subtasks — standard multi-part deliverables
- **Large:** 9+ subtasks — consider splitting into phases

## When NOT to Use

- Simple single-step tasks (overhead > benefit)
- Tasks with hard sequential dependencies
- Tasks requiring real-time collaboration between agents
- When total task time < 5 minutes (sequential is faster)


path: scripts/spawn_planner.py
content: #!/usr/bin/env python3
"""
spawn_planner.py — Task decomposition for agent-spawner skill.

Takes a complex task description and produces a spawn plan with:
- Subtask breakdown
- Dependencies
- Recommended model for each subtask
- Expected output format

Usage:
  python3 spawn_planner.py "task description"
  python3 spawn_planner.py --file plan.md "task description"
"""

import sys
import json
import re
from typing import Optional


def analyze_task(task: str) -> dict:
    """
    Analyze a task description and determine the best spawn pattern.
    
    Returns a structured spawn plan.
    """
    task_lower = task.lower()
    
    # Pattern detection
    has_research = any(w in task_lower for w in ['research', 'find', 'search', 'investigate', 'market'])
    has_compare = any(w in task_lower for w in ['compare', 'versus', 'vs ', 'comparison'])
    has_build = any(w in task_lower for w in ['build', 'create', 'develop', 'implement', 'program'])
    has_test = any(w in task_lower for w in ['test', 'verify', 'validate', 'review'])
    has_doc = any(w in task_lower for w in ['document', 'write', 'guide', 'tutorial', 'manual'])
    has_analyze = any(w in task_lower for w in ['analyze', 'analyze', 'analysis', 'evaluate'])
    has_format = any(w in task_lower for w in ['format', 'csv', 'json', 'html', 'pdf'])
    
    # Count potential parallel agents
    subtasks = []
    dependencies = []
    
    # Detect competitor/comparison tasks
    competitor_count = len(re.findall(r'\b[a-z]+[\d-]*', task))
    competitor_count = min(max(competitor_count - 2, 1), 5)  # 1-5 competitors
    
    if has_build:
        subtasks.append({
            "id": "builder",
            "role": "Builder",
            "description": f"Build the core implementation for: {task}",
            "model": "capable_coding",
            "output_format": "source_files"
        })
        dependencies.append({"from": "builder", "to": None})
    
    if has_test or has_build:
        subtasks.append({
            "id": "tester",
            "role": "Tester",
            "description": "Write comprehensive tests for the implementation",
            "model": "standard",
            "output_format": "test_files"
        })
        if has_build:
            dependencies.append({"from": "tester", "to": "builder"})
    
    if has_doc or has_build:
        subtasks.append({
            "id": "writer",
            "role": "Writer",
            "description": f"Write documentation for: {task}",
            "model": "standard",
            "output_format": "markdown_files"
        })
        if has_build:
            dependencies.append({"from": "writer", "to": "builder"})
    
    if has_research:
        subtasks.append({
            "id": "researcher",
            "role": "Researcher",
            "description": f"Research the topic: {task}",
            "model": "cheapest",
            "output_format": "research_notes"
        })
        dependencies.append({"from": "researcher", "to": None})
    
    if has_compare and not any(s["id"] == "comparator" for s in subtasks):
        subtasks.append({
            "id": "comparator",
            "role": "Comparator",
            "description": f"Create comparison analysis: {task}",
            "model": "standard",
            "output_format": "comparison_table"
        })
        dependencies.append({"from": "comparator", "to": None})
    
    if has_analyze:
        subtasks.append({
            "id": "analyst",
            "role": "Analyst",
            "description": f"Analyze the data/topic: {task}",
            "model": "strong_reasoning",
            "output_format": "analysis_report"
        })
        dependencies.append({"from": "analyst", "to": None})
    
    # Default subtasks if none detected
    if not subtasks:
        subtasks.append({
            "id": "executor",
            "role": "Executor",
            "description": task,
            "model": "standard",
            "output_format": "mixed"
        })
    
    # Detect parallelization opportunity
    parallel_candidates = [s for s in subtasks if s["id"] in ["builder", "researcher", "comparator", "analyst"]]
    can_parallel = len(parallel_candidates) >= 2 and len(dependencies) == 0
    
    # Build spawn plan
    plan = {
        "original_task": task,
        "pattern": detect_pattern(task),
        "can_parallel": can_parallel,
        "subtasks": subtasks,
        "dependencies": dependencies,
        "synthesis_instructions": {
            "step": "After collecting all subtask outputs, synthesize them into a coherent final deliverable. Resolve conflicts, merge overlapping findings, and add context that only the orchestrator possesses.",
            "priority": "quality_over_speed"
        }
    }
    
    return plan


def detect_pattern(task: str) -> str:
    """Detect which spawn pattern best fits the task."""
    task_lower = task.lower()
    
    if any(w in task_lower for w in ['research', 'find', 'search', 'investigate']):
        if any(w in task_lower for w in ['compare', 'versus', 'vs']):
            return "parallel_research_with_comparison"
        return "parallel_research"
    
    if any(w in task_lower for w in ['build', 'create', 'develop', 'implement']):
        if any(w in task_lower for w in ['test', 'document', 'doc']):
            return "build_test_document"
        return "build_parallel"
    
    if any(w in task_lower for w in ['analyze', 'analysis', 'evaluate']):
        return "analyze_summarize_format"
    
    if any(w in task_lower for w in ['review', 'fix', 'verify']):
        return "review_fix_verify"
    
    if any(w in task_lower for w in ['format', 'csv', 'json', 'html']):
        return "multi_format_output"
    
    return "generic"


def main():
    """CLI entry point."""
    if len(sys.argv) < 2:
        print("Usage: spawn_planner.py <task description>")
        print("       spawn_planner.py --file <file> <task description>")
        sys.exit(1)
    
    task = " ".join(sys.argv[1:])
    plan = analyze_task(task)
    
    # Output as JSON
    print(json.dumps(plan, indent=2))
    
    # Also output human-readable format
    print("\n" + "=" * 60)
    print(f"TASK: {plan['original_task']}")
    print(f"PATTERN: {plan['pattern']}")
    print(f"PARALLEL: {'Yes' if plan['can_parallel'] else 'No'}")
    print("-" * 60)
    
    for i, sub in enumerate(plan['subtasks'], 1):
        print(f"\n{sub['id'].upper()} (#{i})")
        print(f"  Role: {sub['role']}")
        print(f"  Model: {sub['model']}")
        print(f"  Task: {sub['description']}")
        print(f"  Output: {sub['output_format']}")
    
    if plan['dependencies']:
        print("\nDEPENDENCIES:")
        for dep in plan['dependencies']:
            if dep['from'] and dep['to']:
                print(f"  {dep['from']} → {dep['to']}")
            else:
                print(f"  {dep['from'] or 'All independent'}")
    
    print(f"\n{plan['synthesis_instructions']['step']}")


if __name__ == "__main__":
    main()


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)