5  A Harness for Every Task: Dynamic Workflows Deep Dive

5.1 Under the Hood

The introductory post on dynamic workflows (Chapter 2) explained what they do: Claude writes an orchestration script that spawns parallel subagents. This chapter, based on the June 2, 2026 deep dive, explains how they do it — the execution model, the patterns, and the use cases that make dynamic workflows a general-purpose tool rather than a feature for three specific tasks.

The central technical insight is that a dynamic workflow is a JavaScript file that Claude writes and then executes. The file uses a small set of special functions to spawn subagents, pass them inputs, await their results, and synthesize outputs. By giving Claude a real programming language as its orchestration substrate (rather than a constrained DSL), dynamic workflows become Turing-complete from the start — any coordination pattern you can imagine, you can implement.

5.2 The Execution Model

When you ask Claude to create a dynamic workflow, the following happens:

  1. Claude decomposes the task into a coordination strategy.
  2. Claude writes a JavaScript file using special workflow functions.
  3. Claude executes the file, which spawns subagents as it runs.
  4. Each subagent runs in its own context window, does its work, and returns a result.
  5. The orchestrator collects results and synthesizes a final output.
  6. Adversarial agents (optionally) verify the output before it reaches you.
// Conceptual structure of a dynamic workflow script
const results = await Promise.all(
  files.map(file => spawnSubagent({
    task: `Analyze ${file} for SQL injection vulnerabilities`,
    tools: ['read_file', 'grep']
  }))
);

const synthesized = await spawnSubagent({
  task: 'Synthesize these findings into a prioritized report',
  input: results
});

return synthesized;

The special functions — spawnSubagent, coordination primitives, and synthesis helpers — are the vocabulary Claude uses. Everything else is standard JavaScript, which means Claude can implement arbitrary control flow, conditional logic, and data transformation.

Note

The choice of JavaScript as the orchestration language is deliberate: it is the language Claude is most fluent in, it has native async/await for parallelism, and it is familiar to the developer audience using Claude Code. The workflow functions are a thin API layer over a familiar substrate.

5.3 The Five Coordination Patterns

The deep dive identified five canonical patterns that dynamic workflows can implement. Most real-world workflows are combinations of these, but understanding them individually is the key to designing effective workflows.

5.3.1 Pattern 1: Classifier Routing

In classifier routing, a first agent inspects each incoming task and routes it to the right specialist. This is the agent equivalent of a load balancer that reads the request before deciding where to send it.

[Incoming Task] → [Classifier Agent] → [Specialist A]
                                       → [Specialist B]
                                       → [Specialist C]

Use cases include model routing (send hard tasks to Opus, easy ones to Sonnet), skill routing (route a code task to the testing specialist, a docs task to the writing specialist), and triage (route bug reports to the right team’s agent).

5.3.2 Pattern 2: Fan-Out and Synthesize

The fan-out and synthesize pattern is the workhorse of dynamic workflows. The orchestrator splits a task into independent subtasks, runs them all in parallel, and a synthesizer merges the results.

[Task] → [Split into N subtasks]
           → [Subagent 1] ─┐
           → [Subagent 2] ─┤
           → [Subagent 3] ─┤→ [Synthesizer] → [Output]
           → [Subagent N] ─┘

This is the pattern behind codebase-wide bug hunts, large migrations, and parallel research. The key design decision is the granularity of the fan-out — too coarse and you lose parallelism; too fine and the synthesis overhead dominates.

5.3.3 Pattern 3: Adversarial Verification

Adversarial verification pairs a producer with a breaker. The producer generates the work; the adversarial agent tries to find flaws. The user sees the work only after it survives (or is annotated with) the adversarial pass.

[Task] → [Producer Agent] → [Output]
                              ↓
                         [Adversarial Agent] → [Confirmed / Flagged]

This pattern is essential for critical work verification — security reviews, correctness checks of migrations, and validation of agent-generated code. It creates a structured tension that catches errors a single agent would miss.

Tip

Adversarial verification is most effective when the adversarial agent has a different prompt and different tools than the producer. If both agents reason identically, they’ll make the same mistakes. Give the breaker a different perspective — “assume the producer missed something; what would it be?”

5.3.4 Pattern 4: Tournament / Competition

In the tournament pattern, multiple agents attempt the same task independently, and a judge selects the best result. This is the agent equivalent of a coding competition.

[Task] → [Agent A produces solution] ─┐
       → [Agent B produces solution] ─┤→ [Judge] → [Best solution]
       → [Agent C produces solution] ─┘

Use cases include solution exploration (generate multiple approaches to a hard problem and pick the best), creative generation (write three versions of a component, pick the best), and robustness (for high-stakes decisions, generate independently and compare).

5.3.5 Pattern 5: Iterative Loop

