---
name: co-fita-dynamic-workflows
type: analysis
title: "Dynamic Workflows: The Bridge Between Three Ecosystems"
description: "Technical analysis of Claude Code Dynamic Workflows (v2.1.154+), the 6 orchestration patterns, comparison with Co-Fita orchestrator and Antigravity channel protocol, and the integration path for Co-Fita."
tags: [co-fita, dynamic-workflows, claude-code, orchestration, multi-agent, antigravity, ultracode, state-machine, subagents, harness-design]
timestamp: 2026-07-22
---

# Dynamic Workflows: The Bridge Between Three Ecosystems

> **Source:** `DYNAMIC_WORKFLOWS_RESEARCH.md` (2026-07-22)
> **Releases:** Claude Code v2.1.154+ (May 26, 2026)
> **Cross-references:** [[co-fita-harness]], [[co-fita-orchestrator]], [[co-fita-governance]], [[unit-distance-methodology]]

---

## What Are Dynamic Workflows

Dynamic Workflows represent a paradigm shift in Claude Code's orchestration model. Rather than having Claude plan and execute within a single context window, Dynamic Workflows allow Claude to **write a JavaScript orchestration script on the fly** that spawns and coordinates dozens to hundreds of subagents, each with isolated context windows. The runtime executes this script in the background while the user's session stays responsive.

The orchestration plan moves from Claude's context window into executable JavaScript code. This solves three systemic failure modes of single-context agentic work:

| Failure Mode | Dynamic Workflows Solution |
|:---|:---|
| **Agentic laziness** -- Claude stops before finishing and declares victory | Deterministic JS script enforces completion of all subtasks |
| **Self-preferential bias** -- Claude is lenient on its own results | Separate verifier agents with isolated contexts judge independently |
| **Goal drift** -- gradual loss of fidelity across turns | Script encodes the original objective; agents receive focused, isolated goals |

```mermaid
graph TB
    subgraph "User Session"
        U[User Prompt] --> C[Claude Main Context]
        C --> W[Workflow Script Generated]
        C --> R[Report Received]
    end

    subgraph "Workflow Runtime (Background)"
        W --> RT[JavaScript Runtime]
        RT --> A1[Agent 1]
        RT --> A2[Agent 2]
        RT --> A3[Agent N...]
        RT --> SYN[Synthesis / Barrier]
        A1 --> SYN
        A2 --> SYN
        A3 --> SYN
        SYN --> R
    end

    subgraph "Agent Isolation"
        A1 --> CW1[Own Context Window]
        A2 --> CW2[Own Context Window]
        A3 --> CW3[Own Context Window]
    end
```

---

## Architecture and Execution Model

### Core Properties

| Property | Detail |
|:---|:---|
| Intermediate results | Live in script variables, not Claude's context |
| Script persistence | Written to `~/.claude/projects/<session>/` |
| Resumability | Within same session (not across sessions) |
| Mid-run user input | Not supported (only permission prompts can pause) |
| Concurrency | Up to 16 concurrent agents |
| Total agents | Up to 1,000 per run |
| Model per agent | Inherits session model unless script routes differently |

### Script Primitives

The JavaScript runtime exposes a small, purpose-built API:

| Primitive | Purpose | Co-Fita Equivalent |
|:---|:---|:---|
| `agent(prompt, options)` | Spawns one subagent, returns result | `invoke_subagent` or Antigravity `define_subagent` |
| `pipeline(items, fn)` | Fan-out: one agent per item in a list | Orchestrator Phase II batch execution |
| `args` | Global variable for saved workflow parameters | Task spec in `state/task_spec.md` |
| `return` | Final result delivered to user session | Wiki export / Telegram notification |
| `JSON`, `Math`, `Array` | Standard JavaScript for data processing | Python stdlib in harness_core |

**Agent options:**

| Option | Effect |
|:---|:---|
| `label` | Display name in progress view |
| `schema` | JSON Schema for structured output |
| `model` | Override model for this specific agent |
| `isolation` | `"worktree"` for git-isolated execution |

### Permission Model

Workflow subagents always run in `acceptEdits` mode. File edits are auto-approved. Shell commands, web fetches, and MCP tools not in the allowlist can still prompt. This is analogous to Co-Fita's pattern where worker agents operate within scoped roles -- [[co-fita-governance]] enforces scope via proposal categories, while Dynamic Workflows enforce it via tool allowlists.

