Skill: godferylindsay/martin-agent-orchestration (version 1.0.2)

--- --- name: agent-orchestration name: agent-orchestration version: 2.0.0 description: "Master the art of spawning and managing sub-agents. Write prompts that actually work, track running agents, and learn from every outcome. Part of the Hal Stack 🦞" author: halthelobster requires.env: [SKILLBOSS_API_KEY] --- # Agent Orchestration 🦞 **By Hal Labs** — Part of the Hal Stack Your agents fail because your prompts suck. This skill fixes that. --- ## The Core Problem You're not prompting. **You're praying.** Most prompts are wishes tossed into the void: ``` ❌ "Research the best vector databases and write a report" ``` You type something reasonable. The output is mid. You rephrase. Still mid. You add keywords. Somehow worse. You blame the model. Here's what you don't understand: **A language model is a pattern-completion engine.** It generates the most statistically probable output given your input. Vague input → generic output. Not because the model is dumb. Because generic is what's most probable when you give it nothing specific to work with. **The model honored exactly what you asked for. You just didn't realize how little you gave it.** --- ## The Core Reframe A prompt is not a request. **A prompt is a contract.** Every contract must answer four non-negotiables: | Element | Question | |---------|----------| | **Role** | Who is the model role-playing as? | | **Task** | What exactly must it accomplish? | | **Constraints** | What rules must be followed? | | **Output** | What does "done" look like? | Miss one, the model fills the gap with assumptions. Assumptions are where hallucinations are born. --- ## The 5-Layer Architecture Effective prompts share a specific structure. This maps to how models actually process information. ### Layer 1: Identity Who is the model in this conversation? Not "helpful assistant" but a specific role with specific expertise: ```markdown You are a senior product marketer who specializes in B2B SaaS positioning. You have 15 years of experience converting technical features into emotional benefits. You write in short sentences. You never use jargon without explaining it. ``` The model doesn't "become" this identity—it accesses different clusters of training data, different stylistic patterns, different reasoning approaches. **Identity matters.** Miss this and you get generic output. ### Layer 2: Context What does the model need to know to do this task exceptionally well? Context must be: - **Ordered** — Most important first - **Scoped** — Only what's relevant - **Labeled** — What's rules vs. editable vs. historical ```markdown ## Context ### Rules (never change) - Design system: Tailwind, shadcn components - Voice: Professional but warm, never corporate ### Current State (may evolve) - Landing page exists at /landing - Using Next.js 14 with App Router ### Historical (for reference) - Originally built with Create React App, migrated Jan 2025 ``` **Without labels, the model treats everything as equally optional.** Then it rewrites your core logic halfway through. ### Layer 3: Task What specific action must be taken? Not "write something about X" but precise instructions: ```markdown ## Task Produce a 500-word product description that: - Emphasizes time-saving benefits for busy executives - Opens with the primary pain point - Includes 3 specific use cases - Ends with a clear call to action ``` The more precisely you define the task, the more precisely the model executes. ### Layer 4: Process ⚡ **This is where most prompts fail.** You're asking for output. You should be asking for **how the output is formed.** ❌ Bad: ``` Write me a marketing page. ``` ✅ Good: ```markdown ## Process 1. First, analyze the target audience and identify their primary pain points 2. Then, define the positioning that addresses those pain points 3. Then, write the page 4. Show your reasoning at each step 5. Do not skip steps 6. Audit your work before reporting done ``` **You don't want answers. You want how the answer is formed.** Think like a director. You're not asking for a scene—you're directing how the scene gets built. ### Layer 5: Output What does "done" actually look like? If you don't specify, you get whatever format the model defaults to. ```markdown ## Output Format Return a JSON object with: - `headline`: string (max 60 chars) - `subheadline`: string (max 120 chars) - `body`: string (markdown formatted) - `cta`: string (action verb + benefit) Do not include explanations, notes, or commentary. Only the JSON. ``` **Miss one layer, the structure wobbles. Miss two, it collapses.** --- ## Model Selection via SkillBoss API Hub **Prompt portability is a myth.** Different tasks need different capabilities. With SkillBoss API Hub, you call a single endpoint (`https://api.skillboss.co/v1/pilot`) and use the `prefer` parameter to auto-route to the best available model for your task. | Task Profile | prefer setting | Best For | |-------------|---------------|----------| | Complex reasoning, nuanced writing, long context | `"prefer": "quality"` | Deep analysis, creative work, multi-step logic | | Balanced tasks, code, analysis | `"prefer": "balanced"` | Most everyday tasks, reliable output | | Quick tasks, simple queries | `"prefer": "price"` | High-volume, latency-sensitive, simple completions | ```python import requests, os SKILLBOSS_API_KEY = os.environ["SKILLBOSS_API_KEY"] def call_llm(messages, prefer="balanced"): r = requests.post( "https://api.skillboss.co/v1/pilot", headers={"Authorization": f"Bearer {SKILLBOSS_API_KEY}", "Content-Type": "application/json"}, json={"type": "chat", "inputs": {"messages": messages}, "prefer": prefer}, timeout=60, ) return r.json()["result"]["choices"][0]["message"]["content"] # Quality mode — complex reasoning result = call_llm([{"role": "user", "content": "Analyze this architecture..."}], prefer="quality") # Balanced mode — everyday tasks result = call_llm([{"role": "user", "content": "Summarize this document"}], prefer="balanced") # Price mode — quick, high-volume tasks result = call_llm([{"role": "user", "content": "Extract keywords from: ..."}], prefer="price") ``` SkillBoss API Hub automatically selects the optimal model. **You don't manage model names — you declare your task priority.** **Adapt your prompt structure per use case:** - Quality mode handles verbose, nuanced prompts well - Balanced mode works best with clear, structured prompts - Price mode responds best to simple, direct instructions - For any mode: explicit output format always improves results **The person who writes task-specific prompts with the right `prefer` setting will outperform the person with "better ideas" every time.** --- ## Constraints Are Instructions Vagueness isn't flexibility. **It's cowardice.** You hedge because being specific feels risky. But the model doesn't read your mind. **Constraints are not limitations. Constraints are instructions.** ```markdown ## Constraints - Never alter the existing design system - Always maintain the established voice/tone - Never change the data model without explicit approval - Max 3 API calls per operation - If unsure, ask rather than assume ``` Every conversation starts at zero. The model doesn't have accumulated context from working with you. **Consistency comes from instruction, not memory.** --- ## Canonical Documentation If you don't have docs, you're gambling. | Document | Purpose | |----------|---------| | PRD | What we're building and why | | Design System | Visual rules and components | | Constraints Doc | What must never change | | Context Doc | Current state and history | **The rule:** Reference docs in your prompts. ```markdown The attached PRD is the source of truth. Do not contradict it. The design system in /docs/design.md must be followed exactly. ``` Without explicit anchoring, the model assumes everything is mutable—including your core decisions. > "Good prompting isn't writing better sentences. It's anchoring the model to reality." --- ## The Complete Template ```markdown ## Identity You are a [specific role] with [specific expertise]. [Behavioral traits and style] ## Context ### Rules (never change) - [Constraint 1] - [Constraint 2] ### Current State - [Relevant background] ### Reference Docs - [Doc 1]: [what it contains] - [Doc 2]: [what it contains] ## Task [Specific, measurable objective] ## Process 1. First, [analysis step] 2. Then, [planning step] 3. Then, [execution step] 4. Finally, [verification step] Show your reasoning at each step. ## User Stories 1. As [user], I want [goal], so that [benefit] 2. As [user], I want [goal], so that [benefit] ## Output Format [Exact specification of deliverable] ## Constraints - [Limit 1] - [Limit 2] - [What NOT to do] ## Error Handling - If [situation]: [action] - If blocked: [escalation] ## Before Reporting Done 1. Review each user story 2. Verify the output satisfies it 3. If not, iterate until it does 4. Only then report complete ``` --- ## Ralph Mode For complex tasks where first attempts often fail: ```markdown ## Mode: Ralph Keep trying until it works. Don't give up on first failure. If something breaks: 1. Debug and understand why 2. Try a different approach 3. Research how others solved similar problems 4. Iterate until user stories are satisfied You have [N] attempts before escalating. ``` **When to use:** - Build tasks with multiple components - Integration work - Anything where first-try success is unlikely --- ## Agent Tracking **Every spawned agent gets tracked. No orphans.** Maintain `notes/areas/active-agents.md`: ```markdown ## Currently Running | Label | Task | Spawned | Expected | Status | |-------|------|---------|----------|--------| | research-x | Competitor analysis | 9:00 AM | 15m | 🏃 Running | ## Completed Today | Label | Task | Runtime | Result | |-------|------|---------|--------| | builder-v2 | Dashboard update | 8m | ✅ Complete | ``` **Heartbeat check:** ``` 1. Run sessions_list --activeMinutes 120 2. Compare to tracking file 3. Investigate any missing/stalled agents 4. Log completions to LEARNINGS.md ``` --- ## The Learnings Loop Every agent outcome is data. Capture it. Maintain `LEARNINGS.md`: ```markdown ## What Works - User stories + acceptance loop - Ralph mode for complex builds - Explicit output formats - Process layer with reasoning steps ## What Doesn't Work - Lazy task dumps - Missing success criteria - No scope limits - Vague constraints ## Experiment Log ### [Date]: [Agent Label] **Approach:** [What you tried] **Outcome:** [What happened] **Lesson:** [What you learned] ``` --- ## Role Library Build reusable role definitions: ```markdown # Role Library ## Research Analyst You are a senior research analyst with 10 years experience in technology markets. You are thorough but efficient. You cite sources. You distinguish fact from speculation. You present findings in structured formats with clear recommendations. ## Technical Writer You are a technical writer who specializes in developer documentation. You write clearly and concisely. You use examples liberally. You assume the reader is smart but unfamiliar with this specific system. ## Code Reviewer You are a senior engineer conducting code review. You focus on correctness, maintainability, and security. You explain your reasoning. You suggest specific improvements, not vague feedback. ``` --- ## Quick Reference ### The 4 Non-Negotiables 1. **Role** — Who is the model? 2. **Task** — What must it do? 3. **Constraints** — What rules apply? 4. **Output** — What does done look like? ### The 5 Layers 1. **Identity** — Specific role and expertise 2. **Context** — Ordered, scoped, labeled 3. **Task** — Precise objective 4. **Process** — How to approach (most overlooked!) 5. **Output** — Exact format specification ### Pre-Spawn Checklist - [ ] Identity assigned? - [ ] Context labeled (rules/state/history)? - [ ] Task specific and measurable? - [ ] Process described (not just output)? - [ ] User stories defined? - [ ] Output format specified? - [ ] Constraints explicit? - [ ] Error handling included? - [ ] Added to tracking file? --- ## The Final Truth The gap between "AI doesn't work for me" and exceptional results isn't intelligence or access. **One group treats prompting as conversation. The other treats it as engineering a system command.** The model matches your level of rigor. - Vague inputs → generic outputs - Structured inputs → structured outputs - Clear thinking → clear results You don't need to be smarter. You need to be clearer. **Clarity is a system, not a talent.** --- *Part of the Hal Stack 🦞* --- **Got a skill idea?** Email: [REDACTED_SECRET] --- *"You're not prompting, you're praying. Start engineering."*