The iterative loop pattern runs a subagent repeatedly, feeding each iteration’s output back as input, until a stop condition is met. This is the dynamic-workflow equivalent of goal-based loops (Chapter 4).

[Task] → [Agent] → [Output] → [Meets criteria?]
                                  ↓ No
                              [Feed back as input] → [Agent] → ...
                                  ↓ Yes
                              [Final output]

Use cases include hypothesis generation and testing (generate a hypothesis, test it, refine, repeat), iterative refinement (improve a design until it meets a rubric), and convergence (refine an estimate until it stabilizes).

5.4 Use Cases Beyond the Core Three

The deep dive expanded the use-case list significantly beyond the three highlighted in the launch post.

5.4.1 Deep Research (/deep-research)

The /deep-research skill is a pre-built dynamic workflow that conducts multi-source research. It fans out subagents to gather information from multiple sources, cross-references findings, and synthesizes a report. The adversarial step checks for unsupported claims.

5.4.2 Fact-Checking

A fact-checking workflow takes a document (or a set of claims), spawns one subagent per claim, each verifies the claim against sources, and synthesizes a report of confirmed, refuted, and unverifiable claims.

5.4.3 Sorting and Ranking

A sorting workflow takes a list of items and ranks them by a criterion. The tournament pattern is natural here: compare items in pairs or groups, and the judge produces a ranked list. This is useful for prioritizing bugs, ranking features, or ordering candidates.

5.4.4 Rule Checking

A rule-checking workflow encodes a set of rules (coding standards, compliance requirements, architectural guidelines) and runs them across a codebase or document set. Each subagent checks one rule against one scope and reports violations.

5.4.5 Hypothesis Generation

For exploratory work — debugging a mysterious issue, understanding a system’s behavior — a workflow can generate multiple hypotheses about the cause, then test each in parallel. The iterative loop pattern refines hypotheses that show promise.

5.4.6 Solution Exploration

When facing a hard design or implementation problem, a tournament workflow generates multiple independent solutions and a judge selects the best — or synthesizes elements from several into a hybrid.

5.4.7 Model Routing

A classifier-routing workflow inspects each task and routes it to the appropriate model. Easy tasks go to a faster, cheaper model; hard tasks go to Opus. This optimizes cost without sacrificing quality on the tasks that need a powerful model.

5.5 Tips for Effective Workflows

The deep dive offered several practical tips for getting the most out of dynamic workflows.

5.5.1 Combine with /goal and /loop

Dynamic workflows can serve as the body of a loop. Combined with /goal (exit-criteria-based looping), a workflow can run repeatedly until a quality bar is met — for example, running a bug-hunt workflow until no new bugs are found. Combined with /loop or /schedule (time-based looping), a workflow can run on a recurring schedule — for example, a nightly security scan.

5.5.2 Set Token Budgets

Because workflows spawn many subagents, costs can scale quickly. Set explicit token budgets to cap spending, especially for exploratory or recurring workflows. Claude Code can prioritize the most valuable subtasks when a budget is tight.

5.5.3 Save and Share Workflows

Once you’ve designed an effective workflow, you can save it and share it with your team. A saved workflow becomes a reusable asset — the orchestration script plus the prompt that generates it. Teams can build libraries of workflows for common tasks (codebase audits, migration patterns, verification suites).

Note

Saved workflows are a form of organizational knowledge capture. The workflow that encodes “how we do a security audit” or “how we verify a migration” becomes a shareable, executable artifact — more durable than a wiki page and more reliable than tribal knowledge.

5.6 Choosing the Right Pattern

Task Type Recommended Pattern
Heterogeneous tasks needing different specialists Classifier routing
Homogeneous task over many items Fan-out and synthesize
High-stakes output needing validation Adversarial verification
Multiple approaches to a hard problem Tournament / competition
Iterative refinement until criteria met Iterative loop

Most real workflows combine patterns. A bug hunt might use fan-out (one subagent per file), adversarial verification (a breaker reviews each finding), and synthesis (merge into a report). Understanding the primitives lets you compose them deliberately.

5.7 Designing Effective Workflows

The flexibility of dynamic workflows — any pattern, any decomposition — means that workflow design becomes a skill. A well-designed workflow produces better results faster; a poorly designed one wastes tokens and produces inferior output.

5.7.1 Granularity: The Key Design Decision

The most important design decision in a fan-out workflow is granularity — how to split the task into subtasks. Too coarse, and you lose parallelism (each subagent does too much). Too fine, and the synthesis overhead dominates (the synthesizer must merge too many tiny results).

Rules of thumb for granularity:

  • One subagent per logical unit (a file, a function, a route, an endpoint).
  • Balance the load — each subagent should do roughly the same amount of work.
  • Minimize dependencies — subagents shouldn’t need to wait for each other.
  • Keep synthesis tractable — the synthesizer should be able to merge results without overwhelming its context.