### Lifecycle

```mermaid
stateDiagram-v2
    [*] --> Generated: Claude writes JS script
    Generated --> Approved: User approves plan
    Approved --> Running: Runtime executes
    Running --> Running: Agents spawned/completed
    Running --> Paused: User pauses (p)
    Paused --> Running: User resumes (p)
    Running --> Completed: All agents done
    Running --> Stopped: User stops
    Stopped --> Running: Resume with cached results
    Completed --> Saved: User presses 's'
    Saved --> [*]: Available as /name command
```

---

## The 6 Named Patterns

Anthropic describes six orchestration patterns that Claude may compose when building workflows. Each implements a different state machine topology in JavaScript control flow.

### 1. Classify-and-Act

```mermaid
graph LR
    I[Input] --> CL[Classifier Agent]
    CL --> |Type A| A1[Agent A]
    CL --> |Type B| A2[Agent B]
    CL --> |Type C| A3[Agent C]
    A1 --> O[Output]
    A2 --> O
    A3 --> O
```

**Topology:** Router. Classify input, then route to specialized agents.

**Co-Fita mapping:** Phase I Ideation already classifies research angles before execution. In Dynamic Workflows, this becomes explicit routing logic.

### 2. Fan-out-and-Synthesize

```mermaid
graph LR
    I[Input] --> SPLIT[Split Tasks]
    SPLIT --> A1[Agent 1]
    SPLIT --> A2[Agent 2]
    SPLIT --> A3[Agent N...]
    A1 --> BARRIER[Barrier / Synthesize]
    A2 --> BARRIER
    A3 --> BARRIER
    BARRIER --> O[Output]
```

**Topology:** Fork-Join. Split task, run agents in parallel, barrier-wait, merge.

**Co-Fita mapping:** Phase II Execution could fan out across multiple approaches simultaneously instead of sequentially. The orchestrator currently tries one approach per iteration; a workflow could try all 3 in parallel.

**Antigravity mapping:** The Research Director spawning multiple hypothesis-verification subagents simultaneously is structurally identical.

### 3. Adversarial Verification

```mermaid
graph LR
    I[Input] --> G[Generator Agent]
    G --> V[Verifier Agent]
    V --> |Pass| O[Output]
    V --> |Fail| G
```

**Topology:** Pipeline with feedback. Generate, verify, accept or reject.

**Co-Fita mapping:** Phase III Red Team Audit. The `RedTeamAuditor` in [[co-fita-harness]] performs exactly this role -- checking for reward hacking (confidence 1.0) and steganography (confidence 0.85). In Dynamic Workflows, this pattern would use separate agent contexts for generator and verifier, eliminating the self-preferential bias problem.

**Antigravity mapping:** The CITATION-VERIFIER subagent role in the unit-distance research.

### 4. Generate-and-Filter

```mermaid
graph LR
    I[Input] --> G[Generate N ideas]
    G --> F1[Filter by rubric]
    F1 --> F2[Deduplicate]
    F2 --> F3[Verify quality]
    F3 --> O[Top M results]
```

**Topology:** Funnel. Generate many, filter to few.

**Co-Fita mapping:** The `EloConsolidator` in [[co-fita-governance]] already implements this as pairwise tournament debate. The Tournament pattern (below) is the Dynamic Workflow equivalent.

### 5. Tournament

```mermaid
graph TB
    I[Input] --> A1[Agent Approach 1]
    I --> A2[Agent Approach 2]
    I --> A3[Agent Approach 3]
    I --> A4[Agent Approach N]
    A1 --> J1[Judge: 1 vs 2]
    A2 --> J1
    A3 --> J2[Judge: 3 vs N]
    A4 --> J2
    J1 --> F[Final Judge]
    J2 --> F
    F --> O[Winner]
```

**Topology:** Bracket. N agents compete pairwise until a winner emerges.

**Co-Fita mapping:** The Elo tournament in `consolidator.py` (K-factor 32, promotion threshold 1200, minimum 3 matches). The key gap: Dynamic Workflows have **no built-in Elo math**. To replicate Co-Fita's tournament, the workflow script must implement pairwise judging with scoring logic in JavaScript.

**Antigravity mapping:** The ELO-RANKER subagent role that calibrated the unit-distance research hypotheses (Elo 1500 for H11 through Elo 2350 for H16).

