Skip to content

Instantly share code, notes, and snippets.

@ncoblentz
Created April 20, 2026 14:37
Show Gist options
  • Select an option

  • Save ncoblentz/4e0a624de43e95dfc1fc2ad41a5caf93 to your computer and use it in GitHub Desktop.

Select an option

Save ncoblentz/4e0a624de43e95dfc1fc2ad41a5caf93 to your computer and use it in GitHub Desktop.
Agentic Patterns Reference

Agent Patterns Cheatsheet

A reference guide for multi-agent system design patterns — when to use them, how they work, and how to implement them with Claude Code.

Merges applied (40 → 35 patterns):

  • Pipeline absorbs Staged Pipeline (staged = pipeline + quality gates variant)
  • Reflection absorbs Retry-with-Reflection (retry = failure-triggered reflection variant)
  • Ensemble absorbs Self-Consistency (self-consistency = same-prompt voting variant)
  • Dispatcher-Worker-Merger absorbs Mixture of Experts (MoE = sparse-activation routing variant)
  • Planner-Executor-Verifier removed — it is Plan-then-Execute + per-step Critic-Validator; noted in both parent sections

Quick Reference

Click any pattern name to jump to its full entry — diagram, when to use, example prompt, and pairings.

# Pattern Core Mechanism Use When Avoid When Parallelism Complexity Top Pairings
1 Orchestrator-Worker Central agent decomposes task, delegates to workers, synthesizes results Task has independent subtasks needing different expertise Tasks strongly sequential; workers need direct communication High Low Specialist Decomp, Critic-Validator, Fan-out/Fan-in
2 Map-Reduce Split large data across parallel agents; aggregate results Large homogeneous data; output is an aggregation Items interdependent; dataset fits one agent High Low Fan-out/Fan-in, Concurrent, Pipeline
3 DAG Execution Tasks as nodes in dependency graph; execute with maximum safe parallelism Mixed serial/parallel dependencies known upfront Fully sequential; fully parallel; dynamic deps discovered at runtime Medium Medium Orchestrator-Worker, Concurrent, Plan-then-Execute
4 Dispatcher-Worker-Merger / MoE Router dispatches each task to best-fit worker; merger aggregates outputs Heterogeneous tasks needing different handlers All tasks identical; every input needs every expert High Medium Specialist Decomp, Orchestrator-Worker, Supervisor
5 Critic-Validator Generator creates; separate critic evaluates; generator revises until approved Quality critical; clear acceptance criteria exist Simple tasks; no clear criteria; latency critical None Low Reflection, Iterative Refinement, Constitutional
6 Ensemble / Self-Consistency Multiple agents tackle same problem independently; outputs aggregated by vote or synthesis Genuine ambiguity or high single-agent variance Single objectively correct answer; agents produce identical output High Low–Med Debate, Council, Concurrent
7 ReAct (Reason+Act) Thought → Tool Action → Observation loop; each step informed by prior result Next step depends on prior tool result; problem too large to plan upfront Task fully plannable upfront; no tools available; strict latency None Low Tool-Augmented, Plan-then-Execute, Reflection
8 Plan-then-Execute Planner creates full plan before any execution; executors carry it out; phases fully separated Actions have real consequences; human review needed before execution Highly dynamic; plan obsoletes before execution completes Low Low DAG Execution, HITL, ReAct, Critic-Validator
9 Reflection / Retry-with-Reflection Agent critiques its own output (proactive) or reflects on failure cause before retrying (reactive) Quality improves with self-critique; failure is diagnosable from output External constraints cause failure; agent cannot identify its own blind spots None Low Critic-Validator, Iterative Refinement, Memory-Augmented
10 Specialist Decomposition Task split by domain; each part routed to matching expert with narrow deep context Clear domain boundaries; specialists benefit from focused context Domains deeply intertwined; specialists need live negotiation High Low–Med Dispatcher/MoE, Orchestrator-Worker, Blackboard
11 Human-in-the-Loop (HITL) Execution pauses at defined checkpoints for human approval, modification, or input Irreversible actions; compliance requirements; low agent confidence Latency-sensitive; routine well-validated tasks; rubber-stamp risk None Low Plan-then-Execute, Critic-Validator, Staged Pipeline
12 Speculative Execution Race multiple paths in parallel; first success wins; others discarded Unknown best path; latency matters more than compute cost Side-effecting actions that can't be cancelled; one path clearly best High Medium Fan-out/Fan-in, Concurrent, Tree-of-Thought
13 Blackboard Agents read/write shared data store; agents trigger on new entries Emergent collaboration; contribution order unknown; insights arise from combination Strict ordering required; write conflicts likely; clear task ownership exists High Medium Swarm, Concurrent, Event-Driven
14 Pipeline / Staged Pipeline Linear chain: each agent's output feeds the next; optional quality gates between stages Sequential transforms; each output is reliable input for next; or propagating bad output is costly Stages are independent (use Fan-out); complex branching retry needed between stages None Low Critic-Validator, HITL, Handoff, Map-Reduce
15 STORM / Outline-then-Write Research → outline → parallel section writing → compile into coherent document Long structured document exceeds single-agent context window Short docs fitting one context; sections deeply interdependent Medium Medium Fan-out/Fan-in, Ensemble, Staged Pipeline
16 Collaborative Agents sequentially improve shared artifact, each contributing from their domain Output quality improves when each agent builds on others' contributions Agents would override each other; clear section ownership exists Sequential Low Iterative Refinement, Specialist Decomp, Blackboard
17 Hierarchical Recursive Orchestrator-Worker: agents organized in multi-level delegation tree Task needs multiple abstraction levels to fully decompose; very large scale One decomposition level sufficient; all agents need full context High High Orchestrator-Worker, Specialist Decomp, Supervisor
18 Fan-out / Fan-in Broadcast task to parallel agents (fan-out); collect and aggregate results (fan-in) Same task for many independent inputs; parallelism cuts latency Sequential/dependent inputs; aggregation requires all results simultaneously High Low Map-Reduce, Concurrent, Orchestrator-Worker
19 Debate Two agents argue opposing positions across rounds; separate judge renders verdict Genuine tradeoffs exist; need to stress-test an argument before committing Objectively correct answer; both agents share the same bias None Low–Med Critic-Validator, Ensemble, HITL, Council
20 Swarm Many simple agents follow local rules; emergent collective behavior via shared environment Large-scale exploration; central coordination impractical; no single point of failure needed Strict ordering required; auditability is critical; problem is well-defined High High Blackboard, Concurrent, Event-Driven
21 Council / Ensemble Structured group with defined roles deliberates; chairperson synthesizes recommendation Multi-expert high-stakes decisions requiring integrated perspectives Speed-critical; all members converge to the same conclusion anyway Low Medium Specialist Decomp, Debate, HITL, Role-Playing
22 Magnetic Agents self-assign to tasks based on capability affinity; emergent routing, no dispatcher Dynamic task types; variable agent availability; self-organization preferred Deterministic routing sufficient; affinity signals unreliable High High Swarm, Dispatcher/MoE, Blackboard
23 Group Chat Agents share full conversation history; take turns; moderator controls turn order Real-time negotiation; agents must challenge and build on each other's claims Independent work; history size degrades performance; strict parallelism required None Medium Debate, Council, Collaborative, Blackboard
24 Handoff Agent packages rich context packet and explicitly transfers responsibility to next agent Long tasks exceeding one context window; different phase ownership; continuity critical All work fits one context; packaging overhead exceeds benefit None Low Pipeline, Memory-Augmented, HITL, Plan-then-Execute
25 Concurrent Multiple agents execute simultaneously with no ordering constraints or required aggregation Truly independent tasks; throughput or latency improvement is critical Tasks share state; dependencies exist between tasks High Low Fan-out/Fan-in, Map-Reduce, Swarm, DAG Execution
26 Supervisor Monitors worker agents; detects failures; restarts, reassigns, or escalates Long-running workers; automatic failure recovery required; quality enforcement Short-lived tasks; human monitoring sufficient; supervision is a bottleneck N/A Medium Orchestrator-Worker, Hierarchical, Reflection, HITL
27 Actor Model Actors with private state + message inbox; communicate exclusively via messages; no shared state High concurrency; private state per actor; fault isolation critical Shared state required; sequential processing; message overhead too expensive High High Concurrent, Blackboard, Swarm, Event-Driven
28 Tree-of-Thought (ToT) Generate multiple thoughts per step; evaluate each; prune weak branches; expand most promising Complex solution space; early choices have large downstream impact; structured search Simple greedy path sufficient; no intermediate evaluation possible; computationally expensive Medium High ReAct, Speculative Execution, Plan-then-Execute, Critic-Validator
29 Tool-Augmented Agent Agent invokes external tools (shell, API, browser) during reasoning to take real-world action Real-world information or actions required; pure language reasoning insufficient All needed info already in context; tool risk or latency is too high None Low ReAct, Specialist Decomp, Plan-then-Execute, Supervisor
30 Memory-Augmented Agent Agent reads/writes persistent memory across sessions; retrieval augments reasoning Cross-session continuity; knowledge accumulates over time; context exceeds window One-shot tasks; memory is stale; privacy constraints prohibit persistence None Medium ReAct, Reflection, Handoff, Blackboard
31 Iterative Refinement Structured revision cycles each targeting a distinct quality dimension Complex artifact where all improvements cannot happen in a single pass First draft already meets quality bar; criteria too vague to converge None Low Reflection, Critic-Validator, Pipeline, HITL
32 Event-Driven Agent Agents triggered by external events (alerts, webhooks, file changes, schedules) Reactive real-time system; processing triggered by external state changes One-shot batch; events arrive faster than agents can process High Medium Swarm, Actor Model, Supervisor, Blackboard
33 Subgoal Decomposition Recursive decomposition of high-level goal into atomic executable subgoals with clear pre/postconditions Goal too complex to execute directly; natural hierarchical structure exists Shallow task; subgoals deeply interdependent Medium Medium Hierarchical, Plan-then-Execute, ReAct, DAG Execution
34 Constitutional / Guided Generation Generate output; apply rule-set critique; revise violations; repeat until fully compliant Explicit formal rules must be enforced; auditability of compliance required No formal rules; rules too complex for automated checking None Low–Med Critic-Validator, Iterative Refinement, HITL, Supervisor
35 Role-Playing / Persona Assign specific persona or role to constrain the agent's knowledge, priorities, and tone Diverse stakeholder perspectives; consistent role behavior across a long interaction Neutral assessment required; persona conflicts with factual accuracy N/A Low Debate, Group Chat, Council, Ensemble

1. Orchestrator-Worker

Pattern Description

A central orchestrator agent decomposes a complex task, delegates subtasks to worker agents, collects their outputs, and synthesizes a final result. The orchestrator maintains overall context and coordinates sequencing; workers are stateless or narrowly scoped.

Diagram

              ┌─────────────────┐
              │   Orchestrator  │
              │  (coordinates,  │
              │  synthesizes)   │
              └────────┬────────┘
                       │ delegates
          ┌────────────┼────────────┐
          ▼            ▼            ▼
    ┌──────────┐ ┌──────────┐ ┌──────────┐
    │ Worker A │ │ Worker B │ │ Worker C │
    │ (task 1) │ │ (task 2) │ │ (task 3) │
    └────┬─────┘ └────┬─────┘ └────┬─────┘
         │             │             │
         └─────────────▼─────────────┘
                  results back to
                   Orchestrator

When to Use

  • Task is naturally decomposable into independent or loosely coupled subtasks
  • Subtasks require different tools, data sources, or expertise
  • Overall output requires integration of multiple independent results
  • You need centralized error handling and retry logic