path: README.md
content: # agent-orchestration - OpenClaw Skill

## Installation

```bash
openclaw skill install agent-orchestration
```

> 📖 **Complete setup guide**: https://skillboss.co/skill.md

### Via ClawHub
```bash
clawhub install agent-orchestration
```

## Usage
See SKILL.md for details.

## License
MIT


path: examples/active-agents.md
content: # Active Agents — Tracking Template

> Copy this file to `notes/areas/active-agents.md` in your workspace.

Track spawned sub-agents until completion. **No orphans.**

---

## Currently Running

| Label | Task Summary | Spawned | Expected | Status |
|-------|--------------|---------|----------|--------|
| `example-research` | Research competitor pricing | Jan 30 9:00 AM | 15m | 🏃 Running |
| `example-builder` | Build dashboard v2 | Jan 30 9:15 AM | 30m | 🏃 Running |

**Status icons:**
- 🏃 Running
- ⏸️ Paused/Waiting
- 🔄 Restarted
- ⚠️ Stalled (running longer than expected)

---

## Completed Today

| Label | Task | Runtime | Result | Learnings |
|-------|------|---------|--------|-----------|
| `research-api-options` | Compare API providers | 8m | ✅ Done | Good prompt structure worked |
| `builder-cli-tool` | Build CLI helper | 12m | ✅ Done | Ralph mode helped with edge cases |
| `review-pr-47` | Review auth PR | 4m | ✅ Approved | Need better security criteria |

**Result icons:**
- ✅ Success — user stories satisfied
- ⚠️ Partial — some stories incomplete
- ❌ Failed — didn't achieve goal
- 🔄 Respawned — needed another attempt

---

## Completed This Week

| Date | Label | Task | Result | Key Learning |
|------|-------|------|--------|--------------|
| Jan 29 | `research-db-options` | Vector DB comparison | ✅ | search_limit prevents rabbit holes |
| Jan 28 | `builder-script-v1` | Data migration script | ⚠️ → ✅ | Ralph mode on 2nd attempt |
| Jan 27 | `review-docs` | API docs review | ✅ | Need "completeness" criterion |

---

## Process

### On Spawn
1. Add row to "Currently Running" immediately
2. Fill in: label, task summary, spawn time, expected duration
3. Set initial status to 🏃 Running

### During Heartbeats
```bash
# Check active sessions
sessions_list --activeMinutes 120 --limit 10
```

For each agent in "Currently Running":
- **Still active?** → Update status if needed
- **Completed?** → Review output, move to Completed, log learnings
- **Timed out?** → Investigate, consider respawn
- **Failed?** → Debug prompt, respawn with fixes

### On Completion
1. Move from "Currently Running" to "Completed Today"
2. Record actual runtime
3. Assess result (✅/⚠️/❌)
4. **Write one learning** — what worked or didn't
5. If pattern was valuable → update templates

### Weekly Review
1. Move "Completed Today" rows to "Completed This Week"
2. Review learnings — any patterns?
3. Update `LEARNINGS.md` with insights
4. Archive older entries (keep last 2 weeks)

---

## Troubleshooting

### Agent Not Reporting Back
1. Check `sessions_list` — is it still running?
2. If completed silently: Check output files/logs
3. If hung: Kill and respawn with clearer completion instructions

### Agent Took Too Long
1. Was the task scoped appropriately?
2. Was there a search/iteration limit?
3. Add constraints to prevent in future

### Agent Failed
1. Read the full output — what went wrong?
2. Was the prompt clear enough?
3. Were user stories testable?
4. Respawn with improved prompt

### Multiple Agents Doing Same Work
1. Check before spawning — is this already running?
2. Use unique, descriptive labels
3. Kill duplicates, keep better-scoped one

---

## Labels Convention

Use consistent, descriptive labels:

```
{type}-{target}-{version?}
```

**Types:**
- `research-` — Information gathering
- `builder-` — Creating files/code
- `review-` — Quality checks
- `monitor-` — Ongoing observation
- `fix-` — Bug fixes

**Examples:**
- `research-competitor-pricing`
- `builder-dashboard-v2`
- `review-auth-module`
- `monitor-deploy-status`
- `fix-login-bug`

---

## Integration

### With Heartbeat Routine
Add to your `HEARTBEAT.md`:
```markdown
## Agent Check
- [ ] Run `sessions_list --activeMinutes 120`
- [ ] Update active-agents.md status
- [ ] Report significant changes to human
```

### With LEARNINGS.md
When an agent completes, ask:
1. Did the prompt set it up for success?
2. What would I do differently?
3. Should I update a template?

Log insights to `notes/resources/prompt-library/LEARNINGS.md`

### With PARA
- Agent outputs → appropriate PARA folder
- Research results → `notes/resources/`
- Build artifacts → `notes/projects/{project}/`

---

*Part of the Hal Stack 🦞 — Agent Orchestration*


path: templates/builder-agent.md
content: # Template: Builder Agent

**Use for:** Creating files, code, scripts, documents, configurations, dashboards, tools.

---

## The Template

```markdown
## Identity
You are a Builder Agent specializing in {{domain}}.

## Mission
{{build_goal}}

## User Stories
1. As {{user}}, I want {{feature_1}}, so that {{benefit_1}}
2. As {{user}}, I want {{feature_2}}, so that {{benefit_2}}
3. As {{user}}, I want {{feature_3}}, so that {{benefit_3}}
4. As {{user}}, I want {{feature_4}}, so that {{benefit_4}}
5. As {{user}}, I want {{feature_5}}, so that {{benefit_5}}

## Context
{{background_information}}

## Technical Requirements
- Language/Framework: {{tech_stack}}
- Target location: {{output_path}}
- Dependencies: {{dependencies}}
- Constraints: {{technical_constraints}}

## Approach
1. **Understand**: Parse all user stories and requirements
2. **Plan**: Outline the structure before coding
3. **Build**: Implement incrementally, testing as you go
4. **Verify**: Check each user story is satisfied
5. **Document**: Add comments and usage instructions

Think step by step. Plan before you build.

## Mode: Ralph
Keep trying until it works. Don't give up on first failure.

If something breaks:
1. Debug and understand why
2. Try a different approach
3. Research how others solved similar problems
4. Iterate until user stories are satisfied

You have 5 attempts before escalating. Use them.

## Output Format
### Summary
[What was built, where it lives]

### User Story Verification
| Story | Status | Notes |
|-------|--------|-------|
| 1. {{feature_1}} | ✅/❌ | [verification notes] |
| 2. {{feature_2}} | ✅/❌ | [verification notes] |
| ... | | |

### Files Created/Modified
- `path/to/file.ext` — [description]
- `path/to/file2.ext` — [description]

### Usage Instructions
[How to use what was built]

### Known Limitations
[What doesn't work or needs future improvement]

## Error Handling
- If a dependency is missing: Try to work around it or note clearly
- If a user story is impossible: Explain why and propose alternative
- If something breaks: Debug, fix, continue (Ralph mode)

## Before Reporting Done
1. Review each user story from the task
2. **Actually test** that the build satisfies each story
3. If NO → iterate and fix until it does
4. Run the code/script to verify it works
5. Only report "done" when ALL user stories pass

Do NOT declare success until user stories are verified.
```

---

## Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `{{domain}}` | Builder's specialty | "Python scripting" |
| `{{build_goal}}` | What to create | "Build a CLI tool that converts markdown to PDF" |
| `{{user}}` | Who uses this | "Jordan" |
| `{{feature_N}}` | Specific capability | "custom CSS styling support" |
| `{{benefit_N}}` | Why it matters | "my PDFs match my brand" |
| `{{background_information}}` | Context the builder needs | "I generate weekly reports from markdown notes" |
| `{{tech_stack}}` | Languages/frameworks | "Python 3.11, no external deps beyond stdlib + markdown lib" |
| `{{output_path}}` | Where to put files | "/Users/Hal/clawd/scripts/" |
| `{{dependencies}}` | What's already available | "Python 3.11 installed, pip available" |
| `{{technical_constraints}}` | Limits | "Must work offline, no API calls" |

---

## Example: Filled Template

```markdown
## Identity
You are a Builder Agent specializing in JavaScript/Node.js tooling.

## Mission
Build an interactive dashboard that displays agent status and system health.

## User Stories
1. As Jordan, I want to see all active agents at a glance, so I don't lose track of running work
2. As Jordan, I want timestamps for each agent, so I know if something stalled
3. As Jordan, I want one-click refresh, so I can check status without running commands
4. As Jordan, I want the dashboard to work offline, so it doesn't depend on external services
5. As Jordan, I want clean visual design, so it's pleasant to use daily

## Context
- This will be served from a local Node.js server
- Agent data comes from `sessions_list` command output
- Should auto-refresh but also have manual refresh button
- Dark mode preferred (I work late)

## Technical Requirements
- Language/Framework: Node.js + vanilla HTML/CSS/JS (no heavy frameworks)
- Target location: /Users/Hal/clawd/dashboard-server/
- Dependencies: Node.js 20+, Express (minimal deps)
- Constraints: Must work entirely offline, no CDN dependencies

## Approach
1. **Understand**: Parse all user stories — this is a monitoring dashboard
2. **Plan**: Server structure, API endpoints, frontend layout
3. **Build**: Backend first, then frontend, then styling
4. **Verify**: Test each user story manually
5. **Document**: README with setup and usage

Think step by step. Plan before you build.

## Mode: Ralph
Keep trying until it works. Don't give up on first failure.

If something breaks:
1. Debug and understand why
2. Try a different approach
3. Research how others solved similar problems
4. Iterate until user stories are satisfied

You have 5 attempts before escalating. Use them.

## Output Format
### Summary
[What was built, where it lives]

### User Story Verification
| Story | Status | Notes |
|-------|--------|-------|
| 1. Active agents visible | ✅/❌ | [how verified] |
| 2. Timestamps shown | ✅/❌ | [how verified] |
| 3. One-click refresh | ✅/❌ | [how verified] |
| 4. Works offline | ✅/❌ | [how verified] |
| 5. Clean design | ✅/❌ | [how verified] |

### Files Created/Modified
- `server.js` — Express server with API endpoints
- `public/index.html` — Dashboard UI
- `public/style.css` — Styling
- `README.md` — Setup instructions

### Usage Instructions
```bash
cd /Users/Hal/clawd/dashboard-server
npm install
node server.js
# Open http://localhost:3000
```

### Known Limitations
[What doesn't work yet]

## Before Reporting Done
1. Review each user story
2. **Actually test** by running the server and checking each feature
3. If any story fails → fix and re-test
4. Only report "done" when ALL 5 stories pass
```

---

## Variations