### 6. Loop-Until-Done

```mermaid
graph LR
    I[Input] --> A[Agent: Do work]
    A --> C{Stop condition met?}
    C --> |No| A
    C --> |Yes| O[Output]
```

**Topology:** Cyclic with guard. Loop until quality stabilizes, no new findings, or no more errors.

**Co-Fita mapping:** The orchestrator's `start_loop(max_iterations)` is a fixed-iteration version. A true loop-until-done would replace the `max_iterations=5` default with quality-convergence detection.

---

## The `ultracode` Effort Level

`ultracode` is a Claude Code setting that combines `xhigh` reasoning effort with **automatic workflow orchestration**. When enabled, Claude plans a workflow for each substantive task without waiting for the user to ask.

| Setting | Behavior |
|:---|:---|
| `/effort ultracode` | Per-session activation |
| `claude --effort ultracode` | Launch flag (v2.1.203+) |
| `ultracode: <task>` | Per-task opt-in keyword (previously `workflow:`) |

With `ultracode` on, a single request can turn into several workflows in sequence: one to understand the codebase, one to make the change, one to verify it. Every task gets this treatment. Token usage increases significantly.

**For Co-Fita:** `ultracode` represents the point where Dynamic Workflows replace manual per-phase orchestration. Instead of Alefita directing each phase, `ultracode` would automatically generate workflows for Planning, Research, Implementation, Review, and Documentation -- with human chancela between phases.

---

## State Machines in Dynamic Workflows

Dynamic Workflows do **not** provide a formal state machine abstraction. There is no `state`, `transition`, or `onEnter`/`onExit` API. The state machine is **implicit in JavaScript control flow**:

- **States** = values of script variables at any point
- **Transitions** = sequential/branching/looping logic
- **Guards** = conditional expressions
- **Actions** = `agent()` and `pipeline()` calls

This contrasts with explicit state machine tools (LangGraph, Temporal, AWS Step Functions):

| Dimension | Dynamic Workflows | Explicit State Machines |
|:---|:---|:---|
| Flexibility | Any topology possible | Constrained to defined states |
| Formality | Informal (JS variables) | Typed states and transitions |
| Visualization | None built-in | State diagrams generated automatically |
| Resumability | Coarse (completed agents cached) | Fine-grained (checkpoint at each state) |

**Comparison with Co-Fita:** The [[co-fita-orchestrator]] implements an explicit 5-phase state machine (Ideation -> Execution -> Audit -> Fixation -> Governance). Dynamic Workflows would model each phase as a workflow invocation with the state machine encoded in the calling script.

**Comparison with Antigravity:** The Antigravity channel protocol (`<|channel|>analysis<|/channel|>`) provided structured separation between reasoning, analysis, and communication. Dynamic Workflows have no equivalent -- agent internal reasoning is opaque to the script, visible only through structured output schemas.

---

## Three-Ecosystem Comparison

### Co-Fita vs Dynamic Workflows vs Antigravity

| Dimension | Co-Fita Orchestrator | Dynamic Workflows | Antigravity 2.0 |
|:---|:---|:---|:---|
| Orchestration | Claude plans turn-by-turn within each phase | JavaScript script holds the plan deterministically | Main agent defines subagents inductively |
| Intermediate results | In Claude's context (task list state) | In script variables (invisible to Claude) | Brain artifacts per conversation |
| Human interaction | Human reviews at each phase boundary | No mid-run user input | Human directs via conversation |
| Reusability | Implicit in CLAUDE.md instructions | Saved `.js` scripts as `/commands` | Per-conversation artifacts |
| Scale | Few subagents per phase | Dozens to hundreds per run | Dozens of invocations per session |
| State persistence | Task list survives across turns | Script variables within run; agents cached | JSONL transcripts + markdown |
| Evaluation | Elo tournament (built-in) | No built-in evaluation | Elo ranking (custom implementation) |
| Philosophy | Human-in-the-loop, dialectical | Autonomous, deterministic | Generate-Debate-Evolve, research-driven |
| Verification | Red Team auditor (steganography, reward hacking) | Adversarial verification pattern | CITATION-VERIFIER subagent |
| Governance | Congress + chancela + Quinquennial Plans | None (developer responsibility) | Research Director authority |

### Pattern Mapping Across Ecosystems