When NOT to Use

  • Task is simple and sequential — orchestration overhead outweighs benefit
  • Workers need to communicate directly with each other (use Blackboard or Group Chat instead)
  • Strong sequential dependencies between subtasks (use Pipeline or DAG instead)
  • Context window sharing is critical across all steps

Example Prompt / Scenario

Scenario: Comprehensive security assessment of a web application

You are an orchestrator agent for a security assessment.
Decompose this assessment into parallel subtasks and spawn specialist agents for each:

Target: https://example.com (authorized pentest engagement)

1. Spawn a Reconnaissance agent: enumerate subdomains, open ports, technologies
2. Spawn an Authentication agent: test login flows, session management, password policies
3. Spawn an Authorization agent: test access controls, IDOR, privilege escalation
4. Spawn an Input Validation agent: test for XSS, SQLi, SSTI, command injection
5. Spawn an API Security agent: test REST/GraphQL endpoints for misconfigurations

After all agents report back, synthesize findings into a prioritized vulnerability report
sorted by CVSS score. Deduplicate overlapping findings.

Claude Code implementation:

claude -p "You are an orchestrator. Read the target scope from scope.txt, then use
the Agent tool to spawn 4 parallel specialist agents (recon, auth, authz, injection).
Collect their markdown reports, deduplicate, and write final-report.md ranked by severity."

Pairs Well With

Pattern Why
Specialist Decomposition Workers are defined by domain expertise, making delegation precise
Critic-Validator Orchestrator routes worker output through a validator before synthesis
Fan-out/Fan-in The orchestrator's delegation IS fan-out; collection IS fan-in
Reflection Orchestrator retries failed worker tasks with reflection feedback
Hierarchical Orchestrators can themselves be workers of a higher orchestrator

2. Map-Reduce

Pattern Description

A large dataset or problem space is split (mapped) across multiple parallel agents, each processing a shard independently. Results are then aggregated (reduced) into a unified output. Modeled after the MapReduce programming model.

Diagram

  Input Dataset
  [A,B,C,D,E,F,G,H]
         │
    ┌────▼────┐
    │  Split  │
    └────┬────┘
         │
   ┌─────┼─────┐
   ▼     ▼     ▼
[A,B]  [C,D]  [E,F]  [G,H]
  │      │      │      │
Map    Map    Map    Map
Agent  Agent  Agent  Agent
  │      │      │      │
result result result result
   \     |     |     /
    └────▼─────▼────┘
         Reduce
         Agent
           │
        Final
        Output

When to Use

  • Processing large volumes of homogeneous data (logs, documents, code files, URLs)
  • Each chunk can be processed independently without shared state
  • Final output is an aggregation (count, summary, merged report, ranked list)
  • Speed is critical and parallel processing provides clear benefit

When NOT to Use

  • Items are interdependent (processing one requires knowing the result of another)
  • Dataset is small enough for a single agent
  • Aggregation logic is complex enough to require full context of all intermediate results simultaneously
  • Order of processing matters in a way that prevents parallelism

Example Prompt / Scenario

Scenario: Analyze 500 JavaScript files for security vulnerabilities

Map phase: Split the list of JS files into 10 batches of 50.
For each batch, spawn an agent with this prompt:
  "Analyze these JavaScript files for: XSS sinks, dangerous eval() usage,
   hardcoded secrets, insecure crypto, and prototype pollution.
   Output JSON: {file, finding_type, line, severity, snippet}"

Reduce phase: Collect all JSON arrays, merge them, deduplicate by
(file+line), sort by severity DESC, and write to findings.json.

Claude Code implementation:

# Map
for batch in batches/; do
  claude -p "Analyze JS files in $batch for security issues. Output findings.json" &
done
wait

# Reduce
claude -p "Merge all batch*/findings.json files, deduplicate, sort by severity, write final-findings.json"

Pairs Well With

Pattern Why
Fan-out/Fan-in Fan-out IS the map phase; fan-in IS the reduce phase
Specialist Decomposition Different map agents use domain expertise per chunk type
Concurrent Map agents run concurrently for throughput
Pipeline / Staged Pipeline Map-Reduce can be one stage in a larger pipeline
Critic-Validator Reducer validates map outputs before merging

3. DAG Execution

Pattern Description

Tasks are modeled as nodes in a Directed Acyclic Graph (DAG). Agents execute tasks only when all upstream dependencies are complete. This enables maximum parallelism while respecting dependencies — tasks with no shared dependencies run simultaneously.

Diagram

     [Task A]──────────┐
         │             │
         ▼             ▼
     [Task B]      [Task C]
         │             │
         ▼             │
     [Task D]◄─────────┘
         │
         ▼
     [Task E]  (final output)

Execution order:
  T=0: A starts
  T=1: B and C start in parallel (A done)
  T=2: D starts (B and C both done)
  T=3: E starts (D done)

When to Use

  • Tasks have complex dependency graphs (some parallel, some sequential)
  • You want maximum throughput without violating ordering constraints
  • Build systems, data pipelines, research workflows with known structure
  • When the dependency graph is known upfront and relatively stable

When NOT to Use

  • Dependencies are discovered dynamically during execution (use ReAct or Plan-then-Execute)
  • All tasks are purely sequential (use Pipeline) or purely parallel (use Fan-out)
  • Graph has cycles or mutual dependencies (by definition, not a DAG)
  • Overhead of dependency tracking exceeds the parallelism benefit

Example Prompt / Scenario

Scenario: Build a security research report with structured dependencies

Execute this task graph for a threat model report:

Nodes and dependencies:
  gather_cve_data         → (no deps)
  gather_exploit_db       → (no deps)
  analyze_attack_surface  → (no deps)
  correlate_cves          → [gather_cve_data, gather_exploit_db]
  prioritize_threats      → [correlate_cves, analyze_attack_surface]
  write_executive_summary → [prioritize_threats]
  write_technical_detail  → [prioritize_threats]
  final_report            → [write_executive_summary, write_technical_detail]

Spawn agents for nodes with satisfied dependencies. As each completes,
check if new nodes become unblocked and spawn them immediately.

Pairs Well With

Pattern Why
Orchestrator-Worker Orchestrator manages the DAG state and worker dispatch
Concurrent Nodes with no shared dependencies run concurrently
Pipeline / Staged Pipeline A pipeline is a degenerate DAG (linear chain)
Plan-then-Execute Plan phase produces the DAG; execute phase runs it
Supervisor Supervisor monitors DAG execution and handles failures

4. Dispatcher-Worker-Merger / Mixture of Experts

Pattern Description

A Dispatcher (or Router) agent routes incoming tasks to the most appropriate worker based on task type, capability, or load. Workers process tasks independently. A Merger collects outputs and combines them. Mixture of Experts (MoE) is a variant where the router performs sparse activation — selecting only the 1–2 best-fit expert agents per input rather than explicit rule-based routing, and typically not all experts are used for any given input.

Diagram

  Incoming Tasks
  [T1, T2, T3, T4, T5]
          │
    ┌─────▼──────┐
    │ Dispatcher  │ ◄── routing rules / capability registry
    │  / Router   │     (MoE: learned or scored affinity)
    └──┬──┬──┬───┘
       │  │  │
       ▼  │  ▼
  [W:SQL] │ [W:Python]     ← Workers / Experts
          ▼
      [W:General]

  Each worker processes only routed tasks
       │    │    │
       └────▼────┘
         Merger
           │
        Combined
         Output

When to Use

  • Tasks are heterogeneous and require different specialized handlers
  • You have a pool of workers with known capabilities
  • Input volume is high and you want sparse (selective) expert activation (MoE)
  • Load balancing across workers is important
  • Input stream is continuous or unpredictable in type

When NOT to Use

  • All tasks are identical (use Map-Reduce instead)
  • Routing logic is trivial or tasks are known in advance (use Specialist Decomposition)
  • Workers need shared state (use Blackboard)
  • Every input genuinely requires every expert (use Ensemble instead)

Variants

Variant Distinguishing Feature
Dispatcher-Worker-Merger Explicit rule-based routing; merger aggregates all outputs
Mixture of Experts (MoE) Scored/learned affinity routing; sparse activation (1–2 experts per input); outputs combined by weighted merge or gating

Example Prompt / Scenario

Scenario — DWM: Triage and route security alerts from multiple scanners

You are a Dispatcher. Incoming alerts come from three scanners:
SAST (code), DAST (web), and SCA (dependencies).

Routing rules:
  - SAST findings → CodeReview Worker (has access to source files)
  - DAST findings → WebTest Worker (has browser tools)
  - SCA findings  → DependencyAudit Worker (has CVE database access)
  - Unknown type  → General Worker

Merger: deduplicate cross-scanner findings for the same vulnerability,
enrich with CVSS scores, output unified alerts.json.

Scenario — MoE: Security alert triage with scored expert activation

Router Agent: "Read this security alert: [alert].
  Score each expert 0–1 for relevance: WebAttack, NetworkAttack,
  MalwareExecution, InsiderThreat, DataExfil.
  Activate only experts scoring ≥ 0.6.
  Combine activated expert outputs by weight."

Pairs Well With

Pattern Why
Specialist Decomposition Workers ARE specialists; dispatcher routes to them
Orchestrator-Worker Dispatcher is an orchestrator with routing intelligence
Concurrent Multiple workers process simultaneously
Blackboard Merger writes to shared blackboard for cross-worker visibility
Supervisor Supervisor monitors worker health and reroutes on failure

5. Critic-Validator

Pattern Description

A Generator agent produces output, then a separate Critic (or Validator) agent evaluates it against criteria — correctness, safety, style, completeness, or domain rules. The generator revises based on critique. Separates generation from evaluation concerns.

Note: Combining this pattern with Plan-then-Execute — specifically, applying a Critic-Validator after each step of execution rather than at the end — is sometimes called the Planner-Executor-Verifier pattern. No separate entry is needed; it is simply Plan-then-Execute with per-step Critic gates.

Diagram

  Task
    │
    ▼
┌──────────┐    output    ┌──────────┐
│ Generator│─────────────►│  Critic  │
│  Agent   │              │  Agent   │
└──────────┘              └────┬─────┘
     ▲                         │
     │    critique/feedback     │
     └─────────────────────────┘
                │
           (if approved)
                │
                ▼
           Final Output

When to Use

  • Output quality is critical and errors are costly
  • Domain-specific validation rules exist (security policies, legal constraints, style guides)
  • Generator and validator benefit from different context or role framing
  • You want separation of creative generation from rigorous checking

When NOT to Use

  • The task is simple enough that one pass is sufficient
  • Critique loop adds latency that outweighs quality benefit
  • There are no clear acceptance criteria for the critic to apply
  • Generator and critic agree trivially (critic adds no value)

Example Prompt / Scenario

Scenario: Generate and validate security remediation advice

Generator Agent:
"Given this vulnerability: [SQL injection in login.php:47],
write remediation guidance including: root cause, code fix with example,
testing steps to verify the fix, and references."

Critic Agent:
"Review this remediation guidance for:
1. Technical accuracy (is the fix correct?)
2. Completeness (does it cover all attack vectors?)
3. Security (does the fix introduce new issues?)
4. Clarity (can a mid-level developer implement it?)
Score each 1–5. If any score < 4, return specific feedback for revision.
If all ≥ 4, return APPROVED."

Loop until APPROVED or 3 iterations max.

Claude Code:

claude -p "Generate remediation for findings.json. After each generation,
spawn a critic agent to validate. Iterate max 3 times. Write approved
remediations to remediations-final.md"