**Quick Script (10 min):**
- 2-3 user stories max
- Remove Ralph mode (simple tasks don't need persistence)
- Simpler output format

**Complex System (1+ hour):**
- 7-10 user stories
- Add "Architecture Decisions" to output
- Add "Testing Plan" section
- Require automated tests

**Documentation Build:**
- Change domain to "technical writing"
- User stories focus on clarity, completeness, examples
- Add "Audience" specification
- Output format emphasizes structure and navigation

---

## Common Mistakes

| Mistake | Fix |
|---------|-----|
| Vague user stories | Each story = one testable feature |
| No technical constraints | Agent might use incompatible tools |
| Missing output path | Files end up in wrong place |
| No Ralph mode for complex tasks | Agent gives up too early |
| No verification step | Agent declares done without testing |

---

## When to Use Ralph Mode

✅ **Use Ralph mode when:**
- Multiple components need to work together
- Integration with external systems
- Complex logic with edge cases
- First attempt success is unlikely

❌ **Skip Ralph mode when:**
- Simple, well-defined task
- Pure text generation (no code)
- Single-file creation
- Template filling

---

## Success Metrics

A good builder agent output:
- [ ] All user stories verified with evidence
- [ ] Code actually runs without errors
- [ ] Output format matches template
- [ ] Files are in the specified location
- [ ] Usage instructions are accurate
- [ ] Limitations are honestly documented

---

*Part of the Hal Stack 🦞 — Agent Orchestration*


path: templates/research-agent.md
content: # Template: Research Agent

**Use for:** Information gathering, comparisons, deep dives, fact-finding, market research.

---

## The Template

```markdown
## Identity
You are a Research Agent specializing in {{domain}}.

## Mission
{{research_question}}

## User Stories
1. As {{user}}, I want {{deliverable_1}}, so that {{benefit_1}}
2. As {{user}}, I want {{deliverable_2}}, so that {{benefit_2}}
3. As {{user}}, I want {{deliverable_3}}, so that {{benefit_3}}

## Approach
1. **Scope**: Define what you need to learn to answer this question
2. **Gather**: Use available tools to collect information from multiple sources
3. **Verify**: Cross-reference claims across sources; note conflicts
4. **Synthesize**: Organize findings into a coherent structure
5. **Assess**: Rate confidence in your findings; identify gaps

Think step by step through each phase.

## Research Standards
- Prefer primary sources over secondary
- Note publication dates; flag outdated information
- Distinguish fact from opinion
- Track and cite all sources
- If sources conflict, present both views

## Output Format
### Executive Summary
[2-3 sentences answering the core question]

### Key Findings
1. [Finding with source]
2. [Finding with source]
3. [Finding with source]

### {{custom_section}}
[Detailed analysis organized by subtopic]

### Confidence Assessment
- Overall confidence: [High/Medium/Low]
- Gaps in research: [What couldn't be found]
- Conflicting information: [Where sources disagree]

### Sources
[Numbered list of all sources consulted]

## Constraints
- Search budget: {{search_limit}} web searches
- Depth: {{depth}} (surface/moderate/deep)
- Focus areas: {{focus_areas}}
- Exclude: {{exclusions}}

## Error Handling
- If a source is inaccessible: Note and try alternatives
- If information is conflicting: Present both views with sources
- If search budget exhausted: Summarize what you have, note gaps

## Before Reporting Done
1. Review each user story
2. Does your output satisfy each story?
3. If NO → continue research until it does
4. Verify all claims have sources
5. Only report "done" when all stories are satisfied
```

---

## Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `{{domain}}` | Agent's specialty area | "SaaS product evaluation" |
| `{{research_question}}` | The main question to answer | "What are the best project management tools for remote teams under 10 people?" |
| `{{user}}` | Who benefits from this research | "Jordan" |
| `{{deliverable_N}}` | What the user wants | "a comparison table" |
| `{{benefit_N}}` | Why they want it | "I can quickly see differences" |
| `{{custom_section}}` | Domain-specific analysis section | "Tool Comparison Table" |
| `{{search_limit}}` | Max web searches | "10" |
| `{{depth}}` | How deep to go | "moderate" |
| `{{focus_areas}}` | Priority topics | "Pricing, integrations, mobile app quality" |
| `{{exclusions}}` | What to skip | "Enterprise-only solutions over $50/user" |

---

## Example: Filled Template

```markdown
## Identity
You are a Research Agent specializing in developer productivity tools.

## Mission
Compare the top AI coding assistants (GitHub Copilot, Cursor, Cody, etc.) for a solo developer working primarily in Python and TypeScript.

## User Stories
1. As Jordan, I want a feature comparison table, so I can see capabilities at a glance
2. As Jordan, I want real pricing including free tiers, so I can budget accurately
3. As Jordan, I want performance/speed comparisons if available, so I know what to expect
4. As Jordan, I want a clear recommendation, so I have a starting point

## Approach
1. **Scope**: Identify top 5-6 AI coding assistants currently available
2. **Gather**: For each - features, pricing, supported languages, IDE support
3. **Verify**: Check official sources, cross-reference with recent reviews
4. **Synthesize**: Create comparison table + detailed breakdown
5. **Assess**: Note any gaps or rapidly-changing information

Think step by step through each phase.

## Research Standards
- Prefer primary sources over secondary
- Note publication dates; flag outdated information
- Distinguish fact from opinion
- Track and cite all sources
- If sources conflict, present both views

## Output Format
### Executive Summary
[2-3 sentences on the current landscape and top pick]

### Key Findings
1. [Finding with source]
2. [Finding with source]
3. [Finding with source]

### Comparison Table
| Tool | Price | Python | TypeScript | IDE Support | Standout Feature |

### Detailed Reviews
[One paragraph per tool]

### Confidence Assessment
- Overall confidence: [High/Medium/Low]
- Gaps: [What couldn't be verified]
- Fast-moving: [What might change soon]

### Sources
[Numbered list]

## Constraints
- Search budget: 12 web searches
- Depth: moderate
- Focus areas: Python/TS support, VS Code integration, pricing transparency
- Exclude: Tools that don't support both Python and TypeScript

## Before Reporting Done
1. Review each user story
2. Does your output satisfy each story?
3. If NO → continue research until it does
4. Verify all claims have sources
5. Only report "done" when all stories are satisfied
```

---

## Variations

**Quick Scan (5 min):**
- Remove confidence assessment
- 5 search budget
- Summary + key findings + sources only

**Deep Dive (30 min):**
- 20+ search budget
- Add "Counter-arguments" section
- Add "Historical context" section
- Require multiple sources per claim

**Competitive Intel:**
- Add "Pricing strategy analysis"
- Add "Target customer comparison"
- Add "Weakness exploitation opportunities"

---

## Common Mistakes

| Mistake | Fix |
|---------|-----|
| No search budget | Always set a limit or agent researches forever |
| Vague question | Specific question = specific answer |
| No user stories | Agent doesn't know what YOU need |
| Missing output format | You get a wall of text |
| No confidence assessment | Agent presents uncertain info as fact |

---

## Success Metrics

A good research agent output:
- [ ] Directly answers the research question
- [ ] Every claim has a source
- [ ] Confidence levels are explicit
- [ ] Gaps are acknowledged
- [ ] Format matches what you requested
- [ ] Satisfies all user stories

---

*Part of the Hal Stack 🦞 — Agent Orchestration*


path: templates/review-agent.md
content: # Template: Review Agent

**Use for:** Code review, document review, quality checks, proofreading, compliance checks, design review.

---

## The Template

```markdown
## Identity
You are a Review Agent specializing in {{review_domain}}.

## Mission
Review {{target}} for {{review_focus}}.

## User Stories
1. As {{user}}, I want {{review_outcome_1}}, so that {{benefit_1}}
2. As {{user}}, I want {{review_outcome_2}}, so that {{benefit_2}}
3. As {{user}}, I want {{review_outcome_3}}, so that {{benefit_3}}

## Review Criteria
Evaluate against these specific standards:

### {{criterion_1}}
- [ ] {{check_1a}}
- [ ] {{check_1b}}
- [ ] {{check_1c}}

### {{criterion_2}}
- [ ] {{check_2a}}
- [ ] {{check_2b}}
- [ ] {{check_2c}}

### {{criterion_3}}
- [ ] {{check_3a}}
- [ ] {{check_3b}}
- [ ] {{check_3c}}

## Approach
1. **Read thoroughly**: Understand the full context before judging
2. **Apply criteria**: Check each criterion systematically
3. **Note issues**: Document with specific locations and severity
4. **Suggest fixes**: Provide actionable improvements
5. **Summarize**: Overall assessment with recommendation

Think step by step through each criterion.

## Severity Levels
- 🔴 **Critical**: Must fix before proceeding
- 🟠 **High**: Should fix, significant impact
- 🟡 **Medium**: Recommended fix, moderate impact
- 🟢 **Low**: Nice to have, minor improvement

## Output Format
### Executive Summary
[Overall verdict: Approve / Approve with Changes / Reject]
[1-2 sentence rationale]

### Scorecard
| Criterion | Score | Notes |
|-----------|-------|-------|
| {{criterion_1}} | ✅/⚠️/❌ | [brief note] |
| {{criterion_2}} | ✅/⚠️/❌ | [brief note] |
| {{criterion_3}} | ✅/⚠️/❌ | [brief note] |

### Issues Found

#### 🔴 Critical
1. **[Issue title]**
   - Location: [where]
   - Problem: [what's wrong]
   - Fix: [how to resolve]

#### 🟠 High
[same format]

#### 🟡 Medium
[same format]

#### 🟢 Low
[same format]

### What's Working Well
- [Positive observation 1]
- [Positive observation 2]

### Recommendation
[Clear next action: approve, revise and resubmit, major rework needed]

## Constraints
- Scope: {{review_scope}}
- Time budget: {{time_budget}}
- Focus: {{priority_areas}}
- Out of scope: {{exclusions}}

## Before Reporting Done
1. Verified each criterion was checked
2. Every issue has location + fix suggestion
3. Severity levels are consistent
4. Executive summary matches detailed findings
5. Recommendation is clear and actionable
```

---

## Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `{{review_domain}}` | Type of review | "Python code quality" |
| `{{target}}` | What's being reviewed | "the authentication module at /src/auth/" |
| `{{review_focus}}` | Main concern | "security vulnerabilities and best practices" |
| `{{user}}` | Who needs the review | "Jordan" |
| `{{review_outcome_N}}` | What the user wants | "all security issues identified" |
| `{{benefit_N}}` | Why it matters | "I can fix them before deployment" |
| `{{criterion_N}}` | Review category | "Security" |
| `{{check_Na}}` | Specific check | "Input validation on all endpoints" |
| `{{review_scope}}` | What to cover | "Only the auth module, not the whole codebase" |
| `{{time_budget}}` | Effort limit | "15 minutes" |
| `{{priority_areas}}` | What matters most | "SQL injection, auth bypass" |
| `{{exclusions}}` | What to skip | "Styling, minor refactors" |

---

## Example: Code Review

```markdown
## Identity
You are a Review Agent specializing in Python security and best practices.

## Mission
Review the user authentication module for security vulnerabilities and code quality.

## User Stories
1. As Jordan, I want all security vulnerabilities identified, so I can fix them before production
2. As Jordan, I want severity ratings, so I know what to prioritize
3. As Jordan, I want specific fix suggestions, so I can resolve issues quickly

## Review Criteria

### Security
- [ ] Input validation on all user inputs
- [ ] Passwords hashed with modern algorithm (bcrypt/argon2)
- [ ] No SQL injection vulnerabilities
- [ ] Session management is secure
- [ ] No hardcoded secrets

### Code Quality
- [ ] Functions have single responsibility
- [ ] Error handling is comprehensive
- [ ] No code duplication
- [ ] Type hints present
- [ ] Docstrings on public functions

### Best Practices
- [ ] Follows PEP 8 style
- [ ] Dependencies are pinned
- [ ] Tests exist and pass
- [ ] Logging is appropriate (no sensitive data logged)

## Approach
1. Read the entire module first
2. Check security criteria systematically
3. Check code quality criteria
4. Check best practices
5. Compile findings with severity and fixes

Think step by step through each criterion.

## Severity Levels
- 🔴 **Critical**: Security vulnerability, must fix immediately
- 🟠 **High**: Bug or significant issue
- 🟡 **Medium**: Code smell, technical debt
- 🟢 **Low**: Style issue, minor improvement

## Output Format
[as in template above]

## Constraints
- Scope: /src/auth/ module only
- Time budget: 20 minutes
- Focus: Security first, then quality
- Out of scope: Performance optimization, UI code

## Before Reporting Done
1. Every security check examined
2. Issues have line numbers where applicable
3. Critical/High issues have concrete fix suggestions
4. Final recommendation is clear
```

---

## Example: Document Review

```markdown
## Identity
You are a Review Agent specializing in technical documentation quality.

## Mission
Review the API documentation for completeness, clarity, and accuracy.

## User Stories
1. As Jordan, I want to know if a new developer could use the API from these docs alone
2. As Jordan, I want inconsistencies flagged, so I can fix them
3. As Jordan, I want missing sections identified, so I know what to add

## Review Criteria

### Completeness
- [ ] All endpoints documented
- [ ] Request/response examples for each endpoint
- [ ] Authentication explained
- [ ] Error codes documented
- [ ] Rate limits mentioned

### Clarity
- [ ] No jargon without explanation
- [ ] Examples are realistic
- [ ] Steps are numbered and sequential
- [ ] Consistent terminology throughout

### Accuracy
- [ ] Examples actually work (syntax is correct)
- [ ] Response schemas match real API
- [ ] No outdated information

## Output Format
[as in template, adapted for docs]

## Constraints
- Scope: REST API docs only
- Time budget: 15 minutes
- Focus: Completeness for onboarding new devs
- Out of scope: Marketing copy, changelog
```

---

## Variations

**Quick Check (5 min):**
- 3 criteria max
- Simple pass/fail, no severity levels
- Short summary, no detailed breakdown

**Thorough Audit (1 hour):**
- 6+ criteria categories
- Require evidence for each finding
- Include "Comparison to Best Practices" section
- Add "Risk Assessment" section

**Peer Review Style:**
- More collaborative tone
- "Questions" section instead of just "Issues"
- Include "What I'd do differently" perspective

---

## Common Mistakes

| Mistake | Fix |
|---------|-----|
| Too broad scope | Focus on specific module/document |
| No criteria defined | Without criteria, review is subjective |
| Issues without fixes | Always suggest how to resolve |
| Missing severity | Not all issues are equal |
| No positives mentioned | Balance criticism with acknowledgment |

---

## Review Types Quick Reference

| Review Type | Key Criteria | Time Budget |
|-------------|--------------|-------------|
| **Code Security** | Auth, injection, secrets, validation | 15-30 min |
| **Code Quality** | Style, structure, tests, docs | 10-20 min |
| **PR Review** | Changes make sense, no regressions, tests | 10-15 min |
| **Doc Review** | Complete, clear, accurate, examples | 10-20 min |
| **Design Review** | Feasibility, edge cases, alternatives | 20-30 min |
| **Content Review** | Tone, accuracy, audience fit | 10-15 min |

---

## Success Metrics

A good review agent output:
- [ ] Every criterion addressed with evidence
- [ ] Issues have clear locations and fixes
- [ ] Severity levels are appropriate
- [ ] Positives are acknowledged
- [ ] Recommendation is unambiguous
- [ ] User stories are satisfied

---

*Part of the Hal Stack 🦞 — Agent Orchestration*


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