Multi-Agent Orchestration: Teams, Protocols & Worktrees Explained
TechWhistle · 2026-04-22 · 11м 36с · 1 213 просмотров · YouTube ↗
Топики: ai-loop-engineering
🎧 Аудио
📝 Summary
model=deepseek-v4-flash · prompt=summary-v7 · 4 257→1 815 tokens · 2026-07-20 12:02:42
🎯 Главная суть
Multi-agent системы эффективны только при правильно спроектированном координационном слое. Вместо хаоса из пяти терминалов, указывающих на один репозиторий, используется архитектура с постоянными агентами-тиммейтами, единым протоколом сообщений, автономным захватом задач из общей доски и изоляцией рабочих директорий через Git WorkTree.
Четыре режима отказа наивной multi-agent архитектуры
Если запустить пять агентов в одном репозитории без координации, возникают четыре предсказуемые проблемы: файловые конфликты (один агент перезаписывает то, что сделал другой), состояния гонки (тесты запускаются до коммита изменений), дублирование работы (два агента берут одну задачу) и тупиковая коммутация (агент ждёт ответа от уже завершившегося коллеги). Все эти сбои решаются на уровне архитектуры, а не модели.
Тиммейты — постоянные агенты с идентичностью и почтовым ящиком
Распространённый подход — создавать временных сабагентов «под задачу», которые выполняют код и завершаются. Такой подрядчик не помнит прошлого. Альтернатива — тиммейт: постоянный агент с именем (например, back-end agent), стабильным идентификатором и почтовым ящиком — очередью сообщений, обрабатываемой по порядку. Лидирующий агент не запускает подзадачи напрямую, а отправляет сообщение в нужный ящик. Это даёт два преимущества: контекст лидера остаётся чистым (детали выполнения не засоряют его), и тиммейты переживают сброс контекста у лидера. Такой паттерн валидирован трёхзвенной схемой Anthropic (Planner → Generator → Evaluator), где каждый специалист работает в своём контекстном окне.
Протокол «запрос-ответ» с корреляционными ID
Без протокола агенты говорят мимо друг друга: один сообщает «схема базы готова», второй уточняет «какая версия?», первый отвечает «последняя», второй зависает в ожидании. Для устранения неоднозначности вводится единая структура сообщения из четырёх полей: ID (уникальный идентификатор сообщения), type (request или response), payload (содержание) и correlation ID (на ответе — ID исходного запроса). Когда Agent A отправляет запрос с ID 007 на валидацию файла, Agent B отвечает с correlation ID 007. Agent A точно знает, какой запрос закрыт, даже если между ними пришло 20 других сообщений. Этот же паттерн лежит в основе HTTP, gRPC и event-driven систем.
Автономный захват задач с общей доски
Лидирующий агент не должен назначать каждую задачу — это превращает его в бутылочное горлышко. Вместо этого архитектура состоит из четырёх состояний: Idle (нет задачи), Scan (агент каждые несколько секунд сканирует общую доску — JSON-файл со списком задач и их статусами), Claim (если задача свободна и подходит скиллам, агент атомарно записывает на неё своё имя; при одновременной записи двух агентов — атомарность гарантирует, что один проигрывает и ищет другую задачу), Resume (агент возобновляет работу с сохранённого контекста задачи). По завершении задача помечается сделанной, агент возвращается в Idle. Теперь лидер не назначает, а пишет задачи на доску. Компания Fountain, используя иерархическую multi-agent оркестрацию, добилась двукратного роста конверсии кандидатов — оркестратор пишет требования на общую доску, специализированные агенты заявляют индивидуальные оценки.
Изоляция рабочих директорий через Git WorkTree
Даже при автономном захвате задач пять агентов, пишущих в один репозиторий, столкнутся с блокировками Git, перезаписью файлов и устаревшими чтениями. Решение — каждому агенту выделить собственный Git WorkTree: отдельную рабочую директорию, указывающую на свою ветку, но разделяющую общее хранилище объектов. Agent 1 чекаутит feature/auth в worktrees/auth, Agent 2 — feature/dashboard в worktrees/dashboard. Они делят историю, но не директорию. Когда задача завершается, WorkTree сливается и удаляется. Конфликты обнаруживаются стандартными средствами Git на этапе merge, а не скрыто во время активной работы. Практическое ограничение: на современном ноутбуке продуктивно работают 5–7 параллельных агентов; дальше упираются в лимиты API, дисковое потребление (≈5 ГБ на один WorkTree на большой кодовой базе) и накладные расходы на ревью слияний.
Полный агент — объединение всех 12 механизмов в одном файле
Финальный артефакт серии — файл s_full.py, меньше 300 строк Python. Он объединяет цикл агента с bash-инструментами (первые уроки), todo-записи, сабагентов, скиллы, сжатие контекста, граф задач на диске, фоновые операции, а также команды тиммейтов, протокол общения, автономный захват и изоляцию WorkTree. Для сборки такого агента не нужны Claude Code, LangChain или CrewAI — достаточно Bash, API-ключа и этих 12 механизмов.
Три практических ограничения перед масштабированием
Первый: параллельные агенты умножают расход токенов — пять агентов по 200 000 токенов за запуск упрутся в лимиты API за минуты. Бюджетируйте заранее. Второй: изоляция WorkTree предотвращает конфликты записи во время выполнения, но не отменяет конфликты слияния при интеграции — пять веток, модифицирующих общие утилиты, дадут серьёзный overhead на ревью. Третий: сброс контекста между сессиями означает, что тимейты начинают свежими — постоянная идентичность не даёт постоянных знаний. В каждую задачу нужно встраивать структурированный артефакт передачи (summary того, что сделано и что осталось). Anthropic называет это «context reset with structured state».
📜 Transcript
en · 1 761 слов · 24 сегментов · clean
Показать текст транскрипта
Five terminals. Five agents. One repo. Watch this. Agent 1 claims the auth feature. Agent 2 claims the dashboard. Agent 3 is already running tests. Agent 4 reviews a pull request. Agent 5 is compressing its context, preparing for the next task. None of them are waiting. None of them are blocking each other. This is session 12 of the Learn Claude Code curriculum, and in the next 10 minutes, you'll understand every mechanism behind it. Here's what most developers do when they want multiple agents. They open five terminals, they point all five at the same repo, and they wait. What happens next is predictable. Agent 2 overwrites the file Agent 1 just finished. Agent 3 runs the tests before Agent 4's changes are committed. Two agents claim the same task, and both silently assume they're the only one working on it. Agent 5 gets lost waiting for a response from an agent that already finished and exited. This is the four failure modes of naive multi-agent. File conflicts, race conditions, duplicate work, deadlocked communication, every single one of these failures is solvable, and sessions 9 through 12 each solve one. The Anthropic 2026 agentic coding trends report puts it plainly. Multi-agent systems replace single-agent workflows, but only when the coordination layer is deliberately designed. Superset One of the teams profiled in that report runs 10 or more agents simultaneously on isolated work trees with zero conflicts. The difference between their setup and five chaotic terminals isn't the model. It's the architecture. Session 9. The task is too big for one. Delegate to teammates. Here's the wrong model most developers start with. They think of sub-agents as temporary workers. You spawn one, it runs, it exits. Every invocation is disposable. No memory, no identity, no history. That works fine for a single isolated task. It breaks the moment agents need to coordinate over time. Session 9 introduces the correct model. Teammates. A teammate is a persistent agent with an identity, a mailbox, and a durable communication channel. Think of it like the difference between a contractor and a full-time employee. You call a contractor, they do the task, they leave. They don't remember last week. A full-time employee has a desk, an inbox, context about the project, and a relationship with the team. Teammates in session 9 work exactly like the employee. Each teammate has a name, a stable identifier like back-end agent or test runner. Each teammate has a mailbox, a durable queue of messages it processes in order. The lead agent doesn't run subtasks directly, it sends a message to the right mailbox. The teammate reads it, acts on it, and replies. Two immediate wins. First, The lead agent's context stays clean. It doesn't absorb the subtask execution details. Second, teammates survive context resets. If the lead agent compacts, teammates don't lose their state. This pattern is validated by Anthropic's own three-agent harness. Planner, generator, evaluator. Each is a persistent specialist. None of them share a context window. Session 10. Teammates need shared communication rules. One request-response pattern drives all negotiation. Here's the failure mode this solves. You have two teammates that send messages back and forth. Agent A sends done with the database schema. Agent B replies, but which version? I see three files. Agent A replies, the latest one. Agent B times out waiting. It never knew what latest meant. Without a protocol, agents talk past each other. Session 10 introduces the request response protocol. Every message is a structured object with four fields. An ID, a unique identifier, so both agents know which message a reply belongs to. A type, either request or response. A payload, the actual content. And a correlation ID on responses, the ID of the request being answered. That's it. One schema, used universally. Sounds simple. The effect is transformational. Watch what changes. Agent A sends a request, ID 007, type request, payload, validate database schema in migration slash v3. Agent B receives it, validates the file, and replies. Type response, correlation ID 007, payload, 12 tables, no conflicts. Agent A matches the correlation ID. It knows exactly which request was answered, even if 20 other messages have arrived in between. This pattern, request response with correlation IDs, is the same foundation used by HTTP, gRPC, and event-driven messaging systems. The Learn Claude Code curriculum makes the point explicit. Quote, one request-response pattern driving all negotiation. When you have this protocol, you can layer any behavior on top of it because every message is traceable. We now have persistent teammates. We have a protocol, they all speak. But here's the problem nobody mentions. The lead agent is still a bottleneck. Every task still has to flow through one brain. Assign this, assign that. Wait for each response, scale that to 12 agents, and you've built the world's most expensive JIRA board. What if the agents just claim their own work? Session 11. Teammates scan the board and claim tasks themselves. No assignment needed. The architecture has four states. Idle, scan, claim, resume. An idle agent has no current task. Every few seconds it scans a shared task board, a JSON file listing all outstanding tasks with their status. If it finds a task marked available and its skills match, it attempts to claim it. The claim is an atomic write, the agent sets the task status to claimed and stamps its own name on it. If two agents attempt to claim the same task simultaneously, only one write wins. The other reads back the file, sees the task is already taken, and scans for the next available one. No deadlock, no duplicates, no coordinator needed. After claiming, the agent enters the resume state, it picks up exactly where the task left off, using the task's stored context. When it finishes, It marks the task done and returns to idle. Idle. Scan. Claim. Resume. The curriculum puts it directly, quote, no need for the lead to assign each one. What this means in practice, the lead agent is now a task writer, not a task assigner. It breaks work into chunks and writes them to the board. The team finds the work. This is how Fountain, a recruiting company, used hierarchical multi-agent orchestration to achieve two times candidate conversions. Their orchestrator writes job requirements to a shared board. Specialist agents claim individual candidate assessments. No bottleneck. Parallel execution. According to the Anthropic 2026 agentic coding trends report. Session 12. Each agent works in its own directory. Zero interference. Agents claiming tasks from a shared board still have one problem left. If five agents all write to the same repo, they hit Git lock contention. File overwrites. Stale reads. VS Code's WorkTree support, shipped in July 2025, made the solution accessible, and the JetBrains 2026.1 release made it first class across the IDE ecosystem. The pattern, every task gets its own Git WorkTree. A WorkTree is a separate working directory pointing at its own branch, but sharing the same .git object store. Agent 1 checks out branch feature slash auth into slash WorkTree slash auth. Agent 2 gets branch feature slash dashboard into slash worktree slash dashboard, they share the repo history. They do not share the working directory. The curriculum's key insight, tasks manage goals, worktrees manage directories, bound by ID. When an agent claims task 007, it creates or resumes worktree 007. The task ID and worktree path share the same identifier. The agent always knows where it is. When the task is done, the work tree is merged and cleaned up. Conflicts move to merge time, where standard Git tooling detects them, instead of happening silently during active work. The practical limit. In testing, five to seven concurrent agents is the productive ceiling on a modern laptop. Beyond that, rate limits, disk consumption. Each work tree copies the working tree, roughly five gigabytes per work tree on a large code base, and merge review overhead cancel out the throughput gains. But five agents working in parallel on a solid code base? That's the sweet spot. Now, the capstone. Python agent slash s underscore full dot pi. This is the full agent, all 12 mechanisms, in one file, under 300 lines of Python. Session 1 through 2, the agent loop with bash tools. Session 3 through 6, to-do write, sub-agents, skills, context compaction. Session 7 through 8, on-disk task graphs, background operations. Session 9 through 12, Agent Teams, Communication Protocol, Autonomous Claiming, Work Tree Isolation. Every mechanism we've built across this series combined. When you run s underscore full, you get an agent that can plan, persist through crashes, work alongside teammates, claim tasks without being told, and execute in its own isolated workspace. You don't need Claude Code to build this. You don't need Langchain. You don't need Crew AI. You need Bash, an API key, and the 12 mechanisms. That's all. Before you spin up 10 agents, three things. First, parallel agents compound costs. Five agents each using 200,000 tokens per run will hit your API rate limits in minutes. Budget before you scale. Second, merge review doesn't disappear. Work tree isolation prevents write conflicts during execution. It does not prevent merge conflicts at integration. Five agents each modifying shared utilities means five divergent branches. Review overhead is real. Third, context resets between sessions means your teammates start fresh. Persistent identity doesn't mean persistent knowledge. Build handoff artifacts into every task, a structured summary of what was done and what's outstanding, or the next agent picks up confused. The curriculum calls this structured handoff artifacts. Anthropic calls it context reset with structured state. Both are the same pattern. Know the limits. Work within them. The agents are powerful. The constraints are still yours to manage. Here's your move. Fork the LearnClawed code repo on GitHub. Link in the description. Go to agent slash s12 underscore worktree task isolation dot pi. Run it. Watch the cycle. Idle, scan, claim, resume in real time. Then go to agent slash s underscore full dot pi. Run that too. That's the complete agent. All 12 mechanisms. Your brain on Tuesday knows things it didn't know on Monday. This is the last episode of the Harness Engineering series, from loop to teams. From 50 lines to a complete agent. If you want to see me build this into a real production system, ship features, manage PRs, integrate with CI, subscribe. That's the next series. The agents are ready. The question is whether you are. I'm TechWhistle. Stop assigning tasks. Let your agents claim them.
⚙️ Pipeline jobs
| Stage | Status | Att. | Updated | Error |
|---|---|---|---|---|
| download | done | 1/3 | 2026-07-20 12:02:15 | |
| transcribe | done | 1/3 | 2026-07-20 12:02:23 | |
| summarize | done | 1/3 | 2026-07-20 12:02:42 | |
| embed | done | 1/3 | 2026-07-20 12:02:44 |
📄 Описание YouTube
Показать
One agent is powerful. Five agents shipping code in parallel — with zero git conflicts, no manager, and no duplicated work — is transformational. But only when the coordination layer is deliberately designed. Here's the complete architecture. This is the series finale of the Harness Engineering course (Sessions 9-12 + Capstone) from the open-source **learn-claude-code** curriculum. We cover every failure mode of naive multi-agent — file conflicts, race conditions, duplicate claiming, deadlocked comms — then solve each one in sequence. Session 9: **Agent Teams** — persistent identity and async mailboxes (think contractors vs full-time employees). Session 10: **Communication Protocols** — one request-response schema with correlation IDs, the same pattern used by HTTP and gRPC. Session 11: **Autonomous Task Claiming** — agents scan a shared board and self-assign using an atomic write (Idle → Scan → Claim → Resume). Session 12: **Worktree Isolation** — one task, one branch, one directory; task ID equals worktree ID. Then the capstone: all twelve mechanisms combined in `s_full.py` — under 280 lines of Python, no frameworks. We close with three honest limits you need to know before you scale. ### Chapters 0:00 The Five-Agent Demo (Cold Open) 0:28 Why Naive Multi-Agent Collapses 1:40 Session 9: Agent Teams 3:15 Session 10: Communication Protocols 4:59 The Autonomous Claiming Reveal 5:23 Session 11: Autonomous Task Claiming 7:00 Session 12: Worktree Isolation 8:45 The Capstone — All 12 Mechanisms 9:39 The Real Limits (Don't Ignore These) 10:41 Your Move ### Tools & Resources Mentioned - learn-claude-code (full 12-session curriculum): https://github.com/shareAI-lab/learn-claude-code - Capstone file (s_full.py): https://github.com/shareAI-lab/learn-claude-code/blob/main/agents/s_full.py - Anthropic harness design paper (April 2026): https://www.anthropic.com/engineering/harness-design-long-running-apps - Anthropic 2026 Agentic Coding Trends Report: https://resources.anthropic.com/hubfs/2026%20Agentic%20Coding%20Trends%20Report.pdf - Previous episode — Persistent Agents (Sessions 7-8) - Full series playlist — Harness Engineering (Sessions 1-12) ### Join the Community Subscribe to TechWhistle for the next series — taking the learn-claude-code capstone into a real production system: shipping features, managing PRs, and integrating with CI. The agents are ready. The question is whether you are. #MultiAgent #AgentOrchestration #ClaudeCode #HarnessEngineering #AIAgents #GitWorktree #Anthropic #TechWhistle