Pairs Well With

Pattern Why
Reflection Critic provides the structured feedback; reflection acts on it
Iterative Refinement Critic drives each refinement cycle
Orchestrator-Worker Orchestrator runs generator+critic loop per task
Constitutional/Guided Critic enforces constitutional constraints
Ensemble Multiple critics vote on output validity

6. Ensemble / Multi-Perspective / Self-Consistency

Pattern Description

Multiple agents independently tackle the same problem, then their outputs are aggregated to produce a more robust final answer. There are two main variants depending on how diversity is introduced:

  • Ensemble / Multi-Perspective: Agents use different prompts, personas, or tool access — genuine diversity of approach. Outputs are synthesized by a separate aggregator.
  • Self-Consistency: The same prompt is run multiple times with temperature > 0. The most common answer across runs is selected (majority vote). Reduces variance caused by stochastic sampling rather than by diversity of approach.

Use Ensemble when you want diversity of perspective. Use Self-Consistency when you want reliability on a question with a single correct answer.

Diagram

── Ensemble / Multi-Perspective ──────────────────────────────
              Task
         ┌────┴────┐
         │         │
    ┌────▼────┐    │
    │Agent A  │    ▼
    │(persona │ ┌──────────┐
    │"skeptic"│ │ Agent B  │
    │)        │ │(persona  │
    └────┬────┘ │"optimist"│     ┌──────────┐
         │      └────┬─────┘     │ Agent C  │
         │           │           │(persona  │
         │           │           │"neutral")│
         │           │           └────┬─────┘
         └───────────▼────────────────┘
                  Aggregator
                  (synthesize)
                      │
                  Final Answer

── Self-Consistency ──────────────────────────────────────────
        Question
   ┌────────┼────────┐
   ▼        ▼        ▼
[Run 1]  [Run 2]  [Run 3]   ← same prompt, varied sampling
Answer A Answer A Answer B
   │        │        │
   └────────▼────────┘
       Majority Vote
       Answer = A

When to Use

  • Ensemble: Problem has genuine ambiguity or multiple valid approaches; you want blind-spot coverage; domain requires checking multiple perspectives (security threat modeling, risk assessment)
  • Self-Consistency: Task has a single correct answer but model shows high variance; mathematical reasoning, logical deduction, classification tasks; budget allows multiple completions

When NOT to Use

  • Task has a single objectively correct answer and first-attempt reliability is already high (Ensemble overkill)
  • All agents will produce identical answers — no diversity benefit
  • Latency constraints prohibit parallel generation
  • Open-ended creative tasks where there is no "most consistent" answer (Self-Consistency inapplicable)

Example Prompt / Scenario

Scenario — Ensemble: Threat modeling with diverse attacker personas

Spawn 4 agents to analyze the same system architecture for threats,
each with a different attacker persona:

Agent 1 (External Attacker): "What are your top 5 attack vectors
  against this system from the outside?"
Agent 2 (Malicious Insider): "You have read access to the database.
  What can you do to cause maximum damage?"
Agent 3 (Nation-State APT): "Unlimited time and resources. What is
  your long-game attack path?"
Agent 4 (Automated Bot): "List all automated attack opportunities
  (default creds, known CVEs, misconfigs)."

Aggregator: merge threats, deduplicate, rank by combined risk score.

Scenario — Self-Consistency: Reliable severity classification

Run this classification prompt 5 times (temp=0.7):
"Classify CVE-XXXX-YYYY as: Critical, High, Medium, or Low. Reasoning first."

Collect 5 answers. Select majority classification.
If no majority (tie), run 2 more times as tiebreaker.
for i in {1..5}; do
  claude -p "Classify severity of finding in finding.txt. Output: Critical/High/Medium/Low" \
    >> votes.txt
done
sort votes.txt | uniq -c | sort -rn | head -1

Pairs Well With

Pattern Why
Debate Ensemble agents can be made to argue for/against their perspectives
Council/Ensemble Council is a structured ensemble with defined roles
Critic-Validator One ensemble member plays critic role
Specialist Decomposition Each ensemble agent is a specialist in their domain
Concurrent Ensemble agents must run in parallel for latency benefit

7. ReAct (Reason+Act)

Pattern Description

An agent interleaves reasoning (Thought) with action (Act) and observation (Observe) in a tight loop. The agent thinks about what to do, takes an action (tool call, query, computation), observes the result, then reasons about the next step. Enables dynamic, adaptive problem solving.

Diagram

  Task
    │
    ▼
┌───────────────────────────────────────┐
│  THOUGHT: "I need to check X first"   │
│  ACTION:  call_tool(search, "X")      │
│  OBSERVATION: "X returns result Y"    │
│                                       │
│  THOUGHT: "Y means I should do Z"     │
│  ACTION:  call_tool(compute, "Z")     │
│  OBSERVATION: "Z gives output W"      │
│                                       │
│  THOUGHT: "W satisfies the goal"      │
│  ANSWER:  return W                    │
└───────────────────────────────────────┘
     ▲          (loop until done)
     └──────────────────────────────────

When to Use

  • Task requires dynamic tool use where next step depends on previous results
  • Problem space is too large to plan fully upfront
  • External information retrieval is needed mid-task
  • Real-world feedback (test results, API responses) must influence reasoning

When NOT to Use

  • Task is fully plannable upfront (use Plan-then-Execute)
  • No tools/external state are available — pure reasoning is sufficient
  • Strict latency constraints — ReAct loops have variable depth
  • Tool calls are expensive and should be minimized

Example Prompt / Scenario

Scenario: Investigate a suspicious finding during a pentest

You are a security investigator. Use ReAct to investigate:
"Possible SSRF at /api/fetch?url="

Available tools: curl, nmap, whois, dns_lookup, read_file

THOUGHT: I should first confirm the SSRF is exploitable...
ACTION: curl "https://target.com/api/fetch?url=http://127.0.0.1:22"
OBSERVATION: [response contains SSH banner — SSRF confirmed]
THOUGHT: Try cloud metadata endpoint...
ACTION: curl "https://target.com/api/fetch?url=http://169.254.169.254/latest/meta-data/"
...continue until full impact is documented

Claude Code:

claude -p "Investigate the SSRF finding in findings.txt using ReAct methodology.
Use available bash tools to probe, observe, and reason. Document each
Thought/Action/Observation triple. Stop when impact is fully characterized
or you hit the 10-iteration limit."

Pairs Well With

Pattern Why
Tool-Augmented Agent ReAct IS tool-augmented reasoning
Plan-then-Execute Plan provides initial structure; ReAct adapts within execution
Reflection Reflect on failed ReAct traces to improve strategy
Memory-Augmented Store successful ReAct traces for future reference
Subgoal Decomposition Each ReAct loop can solve one subgoal

8. Plan-then-Execute

Pattern Description

A Planner agent produces a complete, structured plan (steps, dependencies, resources needed) before any execution begins. Executor agents then carry out the plan. Planning and execution are fully separated, enabling review, modification, or approval of the plan before any irreversible action is taken.

Note: Applying a Critic-Validator after each individual step of execution (not just at the end) is the Planner-Executor-Verifier pattern. Implement it by combining this pattern with per-step Critic-Validator gates — no separate pattern entry is needed.

Diagram

  Task
    │
    ▼
┌──────────┐
│  Planner  │  ──► produces structured plan
└──────────┘
     │
     ▼
  [Plan]
  Step 1: ...
  Step 2: ...
  Step 3: ...
     │
  (optional: human review / critic gate)
     │
     ▼
┌──────────┐
│ Executor  │  ──► carries out each step
└──────────┘
     │
     ▼
  Output

When to Use

  • Actions have real-world consequences (file writes, API calls, deployments)
  • Human review/approval of the plan is required before execution
  • Plan is reusable or shareable across multiple execution contexts
  • You want to separate the "what" from the "how"

When NOT to Use

  • Task is too dynamic — plan becomes obsolete as execution proceeds (use ReAct)
  • Planning overhead is significant relative to execution complexity
  • Task is trivial and single-step
  • Plans cannot be validated without partial execution

Example Prompt / Scenario

Scenario: Automated penetration test with human approval gate

PLANNER PROMPT:
"Given the scope in scope.txt, create a detailed penetration testing plan:
- List each test category (recon, auth, injection, etc.)
- For each: specific tools to use, commands to run, success criteria
- Estimated time per phase
- Risk level (which actions could impact availability)
Output as plan.json"

[Human reviews plan.json, approves or modifies]

EXECUTOR PROMPT:
"Execute the approved plan in plan.json step by step.
For each step: log start time, run the specified command,
capture output to results/step-N.txt, log completion.
If a step fails, log the error and skip to next step.
Do not deviate from the plan."

Claude Code:

# Phase 1: Plan
claude -p "Create pentest plan for scope in scope.txt. Write plan.json. Do not execute anything."
# Human reviews plan.json
# Phase 2: Execute
claude -p "Execute approved plan.json. Log all results to results/. Do not add steps not in the plan."

Pairs Well With

Pattern Why
DAG Execution Plan produces a DAG; executor runs it with parallelism
Human-in-the-Loop Human approves plan before execution begins
ReAct Executor uses ReAct within each plan step for adaptive tool use
Critic-Validator Critic reviews the plan before execution, or validates each step (= PEV)
Supervisor Supervisor monitors execution against the plan

9. Reflection / Retry-with-Reflection

Pattern Description

An agent examines its own previous output, identifies weaknesses or errors, and revises accordingly. Reflection is the general pattern: it can be applied proactively to any output, successful or not, to improve quality. Retry-with-Reflection is the failure-triggered variant: when a task fails or produces subpar output, the agent reflects on why it failed before retrying — each retry is informed by accumulated learning.

Both share the same underlying mechanism: critique → hypothesis → revised attempt.

Diagram

── Reflection (proactive) ─────────────────────────────────
  Task
    │
    ▼
Initial Output
    │
    ▼ (N rounds)
  "What did I miss? What's weak? What's wrong?"
    │
    ▼
Revised Output (v2, v3, ...)
    │
    ▼
Final Output

── Retry-with-Reflection (failure-triggered) ──────────────
  Task
    │
    ▼
┌──────────┐  failure  ┌───────────────┐
│  Agent   │──────────►│  Reflection   │
│          │           │  "Why failed? │
└──────────┘           │  What to try  │
     ▲                 │  differently?"│
     │                 └───────┬───────┘
     │  improved approach      │
     └─────────────────────────┘
(max N retries, then escalate or return best attempt)

When to Use

  • Reflection: Output quality improves with self-critique (writing, analysis, code); first pass likely has gaps; no external validator available
  • Retry-with-Reflection: Tasks have clear success/failure criteria; failure modes are diagnosable from output; multiple attempts are acceptable; domain expertise to reflect meaningfully on failures exists

When NOT to Use

  • Agent lacks ability to identify its own blind spots (use external Critic-Validator)
  • Failures are due to external constraints (permissions, missing data) — reflection won't help
  • Max retries will exhaust budget before finding solution
  • Task has no clear success criterion to guide reflection

Example Prompt / Scenario

Scenario — Reflection: Self-improving security advisory

Write a security advisory for CVE-XXXX-YYYY. Then:

Reflection Round 1:
  "Review your advisory. Check: CVSS score accuracy, version completeness,
   PoC reproducibility, remediation coverage. List all weaknesses. Revise."

Reflection Round 2:
  "Review revised advisory. Would a developer understand the impact?
   Would a security engineer understand the technical details?
   Is remediation actionable today? Make final improvements."

Scenario — Retry-with-Reflection: CTF exploit development

Attempt to solve this CTF challenge: [buffer overflow in vulnerable.c]

After each attempt:
1. Run exploit against challenge server
2. If flag captured: done
3. If not: REFLECT:
   - What was the payload?
   - What was the server response?
   - Why might it have failed? (offset? padding? gadget chain?)
4. Generate improved exploit and retry (max 5 attempts)

On final failure, document best attempt and remaining hypotheses.

Claude Code:

claude -p "Write advisory for CVE in cve.txt. Reflect on your output twice,
improving it each time. Write advisory-v1.md, advisory-v2.md, advisory-v3.md."

claude -p "Solve CTF in challenge/. Write exploit.py, run it, check for flag.txt.
If not found, reflect on failure and iterate. Max 5 attempts.
Document each attempt in attempts/attempt-N.md"

Pairs Well With

Pattern Why
Critic-Validator External critic provides what self-reflection misses
Iterative Refinement Reflection drives each refinement cycle
ReAct Failed ReAct steps trigger micro-reflection
Memory-Augmented Store failure patterns to avoid in future attempts
Orchestrator-Worker Orchestrator retries failed workers with reflection

10. Specialist Decomposition

Pattern Description

A complex task is broken into subtasks that map to distinct domains or capabilities. Each subtask is routed to a specialist agent configured (via system prompt, tools, or context) for that specific domain. The decomposition and routing are based on problem structure, not dynamic load.

Diagram

  Complex Task
       │
  ┌────▼────┐
  │Decompose│
  └────┬────┘
       │
  ┌────┴────────────────────────┐
  │     │          │            │
  ▼     ▼          ▼            ▼
[SQL  [Front-   [Security  [Performance
 Spec] end Spec] Spec]       Spec]
  │     │          │            │
  ▼     ▼          ▼            ▼
SQL   React    Security   Perf
Expert Expert  Expert    Expert
  │     │          │            │
  └─────▼──────────▼────────────┘
            Integrator

When to Use

  • Problem requires genuinely distinct expertise (security, UX, database, legal)
  • Specialists benefit from narrow, deep context rather than broad shallow context
  • Domain boundaries are clear and clean
  • Each specialist can work independently of others

When NOT to Use

  • Domains are deeply intertwined (every change in one affects all others)
  • Specialists need to negotiate shared constraints in real-time (use Group Chat)
  • Overhead of managing specialists exceeds benefit for simple tasks
  • You don't have meaningful specialist configurations to differentiate them

Example Prompt / Scenario

Scenario: Full security code review of a web application

Frontend Security Specialist:
  "You are an expert in browser security. Focus exclusively on:
   client-side XSS, CSP headers, CORS misconfigs, localStorage abuse,
   postMessage vulnerabilities, clickjacking."
  Files: src/frontend/**

Backend Security Specialist:
  "You are an expert in server-side security. Focus on:
   SQL injection, command injection, deserialization, auth flaws, SSRF."
  Files: src/backend/**

Crypto Specialist:
  "You are a cryptography expert. Review all crypto usage:
   key management, algorithm choices, IV reuse, padding oracle risks."
  Files: src/**/*crypto* src/**/*auth* src/**/*session*

Infrastructure Specialist:
  "You are a cloud/infra security expert. Review:
   IAM roles, network policies, secrets management, logging."
  Files: terraform/ k8s/ docker/

Pairs Well With

Pattern Why
Dispatcher-Worker-Merger / MoE Dispatcher routes to specialists based on input type
Orchestrator-Worker Orchestrator manages specialist workers
Ensemble Multiple specialists on same domain = ensemble for that domain
Hierarchical Specialists can have sub-specialists
Blackboard Specialists post findings to shared blackboard

11. Human-in-the-Loop (HITL)

Pattern Description

Agent execution pauses at defined checkpoints to request human input, approval, or verification. The human can approve, reject, modify, or redirect. Combines agent efficiency with human judgment for high-stakes decisions.

Diagram

  Task Start
      │
      ▼
  [Agent Phase 1]
      │
      ▼
  ┌──────────────────┐
  │  HUMAN CHECKPOINT│ ◄── "Review and approve before proceeding"
  │  approve/reject/ │
  │  modify          │
  └──────┬───────────┘
         │ (approved)
         ▼
  [Agent Phase 2]
         │
         ▼
  ┌──────────────────┐
  │  HUMAN CHECKPOINT│ ◄── "Verify output before publishing"
  └──────┬───────────┘
         │
         ▼
      Final Output

When to Use

  • Actions are irreversible (deployment, data deletion, external communications)
  • Regulatory or compliance requirements mandate human review
  • Agent confidence is low or task is novel/risky
  • You need accountability and audit trail for decisions
  • Ethical or legal implications require human judgment

When NOT to Use

  • Humans are unavailable or response latency is unacceptable
  • Task is routine and well-validated enough for full automation
  • Human reviewers lack context to evaluate agent output meaningfully
  • HITL becomes a rubber-stamp (humans approve without real review)

Example Prompt / Scenario

Scenario: Automated vulnerability remediation with approval gates

Phase 1 (Agent): Scan codebase and generate remediation patches.
  Output: patches/ directory with one patch per vulnerability.
  Write REVIEW_NEEDED.md listing each patch with risk level.

[PAUSE — Human reviews REVIEW_NEEDED.md, marks each patch APPROVED/REJECTED]

Phase 2 (Agent): For each patch marked APPROVED in REVIEW_NEEDED.md:
  - Apply the patch
  - Run relevant tests
  - If tests pass: stage for commit
  - If tests fail: log failure, do not commit

[PAUSE — Human reviews staged changes before final commit]

Phase 3 (Agent): Create PR with all approved, tested patches.

Claude Code:

# Phase 1
claude -p "Scan for vulns, generate patches, write REVIEW_NEEDED.md. Stop."
# Human modifies REVIEW_NEEDED.md
# Phase 2
claude -p "Apply only patches marked APPROVED in REVIEW_NEEDED.md. Run tests. Stage passing patches."

Pairs Well With

Pattern Why
Plan-then-Execute Human approves the plan before execution
Critic-Validator Human IS the final critic/validator
Pipeline / Staged Pipeline Human gates exist between pipeline stages
Supervisor Human acts as ultimate supervisor authority
Reflection Human provides reflection guidance on failures

12. Speculative Execution

Pattern Description

Multiple parallel agents speculatively execute different possible continuations of a task before it is known which path is correct or needed. The first successful result is used; others are discarded. Trades compute for latency.

Diagram

  Ambiguous Task / Branch Point
            │
    ┌───────┼───────┐
    ▼       ▼       ▼
[Path A] [Path B] [Path C]
(spec.)  (spec.)  (spec.)
    │       │       │
    └───────┼───────┘
            │
       First success
       (others cancelled)
            │
          Result

When to Use

  • Multiple valid paths forward, but which is best is unknown until tried
  • Latency reduction is more important than compute cost
  • Paths are independent and non-destructive to attempt
  • Decision point resolution would take longer than parallel speculation

When NOT to Use

  • Actions have side effects (can't safely "cancel" in-progress actions)
  • Compute cost is prohibitive
  • Paths are sequential or dependent
  • One path is clearly most likely (speculation wastes resources)

Example Prompt / Scenario

Scenario: Exploit development with uncertain vulnerability class

The target has an input field that behaves strangely.
Speculatively execute three exploit attempts in parallel:

Path A: Assume SQL injection — generate SQLi payloads and test
Path B: Assume SSTI — generate template injection payloads and test
Path C: Assume XSS — generate XSS payloads and test

For each path, test against the authorized CTF environment.
Return the result of whichever path achieves code execution or data exfil first.
Cancel remaining paths once one succeeds.

Pairs Well With

Pattern Why
Fan-out/Fan-in Fan-out for speculation; fan-in collects first success
Concurrent Paths must run simultaneously for latency benefit
Ensemble Both speculate, but Ensemble uses all results; Speculative uses first
Reflection Use reflection to decide which speculative path to prioritize next time

13. Blackboard

Pattern Description

Agents share a common "blackboard" (a shared data store, file, or memory) where they post intermediate results. Any agent can read and write to the blackboard. Agents are triggered by new information appearing on the blackboard. Enables emergent coordination without direct agent-to-agent communication.

Diagram

  ┌─────────────────────────────────┐
  │           BLACKBOARD            │
  │  [findings] [hypotheses] [tasks]│
  │  [evidence] [conclusions]       │
  └──┬──────┬──────────┬────────────┘
     │      │          │
     ▼      ▼          ▼
  [Agent  [Agent    [Agent
    A]      B]        C]
  reads/  reads/    reads/
  writes  writes    writes

Each agent monitors blackboard for
new entries it can act on.

When to Use

  • Agents have complementary but unpredictable contributions
  • No single agent has full context — insights emerge from combination
  • Order of agent contributions is unknown in advance
  • Problem-solving resembles collaborative research or investigation

When NOT to Use

  • Strict ordering of steps is required (use Pipeline or DAG)
  • Agents would create write conflicts on shared state
  • Clear task ownership exists (use Orchestrator-Worker)
  • Blackboard grows so large agents can't process it efficiently

Example Prompt / Scenario

Scenario: Collaborative threat intelligence analysis

Shared blackboard: threat_intel.json

Agent 1 (IOC Hunter): Read threat_intel.json. Add new IP/domain/hash IOCs
  found in the provided log files. Write back.

Agent 2 (CVE Correlator): Read threat_intel.json. For any software versions
  mentioned, look up CVEs and add to the "vulnerabilities" section.

Agent 3 (TTP Mapper): Read threat_intel.json. Map IOCs and CVEs to MITRE
  ATT&CK techniques. Add TTPs to "tactics" section.

Agent 4 (Report Writer): Monitor threat_intel.json. When all sections have
  at least 3 entries, generate final_report.md from all blackboard data.

Run all agents concurrently. Each re-reads blackboard before acting.

Pairs Well With

Pattern Why
Swarm Swarm agents communicate via blackboard (stigmergy)
Concurrent Multiple agents read/write concurrently
Dispatcher-Worker-Merger Merger writes to blackboard instead of returning directly
Specialist Decomposition Each specialist reads/writes its domain section
Event-Driven New blackboard entries trigger agent actions

14. Pipeline / Staged Pipeline

Pattern Description

Output of one agent feeds as input to the next in a linear chain. Each agent has a single transformation responsibility.

  • Pipeline: The basic form — a simple chain with no inter-stage coordination. Best for composable transforms where each step's output is a reliable input for the next.
  • Staged Pipeline: Adds quality gates, format normalization, and explicit handoff protocols between stages. Use when propagating bad output forward is costly and each stage transition benefits from validation.

Diagram

── Pipeline (basic) ──────────────────────────────────────────
  Input → [Agent A] → [Agent B] → [Agent C] → Output
           (parse)    (enrich)    (format)

── Staged Pipeline ───────────────────────────────────────────
  Raw Input
      │
  ┌───▼────┐
  │Stage 1 │ ← Ingest & Normalize
  └───┬────┘
      │ ◄── quality gate (validate schema)
  ┌───▼────┐
  │Stage 2 │ ← Enrich
  └───┬────┘
      │ ◄── quality gate (completeness check)
  ┌───▼────┐
  │Stage 3 │ ← Analyze
  └───┬────┘
      │ ◄── quality gate (human review / critic)
  ┌───▼────┐
  │Stage 4 │ ← Report
  └───┬────┘
      │
  Final Output

When to Use

  • Pipeline: Simple linear transforms (translate → summarize → format); output of each step is well-defined; building composable, reusable agent chains
  • Staged Pipeline: Different stages require different tools/prompts; quality gates prevent garbage propagation; pipeline must be debuggable and replayable stage-by-stage

When NOT to Use

  • Stages are independent and could run in parallel (use DAG or Fan-out)
  • A single agent can handle all transformations without quality degradation
  • Any step can fail in ways requiring complex retry logic beyond a gate

Example Prompt / Scenario

Scenario — Pipeline: Process raw vulnerability data into a Jira ticket

Agent 1: "Parse Burp Suite XML. Extract: name, URL, parameter, evidence. Output JSON."
Agent 2: "Take vulnerability JSON. Write professional finding description for
  developers: impact, reproduction steps, evidence. Output markdown."
Agent 3: "Format markdown finding as Jira API JSON payload:
  Summary (< 80 chars), Description, Priority, Labels ['security','pentest']."

Scenario — Staged Pipeline: Vulnerability report processing with gates

Stage 1 - Ingestion: Parse scanner_output.xml → stage1_normalized.json
  Gate: reject malformed entries to rejected.json

Stage 2 - Enrichment: Add CVE details, affected env → stage2_enriched.json
  Gate: verify all findings have cvss_score and affected_env fields

Stage 3 - Prioritization: Score by risk, rank → stage3_prioritized.json
  Gate: confirm top-10 findings have complete data

Stage 4 - Report: Generate executive summary + technical detail + roadmap

Pairs Well With

Pattern Why
Critic-Validator Critic validates output at each stage gate
Human-in-the-Loop Human gates at high-risk stage transitions
DAG Execution Within a stage, DAG parallelism may apply
Map-Reduce Each stage can internally use Map-Reduce for scale
Supervisor Supervisor monitors pipeline health and restarts failed stages
Handoff Rich context transfer between pipeline stages

15. STORM / Outline-then-Write

Pattern Description

STORM (Synthesis of Topic Outlines through Retrieval and Multi-perspective questioning) first generates a comprehensive outline through research and multi-perspective questioning, then writes each section with full context of the overall structure. Produces long, coherent documents that would exceed single-agent context limits.

Diagram

     Topic
       │
       ▼
  ┌─────────┐     questions from
  │Research │ ◄── multiple perspectives
  │  Agent  │
  └────┬────┘
       │ findings
       ▼
  ┌─────────┐
  │ Outline │  ← comprehensive structure
  │  Agent  │
  └────┬────┘
       │ outline + research
       ▼  (fan-out)
  ┌────┴──────────────┐
  │    │      │       │
  ▼    ▼      ▼       ▼
[Sec [Sec  [Sec    [Sec
  1]   2]    3]      4]
  │    │      │       │
  └────▼──────▼───────┘
           │
      ┌────▼────┐
      │ Compile │  ← stitch sections, ensure coherence
      └────┬────┘
           │
      Final Document

When to Use

  • Writing long, structured documents (reports, research papers, wikis)
  • Topic requires broad research before writing can begin
  • Multiple perspectives need to be represented
  • Document sections can be written independently once outline is fixed

When NOT to Use

  • Short documents that fit in one context window
  • Topic is too narrow for an outline structure
  • Sections have deep interdependencies that require reading each other
  • Speed is critical (multi-phase approach adds latency)

Example Prompt / Scenario

Scenario: Generate a comprehensive penetration testing report

Phase 1 - Research Agent:
  "Research this target system from multiple perspectives:
   - External attacker view (what is exposed publicly?)
   - Developer view (what code patterns are risky?)
   - Operations view (what infrastructure issues exist?)
   For each perspective, generate 5 key questions about the system."

Phase 2 - Outline Agent:
  "Using research from Phase 1, create a full pentest report outline:
   Executive Summary / Scope / Methodology / Findings / Remediation / Appendices.
   Each section: 3+ subsections."

Phase 3 - Section Writers (one agent per section, all parallel):
  Each receives: outline + section assignment + relevant findings.
  Output: fully written section in markdown.

Phase 4 - Compiler:
  "Assemble all sections into final_pentest_report.md.
   Ensure consistent terminology, cross-references, and accurate exec summary."

Pairs Well With

Pattern Why
Fan-out/Fan-in Section writing is fan-out; compilation is fan-in
Ensemble Multiple research agents provide diverse perspectives
Pipeline / Staged Pipeline Research → Outline → Write → Compile is a staged pipeline
Map-Reduce Each section maps independently; compiler reduces

16. Collaborative

Pattern Description

Multiple agents work together on a shared artifact, each contributing their expertise. Unlike Ensemble (independent outputs), collaborative agents actively build on each other's work. Unlike Group Chat (conversational), Collaborative is artifact-focused — each agent reads the current state of the shared artifact, improves it from their domain perspective, and passes it on.

Diagram

  Shared Artifact (document/code/plan)
          │
    ┌─────┼─────┐
    ▼     ▼     ▼
 [Agent  [Agent  [Agent
   A]      B]      C]
  reads,  reads,  reads,
  adds,   adds,   adds,
  refines refines refines
    │     │       │
    └─────▼───────┘
     Updated Artifact
    (better than any
     single agent alone)

When to Use

  • Output quality improves when each agent sees others' contributions
  • Artifact is complex enough to benefit from multiple expert passes
  • Agents have complementary (not redundant) improvements to make
  • Creative or analytical work that benefits from layered refinement

When NOT to Use

  • Agents would simply repeat or override each other's work
  • Artifact has clear ownership sections (use Specialist Decomposition)
  • Agents need to negotiate changes in real-time (use Group Chat)
  • Sequential dependency is strict (use Pipeline)

Example Prompt / Scenario

Scenario: Collaboratively improve a security policy document

Start with: security_policy_draft.md

Agent 1 (Legal):
  "Read security_policy_draft.md. Add/improve sections ensuring compliance
   with GDPR, CCPA, and SOC2. Write updated version."

Agent 2 (Technical):
  "Read the updated draft. Improve technical accuracy: ensure all technical
   controls are implementable and precise. Add specifics where vague."

Agent 3 (UX/Readability):
  "Read current draft. Improve clarity: simplify jargon, add examples,
   restructure for logical flow. Do not change substance."

Agent 4 (Security Architect):
  "Read current draft. Identify security gaps, add missing controls,
   strengthen weak language. Final pass for completeness."

Pairs Well With

Pattern Why
Iterative Refinement Collaborative adds multiple dimensions; refinement adds depth
Specialist Decomposition Each collaborator is a specialist
Critic-Validator Final collaborator acts as critic
Blackboard Shared artifact IS the blackboard

17. Hierarchical

Pattern Description

Agents are organized in a tree structure. High-level agents decompose tasks and delegate to mid-level agents, which may further decompose and delegate to leaf agents. Each level operates at a different abstraction level. Hierarchical is recursive Orchestrator-Worker — use it when one level of decomposition is insufficient.

Diagram

           [CEO Agent]
          /            \
    [VP: Recon]    [VP: Exploit]
      /    \          /      \
  [Recon  [Recon  [Web    [Network
   OSINT] Scan]   Exploit] Exploit]

When to Use

  • Task is so large it requires multiple levels of decomposition
  • Different levels of abstraction need different expertise or context
  • Natural organizational hierarchy mirrors task structure
  • Accountability and delegation chains are important

When NOT to Use

  • Task is shallow — one decomposition level is sufficient (use Orchestrator-Worker)
  • All agents need full context (hierarchy creates context silos)
  • Coordination overhead at multiple levels exceeds benefit
  • Flat organization would be more efficient

Example Prompt / Scenario

Scenario: Enterprise-scale security audit

Level 1 - CISO Agent:
  "Plan a full security audit of a 50-application enterprise.
   Delegate to 3 domain VPs: Infrastructure VP, Application VP, People/Process VP."

Level 2 - Application VP Agent:
  "Coordinate security review of all 50 applications.
   Group into: web apps (20), mobile apps (15), APIs (10), legacy (5).
   Spawn specialist teams for each group."

Level 3 - Web App Team Agent:
  "Coordinate review of 20 web applications.
   Assign 4 apps per specialist agent. Aggregate findings by severity."

Level 4 - Specialist Agents (leaf):
  "Review applications [4, 7, 12, 19]. Full security assessment.
   Output findings.json for each."

Pairs Well With

Pattern Why
Orchestrator-Worker Each hierarchy level is an orchestrator-worker relationship
Specialist Decomposition Leaf agents are specialists
Supervisor Each hierarchy level has supervisor responsibilities
DAG Execution Within a level, DAG execution for parallel tasks

18. Fan-out / Fan-in

Pattern Description

A single task is broadcast (fan-out) to multiple agents for parallel processing. Their results are collected and aggregated (fan-in) into a single output. The simplest parallelism pattern. Distinguished from Map-Reduce by not requiring explicit data splitting logic — fan-out/fan-in is task-centric; Map-Reduce is data-centric.

Diagram

       Input
         │
    ┌────▼────┐
    │ Fan-out │
    └────┬────┘
   ┌─────┼─────┐
   ▼     ▼     ▼
[Agent [Agent [Agent
  A]     B]     C]
   │     │     │
   └─────▼─────┘
    ┌────┴────┐
    │  Fan-in │
    └────┬────┘
         │
       Output

When to Use

  • Same work needs to be done for multiple independent inputs
  • Multiple agents produce complementary results that need combining
  • Parallelism provides clear latency benefit
  • Aggregation logic is simple (merge, vote, pick best)

When NOT to Use

  • Inputs are sequential/dependent (use Pipeline)
  • Agent outputs conflict and require complex resolution
  • Compute cost of parallelism exceeds benefit
  • Only one agent is needed

Example Prompt / Scenario

Scenario: Parallel reconnaissance across multiple target domains

Fan-out: Spawn one recon agent per domain from scope.txt:
  "Enumerate subdomains, open ports, and web technologies for [domain]"

Fan-in: Collect all recon JSONs.
  Aggregator: "Merge all results. Deduplicate hosts.
  Identify highest-value targets: exposed admin panels, outdated software,
  unusual open ports. Output attack_surface.md"

Claude Code:

claude -p "Read domains from scope.txt. Spawn one recon agent per domain in parallel
using the Agent tool. After all complete, aggregate results into attack_surface.md
ranked by attack surface value."

Pairs Well With

Pattern Why
Map-Reduce Map IS fan-out; reduce IS fan-in with transform logic
Concurrent Fan-out requires concurrent execution
Orchestrator-Worker Orchestrator manages fan-out; workers do the work
Speculative Execution Fan-out + take first success = speculative execution

19. Debate

Pattern Description

Two or more agents take opposing positions on a question and argue against each other across multiple rounds. A judge agent (or final synthesis) evaluates the arguments and renders a verdict. Surfaces weaknesses in both positions and produces a more nuanced conclusion.

Diagram

     Question
   /           \
[Agent A]    [Agent B]
(Position    (Position
   Pro)         Con)
   │    ←→→→    │    Round 1
   │    ←→→→    │    Round 2
   │    ←→→→    │    Round 3
   \           /
     [Judge]
    renders verdict

When to Use

  • Decision has genuine tradeoffs that reasonable people can disagree on
  • You want to stress-test an argument or design before committing
  • Risk assessment, architectural decisions, policy choices
  • "Devil's advocate" analysis is valuable

When NOT to Use

  • Answer is objectively correct — debate is theater
  • Both agents share the same bias (no real diversity of view)
  • Speed matters more than deliberation
  • The decision-maker is not equipped to evaluate debate arguments

Example Prompt / Scenario

Scenario: Debate immediate vs. coordinated disclosure of a zero-day

Agent A (Immediate Disclosure):
  "Argue FOR immediate public disclosure. Use: vendor unresponsiveness history,
   public right to know, defenders needing to patch, researcher credit,
   vendor accountability."

Agent B (Responsible Disclosure):
  "Argue FOR 90-day coordinated disclosure. Use: giving vendors time to patch,
   avoiding weaponization, legal protections, CERT coordination,
   protecting users during patch window."

Round 1: Each states position (200 words)
Round 2: Each rebuts the other's points (200 words)
Round 3: Each offers final synthesis (100 words)

Judge: "Based on the arguments, what disclosure timeline is most appropriate
  and why? Write disclosure_decision.md with verdict and reasoning."

Pairs Well With

Pattern Why
Critic-Validator Debate is adversarial critic-validator
Ensemble Ensemble agents can argue for/against; debate structures it
Human-in-the-Loop Human judges the debate
Council/Ensemble Council uses debate for high-stakes decisions

20. Swarm

Pattern Description

Many simple agents operate with minimal coordination, each following local rules. Complex, emergent behavior arises from agent interactions. No central coordinator. Agents share state via stigmergy (environment modification — e.g., a shared file or queue) rather than direct communication.

Diagram

  ●→ ●    ●←→●
 ↗     ↘ ↗     ↘
●       ●       ●
 ↘    ↗  ↘    ↗
  ●←→●    ●→ ●

Each ● is a simple agent following local rules.
No central coordinator.
Emergent behavior = complex collective output.

When to Use

  • Problem benefits from parallel exploration of a large solution space
  • No single agent has enough information to coordinate centrally
  • Robustness to individual agent failure is critical (no single point of failure)
  • Emergent behavior (like ant colony path finding) is desirable

When NOT to Use

  • Task requires strict coordination or ordering
  • Emergent behavior is unpredictable in unacceptable ways
  • Problem is well-defined enough for centralized planning
  • Debugging and auditing the system is important (swarms are opaque)

Example Prompt / Scenario

Scenario: Distributed web crawling and vulnerability scanning

Deploy 20 scanner agents with these simple rules:
1. Read unvisited_urls.txt, claim one URL (atomic write to claimed.txt)
2. Visit the URL, check for 10 common vulnerability patterns
3. Write findings to findings/[url_hash].json
4. Extract all links, add new ones to unvisited_urls.txt
5. If no URL available, wait 5 seconds and retry
6. Stop after 1 hour or 5 consecutive minutes of empty queue

No coordinator — agents self-organize around the shared URL queue.
Emergent result: entire site gets scanned with load distributed across agents.

Pairs Well With

Pattern Why
Blackboard Swarm communicates via blackboard (stigmergy)
Concurrent Swarm agents run concurrently
Fan-out/Fan-in Deploy swarm = fan-out; collect findings = fan-in
Event-Driven Swarm agents react to events in shared environment

21. Council / Ensemble

Pattern Description

A structured group of agents, each with a defined role and perspective, deliberates on a question. Unlike Debate (adversarial) or Ensemble (independent), Council members are aware of each other and can build on each other's inputs. A chairperson synthesizes the deliberations into a final recommendation.

Diagram

          ┌─────────────┐
          │  Chairperson │
          └──────┬───────┘
         ┌───────┼───────┐
         ▼       ▼       ▼
     [Security [Legal  [Ops
      Expert]  Expert] Expert]
         │       │       │
         └───────▼───────┘
              Council
           Deliberation
               │
           Synthesis

When to Use

  • Decision requires multiple expert perspectives that must be integrated
  • High-stakes decisions where accountability is important
  • Risk assessment, architectural review, policy decisions
  • Each council member has a distinct, non-overlapping expertise

When NOT to Use

  • Speed is critical (council deliberation is slow)
  • All council members would reach the same conclusion
  • Problem is technical with objective answer (council is overkill)
  • "Deliberation" would just be sequential agent calls with no interaction

Example Prompt / Scenario

Scenario: Decide whether to disclose a critical vulnerability

Security Expert: "Assess technical severity, exploitability, and in-the-wild
  activity. Provide: severity score, time-to-exploit estimate."

Legal Expert: "Assess legal obligations: CVD policy, regulatory requirements,
  contractual obligations. Identify legal risks of delay."

PR/Communications Expert: "Assess reputational impact of disclosure timing.
  Who is affected and how? What messaging is appropriate?"

Operations Expert: "Assess ability to patch before disclosure: development
  complexity, testing time, deployment rollout timeline."

Chairperson: "Review all assessments. Synthesize into:
  Recommended timeline, rationale, key risks, mitigation actions.
  Output: disclosure_decision.md"

Pairs Well With

Pattern Why
Specialist Decomposition Council members are domain specialists
Debate Council can debate specific points before voting
Human-in-the-Loop Human chairperson makes final call
Ensemble Council is structured ensemble with defined roles

22. Magnetic

Pattern Description

Agents are attracted to tasks or other agents based on capability affinity, availability, or priority signals. Tasks "pull" available agents toward them rather than being pushed by a central dispatcher. Self-organizing assignment without explicit routing logic.

Diagram

  [Task: SQL]──────attracts──────►[SQL Expert Agent]
  [Task: UI] ──────attracts──────►[Frontend Agent]
  [Task: ???]──────attracts──────►[General Agent]
                                  (nearest available)

  Agents "orbit" task queue,
  pulled toward best-fit tasks.

When to Use

  • Agent capabilities and task requirements are dynamic and hard to predefine
  • Self-organization is preferable to rigid routing
  • Agent pool has variable availability (some may be busy)
  • Tasks arrive in unpredictable order with varying types

When NOT to Use

  • Task routing is deterministic and well-understood (use Dispatcher-Worker)
  • Agent specialization is rigid and must be enforced
  • Affinity signals are unreliable or absent

Example Prompt / Scenario

Scenario: Dynamic task assignment in a security operations center

Maintain a task queue (tasks.json) and an agent registry (agents.json).

Each agent: {id, capabilities: ["web", "network", "malware"], current_task: null}
Each task:  {id, type: "web_investigation", priority: "high", claimed_by: null}

Agent loop (each of 5 agents runs independently):
  1. Read tasks.json, find highest-priority unclaimed task matching my capabilities
  2. Atomically claim the task (set claimed_by = my id)
  3. Execute the task
  4. Write result, release claim
  5. Repeat

New tasks appear as alerts arrive. Agents self-assign without a coordinator.

Pairs Well With

Pattern Why
Swarm Magnetic IS swarm with capability-based attraction
Dispatcher-Worker-Merger Magnetic replaces explicit dispatcher with emergent routing
Blackboard Task queue on blackboard is the magnetic field
Event-Driven New tasks trigger agent attention (attraction events)

23. Group Chat

Pattern Description

Multiple agents participate in a shared conversational context, taking turns to contribute. Each agent sees the full conversation history. A moderator (or turn-taking protocol) determines who speaks next. Enables real-time negotiation, clarification, and emergent problem-solving.

Diagram

  ┌─────────────────────────────────┐
  │         GROUP CHAT              │
  │                                 │
  │ [Agent A]: "I found XSS here"   │
  │ [Agent B]: "That might be FP,   │
  │             check the CSP"      │
  │ [Agent A]: "Good point. CSP     │
  │             blocks it. Removing"│
  │ [Agent C]: "But what about      │
  │             the iframe bypass?" │
  │ [Moderator]: "Agent A, respond" │
  └─────────────────────────────────┘

When to Use

  • Agents need to negotiate shared conclusions
  • Real-time clarification and correction between agents is valuable
  • Problem-solving benefits from conversational back-and-forth
  • Agents need to challenge and refine each other's claims

When NOT to Use

  • Agents can work independently without seeing each other's work
  • Conversation history grows so large it degrades agent performance
  • Strict parallel execution is needed (chat is inherently sequential)
  • Task is well-structured enough for pipeline or DAG

Example Prompt / Scenario

Scenario: Collaborative threat modeling discussion

Group chat participants:
  - Red Team Agent (offensive mindset)
  - Blue Team Agent (defensive mindset)
  - Architect Agent (system design mindset)
  - Moderator Agent

Moderator: "We're threat modeling the new payment API. Red Team, start."

Red Team: "The tokenization endpoint looks exploitable — rate limiting is weak."
Blue Team: "We have WAF rules for that. But the token storage is concerning."
Architect: "Token storage uses AES-256 but the key management is in-memory only."
Red Team: "In-memory key management = process dump = key extraction."
Blue Team: "We need HSM or at minimum KMS. Can we implement that?"
Architect: "KMS is available. I'll add it to the design. Any other concerns?"

Moderator (after 10 exchanges): "Summarize: identified threats, proposed
  mitigations, open questions. Write threat_model_summary.md"

Claude Code:

claude -p "Simulate a group chat between Red Team, Blue Team, and Architect agents
about the threat model in architecture.md. Each agent takes 3 turns. Moderator
summarizes after 9 total messages and writes threat_model.md."

Pairs Well With

Pattern Why
Debate Group chat can host structured debates
Council/Ensemble Council deliberation can happen via group chat
Collaborative Group chat produces collaborative artifacts
Blackboard Chat history IS the blackboard

24. Handoff

Pattern Description

An agent completes its portion of a task and explicitly transfers responsibility to the next agent, including all relevant context, completed work, and instructions for continuation. Unlike basic Pipeline (blind pass-through), Handoff includes a rich context packet and acknowledgment — the receiving agent has full understanding of what was done, what wasn't, and what to do next.

Diagram

  [Agent A] ──handoff packet──► [Agent B]
              {
                "completed": [...],
                "in_progress": [...],
                "context": "...",
                "next_steps": [...],
                "critical_info": "...",
                "warnings": [...]
              }

When to Use

  • Long-running tasks that exceed single context window
  • Different agents have authoritative knowledge for different phases
  • Continuity of context between agents is critical
  • Tasks span multiple sessions or timeframes

When NOT to Use

  • All work fits in one agent's context
  • Handoff overhead (context packaging) is expensive relative to work done
  • Parallel execution is preferred over sequential handoff

Example Prompt / Scenario

Scenario: Multi-phase penetration test with context handoff

Phase 1 - Recon Agent [completes reconnaissance, then writes]:
handoff.json:
{
  "completed": ["subdomain enum", "port scan", "tech fingerprint"],
  "key_findings": {
    "interesting_hosts": ["admin.target.com:8080", "api.target.com"],
    "tech_stack": {"cms": "WordPress 5.8", "backend": "PHP 7.4"},
    "open_ports": {"8080": "Tomcat admin", "5432": "PostgreSQL (exposed!)"}
  },
  "recommended_next": ["Test Tomcat default creds", "Check PostgreSQL auth"],
  "warnings": ["admin.target.com responds slowly — rate limit carefully"]
}

Phase 2 - Exploitation Agent:
"Read handoff.json. You are taking over from the recon agent.
 They found [summary]. Start with their top recommendation.
 After completing exploitation, create handoff.json for the report agent."

Pairs Well With

Pattern Why
Pipeline / Staged Pipeline Handoff IS pipeline with rich context transfer
Memory-Augmented Handoff context is stored in persistent memory
Human-in-the-Loop Human reviews handoff packet before next agent starts
Plan-then-Execute Plan defines handoff points and context requirements

25. Concurrent

Pattern Description

Multiple agents execute simultaneously with no ordering constraints between them. Each agent operates independently on its assigned work. Pure concurrency — no synchronization required. Distinguished from Fan-out/Fan-in by not requiring an aggregation step.

Diagram

  T=0: ┌────────┬────────┬────────┐
       │Agent A │Agent B │Agent C │
       │running │running │running │
  T=1: │        │        │        │
       │        │        │        │
  T=2: │(done!) │        │(done!) │
       │        │        │        │
  T=3: └────────┴────────┴────────┘
                (all done)

When to Use

  • Tasks are genuinely independent (no shared state, no dependencies)
  • Throughput improvement from parallelism is significant
  • Rate limits or timeouts make sequential processing impractical

When NOT to Use

  • Tasks share state that requires locking
  • Dependencies exist between tasks
  • Parallel overhead exceeds sequential execution time
  • Tasks are trivially fast

Example Prompt / Scenario

Scenario: Concurrent security scans across isolated environments

Run concurrently (no shared state, each writes to its own output dir):

Scan A: "Run Nikto scan against web.target.com. Write to results/web/"
Scan B: "Run Nmap SYN scan against api.target.com. Write to results/api/"
Scan C: "Run testssl.sh against mail.target.com. Write to results/mail/"
Scan D: "Run wpscan against blog.target.com. Write to results/blog/"

Claude Code:

claude -p "Spawn 4 concurrent scanning agents from targets.txt. Each agent scans
one target and writes to results/[target]/. Use the Agent tool with parallel calls.
After all complete, generate summary from all results/ directories."

Pairs Well With

Pattern Why
Fan-out/Fan-in Concurrent = fan-out without required aggregation
Map-Reduce Map phase uses concurrent agents
Swarm Swarm agents run concurrently
DAG Execution Independent DAG nodes run concurrently

26. Supervisor

Pattern Description

A Supervisor agent monitors worker agents, detects failures or quality issues, and intervenes by restarting, reassigning, or escalating tasks. The Supervisor has authority over the worker pool and maintains overall system health. Provides resilience and quality assurance in multi-agent systems.

Diagram

  ┌─────────────────────────────────┐
  │          SUPERVISOR             │
  │  monitors health, quality,      │
  │  and progress of all workers    │
  └───────┬───────────┬─────────────┘
          │           │
    ┌─────▼─────┐ ┌───▼─────┐
    │  Worker A │ │Worker B │
    │  (healthy)│ │(FAILED!)│◄── Supervisor: restart/reassign
    └───────────┘ └─────────┘

When to Use

  • Worker agents run in long-running or unmonitored environments
  • Failures must be detected and recovered from automatically
  • Quality standards must be enforced across all workers
  • System reliability is critical

When NOT to Use

  • Tasks are short-lived enough that failures are acceptable
  • Human monitoring is sufficient
  • Supervisor becomes a bottleneck (too many workers to monitor)
  • Overhead of supervision exceeds benefit

Example Prompt / Scenario

Scenario: Supervised automated scanning with quality enforcement

Supervisor Agent monitors workers scanning targets in targets.json.

Rules:
1. Each worker must complete its target in < 30 minutes
2. Each worker must produce findings.json (even if empty — proves completion)
3. If worker hasn't updated status in 10 minutes: RESTART
4. If worker's findings.json is malformed: REJECT, reassign to new worker
5. After 3 restart failures for same target: ESCALATE to escalations.txt
6. Log all actions to supervisor.log

Done when all targets have valid findings.json or are in escalations.txt.

Pairs Well With

Pattern Why
Orchestrator-Worker Supervisor adds resilience to orchestrator-worker
Hierarchical Each hierarchy level has a supervisor
Reflection Supervisor triggers reflection-based retries
Human-in-the-Loop Supervisor escalates to human when automated recovery fails
DAG Execution Supervisor ensures DAG nodes complete before dependents start

27. Actor Model

Pattern Description

Agents are "actors" — independent units with private state, a message inbox, and behavior defined by how they respond to messages. Actors communicate exclusively by sending messages to each other's inboxes. No shared state. Highly concurrent, highly decoupled.

Diagram

  Actor A          Actor B          Actor C
  ┌────────┐      ┌────────┐      ┌────────┐
  │inbox:[]│      │inbox:[]│      │inbox:[]│
  │state:{…}│     │state:{…}│     │state:{…}│
  └────┬───┘      └────┬───┘      └────┬───┘
       │  msg→          │  msg→          │
       └──────────────► │               │
                        └──────────────►│
                         ◄──────────────┘
                              reply

When to Use

  • High concurrency requirements with many independent agents
  • Each agent needs private state that must not be shared
  • Message-passing decoupling is important for reliability
  • System must be fault-tolerant to individual actor failure

When NOT to Use

  • Agents need to share state directly (use Blackboard)
  • Sequential processing is required
  • Message passing overhead is too expensive
  • Simpler coordination patterns suffice

Example Prompt / Scenario

Scenario: Distributed vulnerability tracker with actor-per-CVE

For each CVE in cve_list.txt, spawn a CVE Actor:
  Inbox: receives "check_status" and "add_affected_system" messages
  State: {cve_id, severity, affected_systems: [], patch_available: bool}
  Behavior:
    on "check_status":          fetch CVE details from NVD, update state
    on "add_affected_system":   add system to affected_systems list
    on "report":                return current state as JSON

Orchestrator Actor: sends messages to CVE Actors, collects states.

Pairs Well With

Pattern Why
Concurrent Actors run concurrently by design
Blackboard Actors can post to blackboard instead of messaging directly
Swarm Swarm agents can be modeled as actors
Event-Driven Actors are triggered by message events

28. Tree-of-Thought (ToT)

Pattern Description

An agent explores multiple reasoning paths simultaneously, structured as a tree. At each step, multiple "thoughts" (partial solutions) are generated, evaluated, and the most promising are expanded. Unpromising branches are pruned. Enables systematic exploration of solution spaces.

Diagram

           [Problem]
          /    |    \
       [T1]  [T2]  [T3]   ← Generate thoughts
      /   \    |    ✗      ← Evaluate / prune T3
   [T1a] [T1b][T2a]
     ✗     |    |
         [T1b1][T2a1]      ← Continue promising branches
           |
        [Solution]

When to Use

  • Problem requires exploring multiple reasoning strategies
  • Early choices have significant impact on solution quality
  • Search space is large but structured
  • Mathematical proofs, complex planning, multi-step puzzles

When NOT to Use

  • Greedy path (single best choice at each step) is sufficient
  • Problem is too open-ended to evaluate intermediate thoughts
  • Compute budget is limited (ToT is expensive)
  • Task is creative/generative where exploration is unstructured

Example Prompt / Scenario

Scenario: Finding an exploit chain for a complex vulnerability

Problem: Achieve RCE on target.com given: XSS, LFI, and SSRF primitives.

Branch 1: XSS → steal admin cookie → admin panel → file upload → RCE
Branch 2: SSRF → access internal Redis → inject config → RCE
Branch 3: LFI → read SSH key → SSH access → RCE
Branch 4: SSRF → access internal Jenkins → execute build → RCE

Evaluate each branch (feasibility 1–5, complexity 1–5, reliability 1–5).
Prune branches with combined score < 8.
Expand top 2 into detailed sub-steps.
Continue until one branch reaches confirmed RCE or all exhausted.

Pairs Well With

Pattern Why
ReAct ToT explores; ReAct executes the chosen path
Speculative Execution Speculatively execute top ToT branches
Plan-then-Execute ToT produces the plan; then execute best path
Critic-Validator Critic evaluates each thought for pruning decisions

29. Tool-Augmented Agent

Pattern Description

An agent is equipped with a set of tools (functions, APIs, shell commands, browser control) it can invoke during reasoning. The agent decides when and how to use tools based on the task. Extends agent capabilities beyond pure language reasoning into real-world action.

Diagram

  ┌─────────────────────────────────┐
  │            Agent                │
  │                                 │
  │  Task → Reason → Choose tool    │
  │                       │         │
  └───────────────────────┼─────────┘
                          │
          ┌───────────────┼───────────────┐
          ▼               ▼               ▼
     [shell_cmd]    [web_search]    [read_file]
          │               │               │
          └───────────────▼───────────────┘
                    Tool Results
                          │
                    Back to Agent

When to Use

  • Tasks require real-world information or actions (web, files, APIs)
  • Pure language reasoning cannot solve the problem
  • Tools provide reliable, authoritative information vs. model knowledge
  • Agent needs to take actions (write files, run commands, make requests)

When NOT to Use

  • All needed information is in the prompt/context
  • Tool use introduces unacceptable risk (destructive commands)
  • Tool latency makes agent too slow
  • Task can be solved through pure reasoning

Example Prompt / Scenario

Scenario: Automated vulnerability verification

You have these tools:
  - http_request(url, method, headers, body) → response
  - run_command(cmd) → stdout/stderr
  - read_file(path) → content
  - write_file(path, content)

Task: Verify the SQLi vulnerability in bug_report.txt.

Use your tools to:
1. Read the bug report to understand the finding
2. Send HTTP requests to reproduce the vulnerability
3. Capture the response as proof of exploitability
4. Run sqlmap in safe mode to enumerate injectable parameters
5. Write a verified finding with proof to verified_finding.md

Pairs Well With

Pattern Why
ReAct ReAct IS tool-augmented reasoning with explicit thought-action loop
Specialist Decomposition Each specialist has a different tool set
Plan-then-Execute Plan what tools to use; execute with them
Supervisor Supervisor can restrict which tools agents may use

30. Memory-Augmented Agent

Pattern Description

An agent maintains persistent memory across tasks or sessions, storing and retrieving relevant information to inform future reasoning. Memory may be episodic (past experiences), semantic (knowledge), procedural (how-to), or working (current context). Enables learning and context accumulation across conversations.

Diagram

  ┌─────────────────────────────────┐
  │            Agent                │
  │                                 │
  │  Query ──► retrieve ──► enrich  │
  │  memory     memory     context  │
  │    │                     │      │
  │    ▼                     ▼      │
  │  [Memory]           [Reasoning] │
  │    ▲                     │      │
  │    └──────── store ◄─────┘      │
  │              new facts          │
  └─────────────────────────────────┘

When to Use

  • Task context exceeds single conversation/context window
  • Patterns from past tasks should inform future decisions
  • Building up a knowledge base over multiple sessions
  • Personalization based on accumulated context

When NOT to Use

  • Task is one-shot with no future reuse
  • Memory retrieval adds latency exceeding the benefit
  • Memory may be stale and mislead rather than inform
  • Privacy constraints prohibit memory persistence

Example Prompt / Scenario

Scenario: Pentest assistant with persistent knowledge base

Before each task: Read memory/pentest_knowledge.md for:
  - Previously found vulnerability patterns in this codebase
  - Known-good payloads that worked against this tech stack
  - Systems already tested and their findings
  - Client-specific constraints and rules of engagement

After each task: Update memory/pentest_knowledge.md with:
  - New vulnerabilities found (with patterns for future detection)
  - Failed approaches (to avoid repeating)
  - New information about system architecture
  - Successful exploitation techniques

Claude Code:

claude -p "Before starting, read memory/pentest_knowledge.md for context.
Complete the assigned scanning task. After completion, update
memory/pentest_knowledge.md with new findings and lessons learned."

Pairs Well With

Pattern Why
ReAct Memory augments ReAct agent with past experience
Reflection Memory stores failure patterns to avoid
Handoff Memory is the handoff mechanism across sessions
Blackboard Blackboard is a shared, multi-agent memory

31. Iterative Refinement

Pattern Description

An agent produces an initial draft, then systematically improves it through multiple revision cycles. Each cycle has a specific improvement focus (accuracy, completeness, clarity, conciseness). Unlike Reflection (self-critique, any trigger), Iterative Refinement uses external feedback, criteria, or test results to guide each iteration — and each pass targets a different dimension of quality.

Diagram

  Task
    │
    ▼
  Draft v1
    │
    ├── Criteria: accuracy
    ▼
  Draft v2
    │
    ├── Criteria: completeness
    ▼
  Draft v3
    │
    ├── Criteria: clarity
    ▼
  Final (all criteria met)

When to Use

  • Quality improves meaningfully across iterations
  • Clear, measurable quality criteria exist for each iteration
  • Output is complex enough that all improvements can't happen at once
  • Code, reports, algorithms, or other structured artifacts

When NOT to Use

  • First draft meets quality bar (iteration is waste)
  • Quality criteria are so vague iterations don't converge
  • Each iteration introduces regressions in previously-met criteria
  • Time constraints prohibit multiple passes

Example Prompt / Scenario

Scenario: Refine a penetration testing report

Iteration 1 - Technical Accuracy:
  "Focus ONLY on technical accuracy. Fix: incorrect CVSS scores, wrong tool
   names, inaccurate exploit descriptions. Write pentest_report_v2.md"

Iteration 2 - Completeness:
  "Focus ONLY on completeness. Add: missing attack vectors, remediation steps,
   references, evidence. Write pentest_report_v3.md"

Iteration 3 - Executive Communication:
  "Focus ONLY on executive summary and business impact.
   Ensure non-technical readers understand risk and required investment.
   Write pentest_report_v4.md"

Iteration 4 - Polish:
  "Fix: formatting, consistency, grammar, heading hierarchy.
   Write pentest_report_final.md"

Pairs Well With

Pattern Why
Reflection Each iteration uses self-reflection
Critic-Validator External critic provides each iteration's feedback
Pipeline / Staged Pipeline Each refinement dimension is a pipeline stage
Human-in-the-Loop Human provides feedback for one or more iterations

32. Event-Driven Agent

Pattern Description

Agents are triggered by external events (file changes, webhook calls, scheduled triggers, messages, alerts) rather than being invoked directly. Each event carries a payload that provides the agent's task context. Enables reactive, real-time agent systems.

Diagram

  External Events
  ┌─────────────┐
  │ File change │──► trigger ──► [Agent] ──► action
  │ Webhook     │──► trigger ──► [Agent] ──► action
  │ Alert       │──► trigger ──► [Agent] ──► action
  │ Schedule    │──► trigger ──► [Agent] ──► action
  └─────────────┘

When to Use

  • Agents should react to real-world events (CI failure, new CVE, alert)
  • Processing is triggered by external systems, not human invocation
  • Real-time response is required
  • System should be always-on without polling

When NOT to Use

  • Task is one-shot and not reactive
  • Events arrive faster than agents can process them
  • Event ordering matters but events are non-deterministic
  • Stateless processing suffices without event-driven complexity

Example Prompt / Scenario

Scenario: Automated CVE triage triggered by NVD feed

Event: New CVE published in NVD RSS feed (checked every 15 minutes)

Trigger agent with payload: {cve_id, description, cvss, affected_products}

Agent task:
  1. Check if affected_products overlap with our_software_inventory.json
  2. If overlap found:
     a. Assess exploitability given our specific configuration
     b. Create Jira ticket with severity and recommended action
     c. Post to #security-alerts Slack channel
  3. If no overlap: log to cve_log.txt and exit

Claude Code with schedule skill:

# /schedule: "Every 15 minutes, check NVD RSS for new CVEs,
#  compare against software_inventory.json, create tickets for matches"

Pairs Well With

Pattern Why
Swarm Event-driven swarm agents react to shared environmental events
Actor Model Actors are triggered by message events
Supervisor Supervisor monitors event-driven agents for failures
Blackboard Events write to blackboard; agents trigger on new entries
Tool-Augmented Agents use tools to react to events (create tickets, send alerts)

33. Subgoal Decomposition

Pattern Description

A high-level goal is recursively broken into progressively smaller subgoals until each is simple enough to execute directly. Each subgoal has clear preconditions and postconditions. Enables complex goal-directed behavior through hierarchical decomposition. Distinguished from Hierarchical by focusing on goals rather than organizational roles.

Diagram

  [High-level Goal]
          │
     ┌────┴────┐
     ▼         ▼
  [Subgoal   [Subgoal
     1]          2]
     │            │
  ┌──┴──┐      ┌──┴──┐
  ▼     ▼      ▼     ▼
[1a]  [1b]  [2a]  [2b]
(atomic)(atomic)(atomic)(atomic)

When to Use

  • Goal is too complex to execute directly
  • Subtasks have clear success criteria
  • Decomposition is natural and recursive
  • Planning at multiple levels of abstraction is needed

When NOT to Use

  • Task is shallow and doesn't benefit from decomposition
  • Subgoals have complex interdependencies (use DAG instead)
  • Decomposition is unclear or arbitrary for the domain

Example Prompt / Scenario

Scenario: Achieve initial access during a red team engagement

Goal: Achieve initial access to target network.

Subgoal 1: Identify attack vector
  1a: Enumerate public-facing services
  1b: Research employee social media for phishing targets
  1c: Check for exposed credentials in public repos

Subgoal 2: Develop payload (given vector chosen in Subgoal 1)
  2a: Select appropriate payload type
  2b: Develop and test payload in isolated environment
  2c: Implement evasion for target AV/EDR (authorized)

Subgoal 3: Deliver payload
  3a: Execute delivery method
  3b: Confirm callback
  3c: Establish persistence

Execute subgoals in order. Verify completion of each before proceeding.

Pairs Well With

Pattern Why
Hierarchical Hierarchy IS recursive subgoal decomposition by role
Plan-then-Execute Plan produces subgoal tree; execute traverses it
ReAct ReAct executes individual atomic subgoals
DAG Execution Subgoal dependencies form a DAG

34. Constitutional / Guided Generation

Pattern Description

An agent generates output under a set of explicit constitutional rules, principles, or constraints. After generation, a Constitutional AI (CAI) critique pass checks for violations and revises. Ensures outputs adhere to safety, ethical, legal, or domain-specific rules throughout generation.

Diagram

  Task + [Constitution / Rules]
            │
            ▼
        Generator
            │
            ▼
        Output Draft
            │
            ▼
  ┌─────────────────────┐
  │ Constitutional Check │
  │ Does output violate │
  │ any rule?           │
  └──────┬──────────────┘
         │
   ┌─────┴──────┐
   ▼             ▼
 No violations  Violations found
 (approved)     → Revise to fix
                → Re-check

When to Use

  • Output must adhere to explicit rules (legal, ethical, organizational policy)
  • Standard generation produces policy-violating content
  • Auditability of constraint enforcement is required
  • Safety-critical domains (medical, legal, financial, security)

When NOT to Use

  • No formal constraints exist
  • Rules are too complex to check algorithmically
  • Compliance checking is the human's responsibility
  • Constitutional overhead degrades output quality

Example Prompt / Scenario

Scenario: Generate remediation advice following responsible disclosure norms

Constitution:
  Rule 1: Never provide working exploit code in client-facing reports
  Rule 2: All CVSS scores must cite the official calculator methodology
  Rule 3: Remediation steps must reference official vendor documentation
  Rule 4: Never speculate about threat actor attribution without evidence
  Rule 5: All findings must have a business impact statement

Generate remediation advice for: [finding details]

Constitutional check (apply after generation):
  "Review against each rule:
   - Rule 1: Exploit code present? [yes → remove]
   - Rule 2: CVSS scores cited? [no → add citations]
   - Rule 3: Vendor docs referenced? [no → add links]
   - Rule 4: Attribution speculation? [yes → remove]
   - Rule 5: Business impact included? [no → add]
   Revise until all rules pass."

Pairs Well With

Pattern Why
Critic-Validator Constitutional check IS a specialized critic
Iterative Refinement Revise until all constitutional rules are met
Human-in-the-Loop Human defines and updates the constitution
Supervisor Supervisor enforces constitution across all worker outputs

35. Role-Playing / Persona

Pattern Description

Agents are assigned specific roles, personas, or characters that constrain their behavior, knowledge, perspective, and communication style. The persona defines what the agent knows, what it prioritizes, and how it responds. Enables highly tailored agent behavior through identity framing.

Diagram

  Same Base Model
       │
  ┌────┴────────────────────────────┐
  │                                 │
  ▼                                 ▼
"You are Alice,              "You are Bob,
 a senior red team            a skeptical CISO
 operator with 15 years       who questions ROI
 of experience. You           of every security
 think offensively first."    investment."
       │                                │
  [Red Team Alice]              [CISO Bob]
  (offensive outputs)           (business-focused)

When to Use

  • Different perspectives require different knowledge/priority framing
  • Roleplay enables simulation of stakeholder views
  • Persona maintains consistent behavior across a long interaction
  • Training scenarios, red/blue team simulations, stakeholder modeling

When NOT to Use

  • Persona constraints conflict with accuracy (character "stays in character" at cost of truth)
  • Task requires neutral, unbiased assessment
  • Persona is too narrow and excludes necessary context
  • User might be misled into thinking they're interacting with a real person

Example Prompt / Scenario

Scenario: Red team / Blue team adversarial simulation

Red Team Agent (Alice):
  "You are Alice, a senior penetration tester with expertise in web attacks.
   You just completed reconnaissance and found: [recon results].
   Think like an attacker. What is your attack plan?
   What is the most likely path to data exfiltration? Be specific."

Blue Team Agent (Bob):
  "You are Bob, a senior SOC analyst. Alice (red team) is attacking right now.
   Based on these log entries: [logs], what is she trying to do?
   What detective controls would catch her? What should you do RIGHT NOW?"

Debrief Agent:
  "Review Alice's attack plan and Bob's defense. Identify:
   - Where would Bob's defenses have caught Alice?
   - Where would Alice have succeeded undetected?
   - What controls are missing?
   Write debrief.md with specific recommendations."

Pairs Well With

Pattern Why
Debate Personas argue from their role's perspective
Group Chat Multiple personas interact in conversation
Ensemble Multiple personas provide diverse viewpoints
Collaborative Personas collaborate from their role's perspective
Council Each council member has a defined role/persona

Pattern Combination Map

The most powerful multi-agent systems combine multiple patterns. Common high-value combinations:

Orchestrator-Worker
  + Specialist Decomposition  → Experts assigned by domain
  + Critic-Validator          → Quality gates on worker output
  + Supervisor                → Resilience against worker failures
  + Fan-out/Fan-in            → Maximum parallelism

Plan-then-Execute
  + ReAct                     → Adaptive execution within each plan step
  + HITL                      → Human approval gate between plan/execute
  + Reflection                → Recover from execution failures
  + DAG Execution             → Parallel execution of independent plan steps
  + Critic-Validator (per-step) → = Planner-Executor-Verifier

STORM / Long Documents
  + Ensemble (research)       → Multi-perspective research phase
  + Fan-out (writing)         → Parallel section writing
  + Critic-Validator          → Quality check each section
  + Collaborative (compile)   → Coherence pass across sections

Security Operations
  + Event-Driven              → Triggered by alerts
  + Dispatcher-Worker-Merger  → Route alerts to specialist analysts
  + Blackboard                → Share findings across analysts
  + Supervisor                → Monitor analyst agents
  + HITL                      → Human approval for high-severity response

Last updated: 2026-04-19 | 35 patterns

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment