# Deep-Dive DD-12 — CrewAI: Role-Based Multi-Agent (Emergent Coordination)

**Course**: Master Course
**Deep-Dive**: DD-12
**Duration**: 60 minutes
**Level**: Senior Engineer and above
**Prerequisites**: Modules 0–12; DD-01–11 (especially DD-10 LangGraph, the declared-coordination pole)

> *45,900+ stars. Most accessible multi-agent framework. Role-based sequential/concurrent crews. 1.8s avg latency. The emergent-coordination pole — paired with LangGraph (DD-10) as the declared-coordination pole, both load-bearing for Course 4 E09 (Multi-Agent Orchestration).*

---

## Learning Objectives

After this deep-dive, you will be able to:

1. State CrewAI's defining contribution — the role-based mental model — and explain why "describe the team" is the most accessible entry point into multi-agent orchestration in the roster.
2. Distinguish CrewAI's **emergent coordination** (the graph emerges from task context references and process type) from LangGraph's **declared coordination** (the graph is a first-class object you draw), and explain why this contrast defines the multi-agent coordination axis.
3. Describe the three primitives (`Crew`, `Agent`, `Task`), the two orchestration modes (sequential, concurrent/hierarchical), and the role-to-prompt mapping (role + goal + backstory = system prompt).
4. Score CrewAI 33/60 and defend the shape: 4/5 on Module 1.3 (Subagents — sequential crews are a textbook multi-agent pattern), low on production-readiness modules (sandbox 1/5, verification 1/5, security 1/5).
5. Articulate the security implications of crew-scoped shared memory (no per-agent write isolation — Module 4.3 write-gating unavailable by default) and the untrusted-content boundary at each task handoff.
6. Connect CrewAI to Course 4's E09 Multi-Agent Orchestration module as the emergent-coordination reference, paired with LangGraph as the declared-coordination reference.

---

## The Subject

| Metric | Value |
| --- | --- |
| Category | Multi-agent framework (role-based orchestration) |
| Stars | 45,900+ |
| Language | Python |
| Typical latency | ~1.8s avg per crew kickoff |
| Orchestration model | Role-driven (sequential or concurrent/hierarchical processes) |
| Core abstractions | `Crew`, `Agent`, `Task` |
| Tool sharing | Per-agent; tools attach to agents, not the crew |
| Memory | Short-term (crew-scoped), long-term, entity memory (opt-in) |
| Sandbox | None (you bring your own — Docker, E2B, etc.) |
| Score | 33/60 — highest on Module 1.3 (Subagents, 4/5) |

CrewAI is the **role-based multi-agent framework** — the most accessible entry point into multi-agent orchestration. Where LangGraph (DD-10) makes you draw explicit nodes and edges, and the OpenAI Agents SDK (DD-11) hands you handoffs and agents-as-tools as primitives, CrewAI asks you to do something far more intuitive: *describe the team you wish you had, and it runs.*

A `Crew` is a set of `Agent`s (each defined by `role`, `goal`, `backstory`, and an optional `llm`) and a list of `Task`s (each assigned to an agent, with expected output and optional context dependencies). `crewai kickoff` reads the process type (`sequential` or `concurrent`) and dispatches. That is the entire mental model — and the entire reason it has 45,900+ stars.

---

## Architecture — The Three Primitives

### 1. Agent — the unit of role

An agent is its system prompt assembled from `role` ("Senior Researcher"), `goal` ("find the most relevant sources"), `backstory` ("20 years at the New York Times, ruthless about provenance"), plus the tool set it's allowed to call. **Role is the system prompt.** This is the load-bearing insight: CrewAI does not give you a raw system-prompt string; it gives you a templated one whose fields are role/goal/backstory. The template is the framework's opinion. This is Module 12 (Prompt Assembly) applied at the *agent* granularity rather than the harness granularity.

### 2. Task — the unit of work

A task has a `description`, an `assigned_agent`, an `expected_output`, and optional `context` (other tasks whose output feeds this one). Tasks carry the dependency graph **implicitly**: if Task B lists Task A in `context`, A runs first and its result is injected into B's prompt. The graph is not drawn; it emerges.

### 3. Crew — the unit of orchestration

The crew holds the agents, the tasks, and the `process` strategy. It owns the loop, the memory, and the kickoff entry point.

---

## Two Orchestration Modes

**Sequential** is the default and the well-trodden path. Tasks run in list order; each task's output is appended to a shared context the next agent reads. This is a linear ReAct chain stretched across multiple roles — conceptually close to Module 1's conversation-driven loop, except each turn is owned by a different role-shaped system prompt.

**Concurrent (hierarchical)** adds a manager agent that decomposes the goal, assigns subtasks to the worker agents, runs them, and synthesizes results. This is closer to the meta-hierarchy in DD-06 (oh-my-opencode's Sisyphus/Prometheus/Atlas/Junior taxonomy) — except CrewAI's manager is implicit and the hierarchy is one level deep, whereas DD-06's is a deliberate multi-tier design.

---

## The Emergent-vs-Declared Coordination Axis — The Load-Bearing Contrast

This is the central architectural claim of the deep-dive, and it is load-bearing for Course 4's E09 (Multi-Agent Orchestration) module.

**CrewAI — emergent coordination.** You define roles and tasks. The coordination graph *emerges* from task `context` references and the process type. You never draw an edge. This is simpler to declare and more intuitive for first-time builders — "describe the team" beats "draw the graph." The cost: the emergent graph is invisible. For a 3-agent crew this is a feature; for a 15-agent crew it becomes a liability (the implicit dependency graph cannot be audited, checkpointed at specific nodes, or edited without rerunning the crew).

**LangGraph (DD-10) — declared coordination.** You draw explicit nodes and edges. The graph is a first-class object you can visualize, checkpoint, and edit. This is more ceremony upfront but the graph is fully auditable — you can interrupt at any node, resume from any checkpoint, and prove properties about the flow. The cost: every edge must be declared; the ceremony scales with crew complexity.

These two frameworks **define the multi-agent coordination axis.** CrewAI is the emergent-coordination pole; LangGraph is the declared-coordination pole. Every other multi-agent framework in the roster sits between them. Course 4's E09 module takes this axis as its organizing principle: when you choose a multi-agent architecture, you are choosing where to sit on this axis, and the choice is a tradeoff between declaration speed (CrewAI) and auditability (LangGraph).

The diagnostic question: *do you need to prove properties about the coordination graph?* If yes (compliance, security audit, reproducibility), declared coordination (LangGraph) earns its ceremony. If no (prototyping, internal tools, exploratory work), emergent coordination (CrewAI) earns its speed.

---

## How Roles Map to System Prompts

CrewAI's role-to-prompt mapping is opinionated and worth reading in source. Each agent's system prompt is assembled roughly as:

```
You are {role}.
Your personal goal is: {goal}
Your backstory: {backstory}
You have access to the following tools: {tool_names_and_schemas}
...
```

This is Module 12 (Prompt Assembly) applied at the *agent* granularity rather than the harness granularity. The framework's value proposition is that you never hand-author a system prompt — you fill in three fields and the template does the rest. The risk is the inverse: when the template is wrong for your use case, you are fighting the framework's opinion rather than editing a string.

---

## Tool Sharing and the Crew Boundary

Tools attach to agents (`Agent(tools=[...])`), not to the crew. This means each agent's capability surface is scoped at declaration time — which is, structurally, a form of Module 2.4 per-agent capability scoping. The catch: there is no enforcement that two agents can't share the same dangerous tool, and no built-in mechanism to *prevent* an agent from passing instructions to a downstream agent that would cause it to call a tool the upstream agent doesn't have. Per-agent scoping exists by construction; per-agent *capability isolation* does not.

---

## Memory Model — Crew-Scoped Shared Store

CrewAI offers three opt-in memory tiers:
- **Short-term** — crew-scoped; recent task outputs are retained for the crew's run.
- **Long-term** — persists across crew runs (backed by a local or remote store).
- **Entity memory** — keyed by named entities (people, orgs, codebases) so an agent can recall facts about a specific subject.

This maps cleanly to Module 4's memory tiers. The notable design choice is that memory is **crew-scoped, not agent-scoped** — all agents in a crew share the same memory store. That is convenient for collaboration but eliminates the per-agent memory isolation that Module 4.3 (write-gating) would want. A compromised agent can write into shared memory that every other agent later reads. This is the same poisoning-surface argument as Hermes (DD-08), except here the compounding happens *across agents within a single crew run*, not across sessions.

---

## When Role-Based Multi-Agent Is Right (and Wrong)

**Right:** work that genuinely decomposes along role lines — research-then-write, draft-then-review, plan-then-execute. When the subtasks have clean handoffs and each benefits from a distinct persona/policy, the role abstraction earns its keep. The classic example is "research a topic, then write a blog post, then edit it" — three roles, three skill profiles, sequential dependencies. CrewAI's mental model fits this almost perfectly.

**Wrong:** work that is really a single reasoning thread wearing different hats. If Task 2 needs everything Task 1 produced plus the ability to revise it, you don't have two agents — you have one agent with a checkpoint. Spinning it into a crew adds latency, token cost (each agent re-reads context), and a new injection surface (the task-output handoff) without adding capability. The temptation in CrewAI is to role-ify everything because the abstraction is so pleasant; the cost shows up in the bill and in the attack surface.

The diagnostic question: *could one agent with one system prompt and a subtask list do this?* If yes, you don't need a crew. If the roles genuinely carry different policies, tool sets, or verification duties, the crew earns its overhead.

---

## Score: 33/60

| Module | Score | Key decision | Notes |
| --- | --- | --- | --- |
| 1 Loop | 3/5 | Role-per-turn, conversation-driven | token-heavy; no steering mid-crew |
| 1.3 Subagents | 4/5 | Sequential crews + hierarchical manager | textbook multi-agent pattern; hierarchical shallower than DD-06 |
| 2 Tools | 3/5 | Per-agent attachment | good; no isolation enforcement |
| 3 Context | 2/5 | Re-reads shared context | no compaction |
| 4 Memory | 3/5 | Three tiers exist | crew-scoping forfeits write isolation |
| 5 Sandbox | 1/5 | None | bring your own |
| 6 Permission | 2/5 | No per-action gates | |
| 7 Errors | 2/5 | Basic | a failing task can sink a crew |
| 8 State | 2/5 | Limited checkpointing | long crews don't resume |
| 9 Verification | 1/5 | None built-in | |
| 10 Observability | 2/5 | Run logs | below the structured-event floor |
| 11 Security | 1/5 | No security model | shared memory is an attack surface |
| **TOTAL** | **33/60** | | |

Highest on Module 1.3 (Subagents): 4/5 — sequential crews are a textbook multi-agent pattern, and the role-based mental model is the most accessible in the category. The low scores across production-readiness modules (sandbox 1/5, verification 1/5, security 1/5) reflect that CrewAI is a framework for orchestration, not a production harness.

### Architect's Verdict

> *CrewAI optimizes for accessibility — the fastest way to stand up a multi-agent crew with role-based task assignment, and the most legible mental model ("describe the team") in the multi-agent category. It sacrifices production-readiness: no sandboxing, crew-scoped shared memory with no write isolation, limited state, and run logs below the structured-event floor. Build on CrewAI to prototype multi-agent patterns and to teach orchestration; move to LangGraph (DD-10) when the dependency graph needs to be explicit and auditable, or to the Agents SDK (DD-11) when you need sandboxing and handoffs as primitives. CrewAI is the emergent-coordination pole of the multi-agent axis — load-bearing for Course 4 E09.*

### MLSecOps Relevance

> *Role-based crews inherit all agents' combined permissions: a compromised agent can influence downstream agents via task outputs (indirect prompt injection across the handoff boundary) and can poison the crew-scoped shared memory every other agent later reads. Per-agent capability scoping (Module 2.4) exists by construction but per-agent isolation does not; the shared memory tier makes Module 4.3's write-gating defense unavailable by default. Treat every task-output handoff as an untrusted-content boundary (Module 2.4 Vector 1).*

### Three things CrewAI does better

1. **Role-based mental model**: the most accessible entry point into multi-agent orchestration in the roster. "Describe the team" beats "draw the graph" for first-time builders.
2. **Sequential crews as a clean pattern**: the default process type composes well for research-then-write, draft-then-review, plan-then-execute workloads.
3. **Per-agent tool attachment**: structurally gives you per-agent capability scoping at declaration time — closer to Module 2.4 than most frameworks that attach tools at the harness level.

### Three things to fix

1. **Make the dependency graph explicit at scale** — the emergent graph from task `context` references is invisible past ~5 tasks; offer a LangGraph-style visualization/checkpoint path.
2. **Offer agent-scoped memory** — crew-scoped shared memory forfeits the Module 4.3 write-gating defense by default; let memory isolation be opt-in.
3. **Emit structured per-agent events** — the run logs are below the observability floor; adopt an event union so a crew run produces a trace, not a log.

---

## Anti-Patterns

### Role-ifying everything because the abstraction is pleasant
The temptation in CrewAI is to turn every multi-step task into a crew because the role/goal/backstory template is so intuitive. The cost: each additional agent adds latency, token cost (each agent re-reads shared context), and a new injection surface (the task-output handoff). Cure: use the diagnostic question. If one agent with one system prompt and a subtask list could do the work, you don't need a crew. Reserve multi-agent for work that genuinely decomposes along role lines with different policies, tool sets, or verification duties.

### Treating task-output handoffs as trusted
Each task-output handoff is an untrusted-content boundary. A compromised upstream agent can inject instructions into its task output that the downstream agent reads and acts on (indirect prompt injection across the handoff). Cure: treat every handoff as untrusted input (Module 2.4 Vector 1). Validate task outputs before injecting them into the next agent's prompt; do not assume the upstream agent's output is benign just because the upstream agent was declared with a benign role.

### Deploying CrewAI crews without sandboxing
CrewAI has no built-in sandbox (Module 5: 1/5). If your agents execute tools with side effects (file writes, API calls, code execution), those tools run on the host with no isolation. Cure: bring your own sandbox (Docker, E2B) and route tool execution through it. This is the same lesson as NemoClaw (DD-09) and the Agents SDK (DD-11) — isolation is not optional in production — except CrewAI makes it bring-your-own rather than baked in.

---

## Key Terms

| Term | Definition |
| --- | --- |
| **Role-based multi-agent** | The coordination model where agents are defined by role/goal/backstory (the system prompt template), and the crew structure emerges from task assignments rather than explicit graph edges. |
| **Emergent coordination** | The coordination graph is not drawn; it emerges from task `context` references and the process type. Simpler to declare, harder to audit. CrewAI's pole on the multi-agent coordination axis. |
| **Declared coordination** | The coordination graph is a first-class object you draw (nodes, edges). More ceremony, fully auditable. LangGraph's (DD-10) pole on the multi-agent coordination axis. |
| **Sequential crew** | The default process type: tasks run in list order, each task's output appended to shared context the next agent reads. A linear ReAct chain across multiple roles. |
| **Concurrent/hierarchical crew** | A manager agent decomposes the goal, assigns subtasks to workers, synthesizes results. One-level hierarchy (shallower than DD-06's multi-tier design). |
| **Crew-scoped memory** | All agents in a crew share the same memory store. Convenient for collaboration; eliminates per-agent write isolation (Module 4.3 write-gating unavailable by default). |
| **Task-output handoff** | The boundary where one agent's output becomes another agent's input. An untrusted-content boundary (Module 2.4 Vector 1) — indirect prompt injection can propagate through it. |

---

## Lab Exercise

See `07-lab-spec.md`. You simulate a CrewAI-style role-based crew in pure Python: define agents with role/goal/backstory, assign tasks, run a sequential crew, observe the emergent dependency graph, and demonstrate the security risk (indirect prompt injection propagating through a task-output handoff into crew-scoped shared memory).

---

## References

1. **CrewAI source** — the role-based multi-agent reference.
2. **Module 1** — conversation-driven loop architectures; CrewAI's role-per-turn is a multi-agent instance.
3. **Module 1.3** — subagents; sequential crews and the hierarchical manager.
4. **Module 2.4** — per-agent capability scoping (exists by construction) and the untrusted-content boundary at each task handoff.
5. **Module 4 / 4.3** — memory tiers; crew-scoped shared memory and the absent write-gating defense.
6. **Module 12** — prompt assembly; CrewAI's role/goal/backstory template is Module 12 applied at agent granularity.
7. **DD-06 (oh-my-opencode)** — the meta-hierarchy comparison; CrewAI's hierarchical manager is a shallower instance of Sisyphus/Prometheus/Atlas/Junior.
8. **DD-08 (Hermes)** — the shared-memory poisoning parallel; crew-scoped memory compounds poisoning across agents within a run, as Hermes's skill store compounds it across sessions.
9. **DD-09 (NemoClaw)** — the sandbox-is-not-optional lesson; CrewAI has no built-in sandbox (Module 5: 1/5), so isolation is bring-your-own.
10. **DD-10 (LangGraph)** — the declared-coordination pole; CrewAI is the emergent-coordination pole. The contrast defines the multi-agent coordination axis, load-bearing for Course 4 E09.
11. **DD-11 (OpenAI Agents SDK)** — handoffs + agents-as-tools as primitives; the production path with sandboxing, contrasted with CrewAI's prototyping-first approach.
12. **Course 4 E09 (Multi-Agent Orchestration)** — the course module that takes the emergent-vs-declared coordination axis as its organizing principle.