| Dynamic Workflow Pattern | Co-Fita Phase | Antigravity Role |
|:---|:---|:---|
| Classify-and-act | Phase I Ideation (approach selection) | Research Director (hypothesis routing) |
| Fan-out-and-synthesize | Phase II Execution (parallel approaches) | Multiple hypothesis subagents |
| Adversarial verification | Phase III Red Team Audit | CITATION-VERIFIER |
| Generate-and-filter | Elo Consolidator (tournament) | ELO-RANKER (bracket ranking) |
| Tournament | Elo Consolidator (pairwise debate) | Elo tournament across sessions |
| Loop-until-done | Orchestrator `start_loop()` | Generate-Debate-Evolve cycle |

---

## The Elo Gap

Antigravity's most distinctive feature was **Elo-based evaluation** of hypotheses -- a quantitative ranking system that allowed the Research Director to compare approaches across sessions. Dynamic Workflows have no built-in equivalent.

To replicate Elo in Dynamic Workflows:

1. Implement a `judge` function that takes two agent results and returns a preference
2. Use the Tournament pattern for pairwise comparison
3. Track scores in script variables (or in a file via an agent)
4. Use the ranking to filter/evolve hypotheses in a Loop-until-done

```javascript
// Pseudocode: Elo math in a Dynamic Workflow
function eloUpdate(ratingA, ratingB, scoreA, K = 32) {
  const expectedA = 1 / (1 + Math.pow(10, (ratingB - ratingA) / 400));
  const newA = ratingA + K * (scoreA - expectedA);
  const newB = ratingB + K * ((1 - scoreA) - (1 - expectedA));
  return { newA, newB };
}
```

Co-Fita already implements this in `consolidator.py` (301 lines, K-factor 32, promotion threshold 1200). The portability is high -- the Elo math is simple arithmetic, and `Math` is available in the Dynamic Workflows runtime.

---

## Integration Path for Co-Fita

### The Optimal Hybrid

Co-Fita's strength is the **human-in-the-loop at phase boundaries**. Dynamic Workflows' strength is **scale and determinism within a phase**. The hybrid model:

```mermaid
graph TB
    subgraph "Phase 1: Planning"
        P1[Single Agent<br/>Standard subagent]
    end

    subgraph "Phase 2: Research"
        W2[Workflow: Fan-out-and-Synthesize]
        W2A[Research Agent 1]
        W2B[Research Agent 2]
        W2C[Research Agent N]
        W2 --> W2A
        W2 --> W2B
        W2 --> W2C
    end

    subgraph "Phase 3: Implementation"
        W3[Workflow: Fan-out + Loop-Until-Done]
    end

    subgraph "Phase 4: Review"
        W4[Workflow: Adversarial Verification]
    end

    subgraph "Phase 5: Documentation"
        P5[Single Agent<br/>Wiki-maintainer skill]
    end

    P1 -->|"Human chancela"| W2
    W2 -->|"Human chancela"| W3
    W3 -->|"Human chancela"| W4
    W4 -->|"Human chancela"| P5
```

### Phase-by-Phase Mapping

| Co-Fita Phase | Workflow Type | Why |
|:---|:---|:---|
| Phase 1: Planning | Single agent | Strategic; does not benefit from fan-out |
| Phase 2: Research | Fan-out-and-synthesize | Multiple sources in parallel, each with clean context |
| Phase 3: Build | Fan-out per module + loop-until-tests-pass | Each file gets its own agent; iterate until green |
| Phase 4: Review | Adversarial verification per artifact | Eliminates self-preferential bias; separate verifier contexts |
| Phase 5: Docs | Single agent | Deterministic wiki-maintainer; `uv run` scripts |

### Preserving the Chancela

The critical design constraint: Alefita reviews between phases. Dynamic Workflows do not support mid-run user input, so each phase must be a **separate workflow invocation**. The chancela happens in the gap between workflow completions:

```
Workflow 1 (Planning) completes
  -> Alefita reviews plan, gives chancela
    -> Workflow 2 (Research) starts
      -> Alefita reviews findings, gives chancela
        -> Workflow 3 (Build) starts
          -> ...
```

This preserves the [[co-fita-governance]] chancela pattern while gaining Dynamic Workflows' scale advantages within each phase.

### What Replaces What

| Co-Fita Component | Dynamic Workflow Replacement | What Changes |
|:---|:---|:---|
| SearXNG + Crawl4AI in Phase I | Fan-out agents with WebFetch tool | Search becomes agent-level, not harness-level |
| `acp_client.execute_prompt()` | `agent()` primitive | Model routing moves from Python to JS |
| `RedTeamAuditor` (Python) | Adversarial verification agent | Verifier gets its own context window |
| `HashMathVerifier` | Script-level hash computation | JS `crypto` or simplified chain |
| `FailureTree` | Script variable + agent memory | No persistent tree; need file-based agents |
| `EloConsolidator` | Tournament pattern + JS Elo math | Must implement Elo in script |
| Watchdog stall detection | Not needed (JS runtime manages lifecycle) | Watchdog becomes runtime-level |
| Governance integration | Separate workflow per Congress cycle | Congress as its own workflow |

### Saving Workflows for Reuse

Workflows can be saved as `.js` files in:
- `.claude/workflows/` (project-scoped, git-shared)
- `~/.claude/workflows/` (personal, cross-project)

Saved workflows accept input through the `args` global and become available as `/commands`. This replaces Co-Fita's implicit orchestration in CLAUDE.md with explicit, reusable scripts.

---

## What This Means for the Ecosystem

### For Wikifita

Dynamic Workflows can automate wikifita maintenance tasks:
- **OKF compliance audit:** Fan-out per file + adversarial verification against OKF spec
- **Index reconciliation:** Loop-until-done comparing `index.md` against actual pages
- **Link validation:** Fan-out across all wiki links and media URLs, synthesize broken-link report
- **Memory consolidation:** Classify-and-act routing new memories to correct `memorias/` locations

### For the ClickFix Study

The [[clickfix-incident-response]] monitoring protocol (18h cycles) maps to a Loop-until-done workflow:
- Fan out IOC checks across DNS, WHOIS, blockchain, TLS endpoints
- Adversarially verify findings against historical baselines
- Loop until monitoring cycle completes
- Synthesize delta report

### For the Unit-Distance Research

The [[unit-distance-methodology]] Generate-Debate-Evolve loop maps to Dynamic Workflows' pattern composition. The specific gaps (Elo ranking, channel protocol) can be implemented in JavaScript. Migration path:

1. **Generate** = Fan-out-and-synthesize across hypotheses
2. **Debate** = Tournament pattern with pairwise judging
3. **Evolve** = Loop-until-done with quality convergence
4. **Citation verification** = Adversarial verification subagent
5. **Wiki maintenance** = Skill script (already `uv run`)

### For Kaggle Agent Security

The [[kaggle-agent-security]] attack primitives research informs Dynamic Workflows security:
- **Identity steering** -- each subagent should receive a focused, isolated prompt without ambient identity cues
- **Decision-collapsing** -- structured output schemas (`schema` option) prevent the agent from silently omitting requirements
- **Urgency vectors** -- workflow scripts encode the objective deterministically, removing context-pressure triggers
- **Steganography in CoT** -- adversarial verification agents can inspect intermediate outputs with their own clean context

---

## Design Constraints

1. **No mid-run user input** -- chancela happens between workflow invocations, not within them
2. **No built-in evaluation** -- Elo math must be implemented in JavaScript within the script
3. **No channel protocol** -- agent reasoning is opaque; only structured output is visible
4. **Coarse resumability** -- completed agents are cached; running agents are not checkpointed
5. **Script fragility** -- a bug in the generated JS produces undefined behavior; no state machine validator
6. **Token cost** -- `ultracode` significantly increases token usage; model routing to cheaper models for non-critical stages is available

---

## Open Questions

1. **Nested workflow invocation** -- Can a workflow call another saved workflow (e.g., `/deep-research` from within a custom workflow)? Not documented.
2. **Cross-session state** -- Agent-memory may bridge the gap, but this is not explicitly addressed.
3. **Maximum script complexity** -- Beyond 16-concurrent / 1000-total caps, no documented limits.
4. **Error handling** -- How the runtime handles JS errors, agent failures, and timeouts is not detailed.
5. **`pipeline()` concurrency** -- Whether items run sequentially or concurrently (up to 16-agent limit) is implied concurrent but not stated.

---

*This document is alive. It evolves as the research evolves. Challenge it. Improve it. That is the protocol.*