5.7.2 Prompting for Workflows

When you ask Claude to create a workflow, the clarity of your description determines the quality of the decomposition. Effective workflow prompts include:

  1. The goal — what the workflow should accomplish.
  2. The scope — what part of the codebase or data to cover.
  3. The criteria — how to judge if a subagent’s work is complete.
  4. The output format — how results should be structured for synthesis.
> Create a workflow that checks every API endpoint in the
  /api/v2/ directory for proper input validation. For each
  endpoint, verify that all inputs are validated for type,
  length, and format. Report any endpoints missing validation
  as a table with: endpoint path, missing validations, severity.

5.7.3 Handling Shared State

Some workflows require shared state — information that multiple subagents need to read or write. Dynamic workflows support shared state through the filesystem: subagents can write intermediate results to files that other subagents read. The orchestrator manages access to avoid conflicts.

5.8 Advanced Composition

5.8.1 Nested Workflows

Dynamic workflows can be nested — a workflow’s subagent can itself spawn a workflow. This enables hierarchical decomposition: a top-level workflow decomposes the task into major units; each unit’s subagent runs its own workflow to decompose further.

[Top-Level Workflow]
  ├─→ [Subagent A + nested workflow] → [detailed results]
  ├─→ [Subagent B + nested workflow] → [detailed results]
  └─→ [Synthesizer]

5.8.2 Conditional Workflows

Because workflows are JavaScript, they can include conditional logic. A workflow might run a first pass to assess the codebase’s size and complexity, then decide how many subagents to spawn based on what it finds. This adaptivity — scaling the workflow to the task — is a significant advantage over static scripts.

5.8.3 Combining Patterns in a Single Workflow

Real-world workflows often combine multiple patterns. Consider a comprehensive code review workflow:

  1. Classifier routing determines the type of each file (API code, UI code, tests, config).
  2. Fan-out sends each file to a specialist subagent based on its type.
  3. Adversarial verification has a reviewer check each specialist’s findings.
  4. Synthesis merges everything into a prioritized report.

This single workflow uses four patterns, each contributing a different quality. Understanding the patterns individually (as presented earlier) lets you compose them effectively.

5.9 Common Pitfalls in Workflow Design

5.9.1 Pitfall 1: Over-Decomposition

Spawning too many subagents — one per line of code, for example — creates enormous synthesis overhead and often produces lower-quality results (each subagent has too little context to reason effectively). Find the natural granularity for your task.

5.9.2 Pitfall 2: Under-Specifying Subagent Tasks

Each subagent needs a clear, self-contained task. If the task is vague (“review this file”), the subagent may not know what to look for. Specify what the subagent should do, what to report, and how to format its output.

5.9.3 Pitfall 3: Neglecting the Synthesizer

The synthesizer is the final arbiter of quality. If the synthesizer’s task is underspecified (“combine these results”), it may produce a disorganized merge. Give the synthesizer clear instructions about the desired output format and how to resolve conflicts.

Tip

Treat the synthesizer as the most important subagent in a fan-out workflow. It determines the quality of the final output. Invest in specifying what the synthesizer should produce, how to prioritize findings, and how to resolve conflicts between subagents’ results.

5.10 Measuring Workflow Effectiveness

To assess whether a workflow is well-designed, consider:

  • Coverage: Did the workflow examine all relevant parts of the codebase/task?
  • Precision: Are the findings accurate (low false-positive rate)?
  • Recall: Did it find the issues it should have (low false-negative rate)?
  • Cost: How many tokens did it consume? Was the cost justified by the results?
  • Time: How long did it take? Was the parallelism effective?

Iterate on workflow design based on these metrics. A workflow that produces many false positives needs better subagent task descriptions or stronger adversarial verification. A workflow that misses issues needs finer granularity or broader scope.

5.11 Key Takeaways

  • Dynamic workflows are JavaScript files. Claude writes and executes real code using special functions to spawn and coordinate subagents — Turing-complete orchestration, not a constrained DSL.
  • Five canonical patterns: classifier routing, fan-out and synthesize, adversarial verification, tournament/competition, and iterative loop.
  • Most real workflows combine patterns. A bug hunt might fan-out, verify adversarially, and synthesize.
  • Use cases extend far beyond the core three. Deep research, fact-checking, sorting/ranking, rule checking, hypothesis generation, solution exploration, and model routing are all natural fits.
  • Combine with /goal and /loop to run workflows until a condition is met or on a schedule.
  • Set token budgets to control cost — parallelism multiplies token consumption.
  • Save and share workflows to build organizational libraries of reusable, executable processes.
  • Pattern selection drives effectiveness. Match the coordination pattern to the task structure.