Зачем это нужно
В предыдущих уроках мы разобрали три важных ограничения multi-agent development:
- несколько агентов полезны только для независимых проверяемых ветвей;
- роли должны отличаться по context, permissions и output contract;
- reviewer должен быть независимым от implementer context.
Теперь нужно собрать это в управляемый workflow.
Наивная multi-agent схема выглядит так:
Запустим трех агентов одновременно.
Пусть каждый что-нибудь сделает.
Потом как-нибудь объединим.
Такой подход быстро ломается. Один агент меняет API, другой пишет UI под старый contract, третий пишет tests под собственные assumptions, reviewer получает огромный diff без evidence, а человек в конце пытается понять, где именно система сошла с рельсов.
Orchestration нужна, чтобы заменить "параллельный хаос" на проверяемый процесс:
Task
-> Plan
-> Task DAG
-> Role assignment
-> Parallel work
-> Handoffs
-> Integration
-> Independent review
-> CI
-> Human decision
Главная мысль урока:
Orchestration - это не магический runtime.
Orchestration - это порядок выполнения, артефакты передачи, gates и правила остановки.
Основная идея
Orchestration отвечает на вопрос:
Кто, в каком порядке, с какими inputs, с какими permissions,
до какого observable result и через какой gate выполняет работу?
Это не то же самое, что "один главный агент всем командует". В хорошей orchestration есть:
- входная specification;
- декомпозиция в task DAG;
- роли;
- assignment каждой роли;
- границы context;
- границы tools;
- handoff artifacts;
- verification evidence;
- integration stage;
- independent review;
- CI gate;
- human approval для risky decisions.
Плохой orchestration:
Manager Agent:
Сделай feature. Позови других агентов, если надо.
Хороший orchestration:
Planner:
Build task DAG and task briefs.
Backend Agent:
Implement API branch from Backend Task Brief only.
Output diff + tests + notes.
Frontend Agent:
Implement UI branch from Frontend Task Brief and API contract.
Output diff + UI checks + notes.
Test Agent:
Add acceptance/e2e tests from spec.
Output test diff + expected verification commands.
Integrator:
Merge branches in controlled order.
Resolve conflicts explicitly.
Run full verification.
Reviewer:
Review final integrated diff from fresh context.
CI:
Run deterministic checks.
Human:
Approve product, security, deploy or scope decisions.
Ключевые термины
| Термин | Значение |
|---|---|
| Orchestration | Управление порядком выполнения agent workflow: stages, roles, handoffs, gates и stop conditions. |
| Coordinator | Роль или процесс, который выбирает next step, назначает agents и собирает evidence. |
| Manager-style orchestration | Схема, где central coordinator маршрутизирует задачи между ролями и принимает routing decisions. |
| Task DAG | Directed acyclic graph задач и зависимостей. Показывает, что можно делать параллельно, а что только после dependency. |
| Stage | Состояние workflow: planning, implementation, verification, review, integration, CI, done. |
| Handoff | Передача проверяемого artifact между stages или agents. |
| Gate | Контрольная точка, без прохождения которой workflow не идет дальше. |
| Human approval point | Gate, где решение должен принять человек: scope, risk, permission, deploy, destructive action. |
| Integration point | Этап, где результаты отдельных branches собираются в единый diff и проверяются вместе. |
| State machine | Явная модель допустимых transitions между состояниями workflow. |
| Evidence | Проверяемое подтверждение результата: diff, tests, logs, screenshots, eval reports, CI status. |
| Routing decision | Решение coordinator: продолжить, вернуть на доработку, разделить задачу, заблокировать, запросить approval. |
Orchestration, Coordination и Implementation
Эти слова часто смешивают, но в engineering workflow они означают разные вещи.
| Слой | Главный вопрос | Типичный output |
|---|---|---|
| Orchestration | Как устроен весь process от task до merge? | State machine, gates, role flow, handoff contracts. |
| Coordination | Что делать следующим шагом прямо сейчас? | Assignment, routing decision, status update. |
| Implementation | Как изменить код или документы? | Diff, tests, migration, docs update. |
Orchestration задает правила игры.
Coordination применяет эти правила к конкретной задаче.
Implementation выполняет конкретные изменения.
Пример:
Orchestration rule:
No branch enters integration without local verification evidence.
Coordination decision:
Frontend Agent has no screenshot evidence, return to verification.
Implementation action:
Frontend Agent fixes layout and reruns UI check.
Это разделение важно. Если orchestration растворяется внутри implementation, процесс становится непрозрачным. Агент может сказать "все готово", но непонятно:
- кто проверил acceptance criteria;
- какие branches были независимыми;
- были ли conflicts;
- что именно вошло в final diff;
- запускался ли CI;
- почему reviewer approved.
Базовый Multi-Agent Pipeline
Типовой pipeline:
Эта схема не требует сложного фреймворка. Ее можно выполнить вручную:
- отдельными агентными сессиями;
- отдельными Git branches;
- отдельными worktrees;
- отдельными prompt templates;
- отдельными review packets.
Framework может помочь автоматизировать routing, но не заменяет саму дисциплину.
Почему Task DAG Важнее Списка Задач
Список задач показывает порядок чтения. DAG показывает зависимости.
Плохая декомпозиция:
1. Сделать backend.
2. Сделать frontend.
3. Сделать tests.
4. Проверить.
Проблема: непонятно, можно ли выполнять пункты параллельно.
Хорошая декомпозиция:
Spec Clarification
↓
API Contract
├── Backend Implementation
├── Frontend Implementation
└── Acceptance Tests
↓
Integration
↓
Review
↓
CI / Merge
DAG отвечает на вопросы:
- какая задача должна быть выполнена первой;
- какие ветви можно делать параллельно;
- какой artifact нужен следующей ветви;
- где находится integration point;
- какие checks должны пройти до review;
- что блокирует merge.
Правило:
Parallel agents should start from stable contracts, not from vague shared intentions.
Если contract еще не стабилен, parallel work преждевременен.
Manager-Style Orchestration
Manager-style orchestration - это схема, где coordinator принимает routing decisions:
What is ready?
What is blocked?
Who should work next?
What evidence is missing?
Can this branch enter integration?
Does this require human approval?
Важно: manager не должен быть "агентом, который делает все сам".
Роль manager/coordinator:
- держать state workflow;
- раздавать task briefs;
- проверять наличие artifacts;
- направлять failed branches обратно;
- не смешивать contexts без необходимости;
- не давать write permissions reviewer'у без явной причины;
- не пропускать gates ради скорости;
- собирать final report.
Что manager не должен делать:
- молча менять acceptance criteria;
- объединять branches без explicit evidence;
- скрывать failed checks;
- выдавать self-review за independent review;
- запускать risky tools без approval;
- делать все edits вместо implementers;
- считать "agent said done" эквивалентом verification.
В небольшом проекте manager может быть человеком. В учебном workflow manager часто является основной Codex-сессией, которая вызывает отдельные roles последовательно. В более сложном workflow это может быть orchestration framework.
Но принцип остается тем же:
Manager controls flow.
Agents produce artifacts.
Gates decide whether artifacts can move forward.
Manager Pattern И Decentralized Handoff
В multi-agent системах часто встречаются два базовых orchestration pattern.
| Pattern | Как работает | Когда полезен | Главный риск |
|---|---|---|---|
| Manager pattern | Центральный coordinator вызывает специализированных agents как tools и собирает результат. | Нужен один владелец flow, единый user experience, controlled synthesis. | Manager становится bottleneck или скрывает ошибки subagents. |
| Decentralized handoff | Agent передает управление другому agent, который продолжает workflow. | Conversation triage, domain handoff, support-style routing. | Потеря общего контекста, циклы handoff, неясный owner. |
В software development чаще безопаснее начинать с manager pattern:
Coordinator -> Task Brief -> Specialized Agent -> Handoff Artifact -> Coordinator
Почему:
- легче сохранить общий task state;
- проще логировать evidence;
- понятнее, кто принимает routing decisions;
- reviewer видит unified final packet;
- human approval points проще разместить между stages.
Decentralized handoff может быть уместен, если домены действительно независимы:
Triage Agent -> Security Review Agent
Triage Agent -> Documentation Agent
Triage Agent -> Release Agent
Но для coding workflow у decentralized handoff должны быть дополнительные ограничения:
- максимальная глубина handoff;
- запрет циклов без human approval;
- обязательный handoff artifact;
- общий run_id;
- лог текущего owner;
- explicit return condition.
Иначе агенты начинают "передавать ответственность", а не работу.
State Machine Workflow
Orchestration проще контролировать, если представить workflow как state machine.
Минимальные состояния:
| State | Что означает | Кто переводит дальше |
|---|---|---|
| New | Есть запрос, но нет validated scope. | Planner или human. |
| Planned | Есть task DAG и acceptance criteria. | Coordinator. |
| Assigned | Ветви назначены ролям. | Coordinator. |
| InProgress | Агент выполняет ограниченную task. | Assigned agent. |
| ReadyForVerification | Есть diff или artifact, но evidence еще не подтвержден. | Implementer. |
| Verified | Есть local verification evidence. | Verifier или implementer with evidence. |
| ReadyForIntegration | Branch можно объединять. | Coordinator. |
| Integrated | Branches собраны в единый diff. | Integrator. |
| Review | Fresh reviewer проверяет integrated diff. | Reviewer. |
| ChangesRequested | Reviewer нашел blocking findings. | Coordinator. |
| Approved | Review passed. | Reviewer. |
| CI | Запущены deterministic checks. | CI system. |
| Done | Change принят, merged или готов к merge. | Human или merge policy. |
| Blocked | Нужен input, approval или external change. | Coordinator. |
State machine нужна не для красоты. Она помогает не терять контроль:
- нельзя попасть в
Integrated, если нетVerified; - нельзя попасть в
Approved, если review не был independent; - нельзя попасть в
Done, если CI failed; - нельзя бесконечно чинить без фиксации новых findings;
- нельзя скрыть
Blockedза фразой "почти готово".
Handoff Artifacts
Handoff - это не сообщение "я закончил". Handoff - это проверяемый пакет, который следующий stage может использовать без чтения всего предыдущего transcript.
Пример handoff chain:
Planner
-> Task DAG + Task Briefs
Backend Agent
-> Backend diff + test evidence + API notes
Frontend Agent
-> Frontend diff + UI evidence + API assumptions
Test Agent
-> Test diff + expected failing/passing behavior
Integrator
-> Integrated diff + conflict resolution notes
Verifier
-> Full verification report
Reviewer
-> Findings or approval
CI
-> Check status
Хороший handoff должен быть:
- compact;
- artifact-based;
- verifiable;
- scoped;
- explicit about failures;
- explicit about assumptions;
- independent of hidden reasoning.
Плохой handoff:
Готово, я все поправил. Тесты вроде проходят.
Хороший handoff:
Task: Add password reset request API.
Changed files:
- app/api/auth/reset/request/route.ts
- lib/auth/password-reset-token.ts
- tests/auth/password-reset-request.test.ts
Acceptance criteria covered:
- email is accepted even if account does not exist;
- reset token is stored hashed;
- rate limit error returns 429;
- no account enumeration in response.
Verification:
- npm test -- tests/auth/password-reset-request.test.ts
- npm run lint
Not run:
- full e2e, because UI branch is separate.
Known risks:
- token cleanup job not implemented in this task.
Handoff Contract Table
| From | To | Artifact | Required fields |
|---|---|---|---|
| Human | Planner | Feature request | Goal, constraints, acceptance criteria, out of scope. |
| Planner | Coordinator | Task DAG | Nodes, dependencies, contracts, parallel branches, gates. |
| Coordinator | Implementer | Task brief | Scope, allowed files, contract, tests, stop conditions. |
| Implementer | Verifier | Implementation packet | Diff, changed files, commands run, known limitations. |
| Verifier | Coordinator | Verification report | Pass/fail, command outputs summary, missing checks. |
| Coordinator | Integrator | Ready branches | Branch names, evidence, merge order, conflicts expected. |
| Integrator | Reviewer | Review packet | Final diff, spec, relevant code, evidence, risk notes. |
| Reviewer | Coordinator | Review findings | Severity, location, evidence, recommended action. |
| CI | Human/Coordinator | CI result | Checks, status, logs link or summary, deploy readiness. |
Каждый artifact должен отвечать на два вопроса:
Can the next role act without guessing?
Can a reviewer verify the claim from evidence?
Если ответ "нет", handoff слабый.
Gates
Gate - это checkpoint, где workflow может остановиться.
Без gates multi-agent workflow превращается в pipeline, который продолжает двигаться даже с плохими inputs.
Основные gates:
| Gate | Когда | Что проверяет |
|---|---|---|
| Spec Gate | До planning | Goal, acceptance criteria, scope boundaries. |
| Plan Gate | После Planner | DAG реалистичен, dependencies ясны, tasks small enough. |
| Contract Gate | До parallel work | Shared interfaces стабильны: API, schema, event, file format. |
| Verification Gate | После ветви | Есть tests/evidence для branch result. |
| Integration Gate | Перед объединением | Branches готовы, merge order понятен, conflicts ожидаемы. |
| Review Gate | После integration | Fresh reviewer проверил final diff. |
| CI Gate | Перед merge/deploy | Deterministic checks passed. |
| Human Approval Gate | В risky points | Человек подтвердил scope, risk, permissions или release. |
Gates должны быть explicit. Не "мы потом проверим", а:
Branch cannot enter integration unless:
- changed files are listed;
- targeted tests passed or are explicitly not applicable;
- known failures are documented;
- no unrelated changes are included.
Human Approval Points
Human approval нужен не в каждой мелочи. Если человек утверждает каждый import, orchestration становится медленной и бессмысленной.
Но есть решения, которые агент не должен принимать автоматически.
Типовые human approval points:
| Ситуация | Почему нужен человек |
|---|---|
| Scope expansion | Агент хочет сделать больше, чем было согласовано. |
| Product behavior ambiguity | Нужно выбрать UX, policy или business rule. |
| Security-sensitive change | Auth, permissions, tokens, secrets, personal data. |
| Database migration | Риск data loss, rollback, compatibility. |
| Dependency upgrade | Supply chain, breaking changes, license, footprint. |
| Destructive command | Удаление файлов, reset, force push, cleanup. |
| Production deploy | Влияет на пользователей. |
| Failed check override | Нужно решить, можно ли принять residual risk. |
Human approval prompt должен быть конкретным:
Approval needed: database migration changes `users.reset_token_hash`.
Decision required:
- accept migration as written;
- ask for backward-compatible migration;
- reject this scope for current task.
Evidence:
- migration file: ...
- rollback plan: ...
- tests run: ...
- known risk: existing users without column default.
Плохой approval prompt:
Можно продолжить?
Он не объясняет, что именно человек разрешает.
Permissions By Stage
Хорошая orchestration ограничивает tools не только по agent role, но и по stage.
| Stage | Разрешено | Запрещено без approval |
|---|---|---|
| Planning | Read files, inspect docs, build DAG. | Write production code, change tests, install deps. |
| Assignment | Create task briefs, choose branches/worktrees. | Merge code, edit unrelated files. |
| Implementation | Edit scoped files, run targeted tests. | Change spec, broaden scope, destructive Git. |
| Verification | Run tests/evals, inspect output. | Rewrite implementation to make tests pass unless role allows it. |
| Integration | Merge branches, resolve conflicts, run full checks. | Silently drop changes, rewrite feature behavior. |
| Review | Read diff, inspect code, run read-only checks. | Implement fixes by default, approve without evidence. |
| CI | Run deterministic checks. | Change code. |
| Release | Merge/deploy after gates. | Override failed gates without explicit human decision. |
Permissions are part of orchestration because agents are powerful. A role without boundaries is not a role, it is just another general-purpose assistant.
Context Packaging
У каждого stage должен быть свой context packet.
Planner получает широкий context:
- user request;
- product goal;
- architecture overview;
- relevant docs;
- previous constraints;
- acceptance criteria;
- repo map.
Implementer получает узкий context:
- task brief;
- relevant files;
- interface contract;
- allowed scope;
- tests to run;
- output format.
Verifier получает:
- task brief;
- changed files;
- test commands;
- expected behavior;
- known limitations.
Reviewer получает:
- spec;
- acceptance criteria;
- final diff;
- relevant code;
- verification evidence;
- risk notes.
Integrator получает:
- branch list;
- merge order;
- contracts;
- verification evidence;
- conflict notes;
- rollback strategy.
Принцип:
Give each role enough context to do its job,
but not so much that it inherits every assumption from previous roles.
Integration Is A Separate Stage
Одна из частых ошибок multi-agent workflow - считать, что если все ветви отдельно готовы, то feature готова.
Это не так.
Branch-level success:
Backend tests pass.
Frontend build passes.
E2E tests are written.
Feature-level success:
Backend, frontend and tests agree on one behavior.
The integrated system passes the acceptance criteria.
Integration stage отвечает за:
- merge order;
- conflict resolution;
- contract mismatches;
- duplicate changes;
- shared dependency updates;
- schema/API compatibility;
- combined test run;
- final diff shape;
- rollback notes.
Integration не должен быть "автоматическим склеиванием". Это отдельная инженерная работа.
Пример mismatch:
Backend Agent:
POST /api/auth/reset returns { ok: true }
Frontend Agent:
expects { success: true }
Test Agent:
checks status 202 and no JSON body
Все три ветви могли быть "готовы" по отдельности. Вместе они не реализуют один contract.
Поэтому перед parallel implementation нужен Contract Gate, а после parallel implementation нужен Integration Gate.
Reviewer Проверяет Integrated Diff
Independent reviewer должен проверять final integrated diff, а не только отдельные ветви.
Почему?
Потому что баги часто появляются на стыках:
- API response differs from UI expectation;
- tests cover old behavior;
- integration dropped one branch's change;
- duplicate helper functions diverged;
- migration order broke runtime;
- feature works locally but not in combined build;
- docs describe behavior that code does not implement.
Reviewer packet для orchestration должен включать:
Original specification
Acceptance criteria
Task DAG
Integrated diff
Changed files
Verification evidence
Conflict resolution notes
Known risks
Out-of-scope items
Reviewer не должен получать только summaries от agents. Summaries полезны, но source of truth - final diff and evidence.
CI Как Deterministic Gate
CI не заменяет reviewer. Reviewer не заменяет CI.
Они проверяют разные вещи.
| Проверка | Лучше делает |
|---|---|
| Syntax, lint, typecheck, unit tests | CI |
| Regression test suite | CI |
| Deterministic build | CI |
| Spec mismatch | Reviewer |
| Scope creep | Reviewer |
| Architecture boundary violation | Reviewer |
| Missing edge case | Reviewer + tests |
| Risk acceptance | Human |
CI должен быть последним автоматическим gate перед merge или deploy.
Но CI не должен быть единственным gate:
Green CI can still mean wrong feature.
Например:
- tests проверяют не тот behavior;
- acceptance criteria неполные;
- UI выглядит сломанным, но build green;
- security decision неверна, но unit tests pass;
- agent удалил важный edge case вместе с flaky test.
CI подтверждает, что deterministic checks прошли. Он не доказывает, что продуктовая задача решена правильно.
Orchestration В Git И Worktrees
Multi-agent workflow должен учитывать Git с самого начала.
Практичная схема:
main
├── feature/password-reset-api
├── feature/password-reset-ui
├── feature/password-reset-tests
└── feature/password-reset-integration
Каждая ветвь может жить в отдельном worktree:
repo/
repo-api/
repo-ui/
repo-tests/
repo-integration/
Зачем это нужно:
- агенты не пишут в одну рабочую директорию;
- проще увидеть diff каждой ветви;
- проще откатить одну ветвь;
- меньше accidental overwrite;
- integration становится явным stage;
- reviewer видит final integrated change.
Но worktrees не решают orchestration сами по себе. Они только дают изоляцию. Все равно нужны:
- task briefs;
- branch contracts;
- verification evidence;
- merge order;
- conflict policy;
- final review.
Пример: Password Reset Feature
Допустим, capstone feature:
Пользователь может запросить password reset link,
получить email, перейти по ссылке и задать новый пароль.
Acceptance criteria:
- request endpoint не раскрывает, существует ли email;
- reset token хранится в hashed form;
- token expires after configured time;
- пользователь может задать новый пароль по valid token;
- invalid или expired token отклоняется;
- UI показывает понятные states;
- tests покрывают happy path и основные failure cases.
Task DAG
Branch Assignments
| Branch | Agent | Scope |
|---|---|---|
feature/reset-contract |
Planner / Architect | API shape, data model, acceptance criteria. |
feature/reset-api |
Backend Agent | Endpoints, token hashing, expiry, backend tests. |
feature/reset-ui |
Frontend Agent | Request form, reset form, loading/error/success states. |
feature/reset-tests |
Test Agent | Acceptance/e2e tests from spec. |
feature/reset-integration |
Integrator | Merge branches, resolve contract mismatches, run full checks. |
Contract Artifact
Before parallel work:
Password Reset Contract
Endpoints:
- POST /api/auth/password-reset/request
- POST /api/auth/password-reset/confirm
Security:
- request response must not reveal account existence;
- token stored hashed;
- token has expiry;
- token is single-use.
UI states:
- request idle/loading/sent/error;
- confirm idle/loading/success/invalid/expired.
Test expectations:
- no enumeration;
- valid reset succeeds;
- reused token fails;
- expired token fails.
This contract is the shared input for Backend, Frontend and Test agents.
Backend Agent Brief
Role:
Backend Implementer
Goal:
Implement password reset request and confirm endpoints.
Inputs:
- Password Reset Contract
- Relevant auth files
- Existing database/auth patterns
Allowed:
- edit backend auth files;
- add backend tests;
- run targeted backend tests.
Forbidden:
- change frontend UI;
- change product acceptance criteria;
- add email provider dependency without approval;
- perform destructive migration without approval.
Output:
- changed files;
- diff summary;
- backend test evidence;
- unresolved assumptions.
Frontend Agent Brief
Role:
Frontend Implementer
Goal:
Implement password reset request and confirm UI using the approved contract.
Inputs:
- Password Reset Contract
- Existing auth UI patterns
- Relevant route/component files
Allowed:
- edit scoped UI files;
- add component tests if project has them;
- run frontend build or targeted UI checks.
Forbidden:
- invent different API response shape;
- change backend routes;
- change design system conventions.
Output:
- changed files;
- UI state coverage;
- screenshot or browser evidence when practical;
- known limitations.
Test Agent Brief
Role:
Test Implementer
Goal:
Add acceptance tests for password reset behavior from the contract.
Inputs:
- Password Reset Contract
- Existing test patterns
- Relevant auth fixtures
Allowed:
- add tests/evals;
- run targeted test suite.
Forbidden:
- modify implementation just to make tests pass;
- weaken acceptance criteria;
- skip negative cases without noting risk.
Output:
- test files changed;
- scenarios covered;
- commands run;
- expected failures if implementation is not ready.
Integration Brief
Role:
Integrator
Goal:
Combine backend, frontend and test branches into one coherent feature diff.
Inputs:
- Backend packet
- Frontend packet
- Test packet
- Password Reset Contract
Allowed:
- merge branches;
- resolve conflicts;
- make narrow compatibility fixes;
- run full verification.
Forbidden:
- silently drop branch changes;
- change contract without approval;
- hide failing checks;
- turn off tests to make CI pass.
Output:
- final changed files;
- conflict resolution notes;
- full verification evidence;
- risks and follow-ups.
Example Orchestration Run
The coordinator's runbook can look like this:
1. Read feature request and existing auth docs.
2. Ask for clarification only if acceptance criteria are ambiguous.
3. Produce Password Reset Contract.
4. Build task DAG.
5. Get human approval for contract if security/product behavior is ambiguous.
6. Assign backend, frontend and test branches.
7. Require each branch to return a packet with diff + evidence.
8. Reject branch handoff if evidence is missing.
9. Integrate branches in a dedicated integration worktree.
10. Run full test/build/lint/eval checks.
11. Prepare review packet from final integrated diff.
12. Send packet to fresh reviewer.
13. Route blocking findings back to the relevant stage.
14. After approval, let CI run as deterministic gate.
15. Ask human approval for merge/deploy if required by project policy.
Notice the shape:
The coordinator does not need to know every internal thought of every agent.
The coordinator needs artifacts, state and gates.
Orchestration Для AI Agent Development Задачи
Теперь пример ближе к самому курсу.
Task:
Добавить в coding-agent workflow правило:
перед изменением production code агент должен сформулировать acceptance criteria
и предложить verification commands.
Possible DAG:
Роли:
- Planner определяет, где живет правило: guide, prompt, checklist, template;
- Docs Agent обновляет объяснение для студентов;
- Prompt Agent обновляет reusable prompt или agent rule;
- Test Agent добавляет checklist/eval, который ловит отсутствие acceptance criteria;
- Integrator проверяет, что docs и prompt не расходятся;
- Reviewer проверяет, что правило не стало слишком широким или невыполнимым;
- CI запускает markdown lint, tests или eval suite.
Здесь важно не перепутать:
Policy correctness is not the same as Markdown validity.
CI может сказать, что Markdown валиден. Reviewer должен сказать, что правило действительно помогает управлять агентом и не создает ложную безопасность.
Conceptual Framework Comparison
В экосистеме AI agents есть разные инструменты, которые помогают описывать teams, handoffs, graphs и workflows. В этом уроке они важны как источник терминов, а не как обязательный выбор.
| Подход | Как думать о нем в курсе |
|---|---|
| Manager-style flow | Coordinator принимает routing decisions и передает task специализированным ролям. |
| Graph-based flow | Workflow описывается как nodes, edges, states и transitions. |
| Crew/team abstraction | Несколько roles работают над общей задачей через заданный process. |
| Custom scripts | Простые локальные scripts фиксируют checks, packet generation и status updates. |
| Manual orchestration | Человек или ведущий агент выполняет state machine руками по шаблону. |
Для курса важнее не название framework, а вопросы:
- где хранится state;
- как описаны transitions;
- какие artifacts передаются;
- какие tools доступны каждой роли;
- где стоят gates;
- что делает человек;
- как восстановиться после failure.
На ранних этапах manual orchestration часто выигрывает. Она прозрачна, легко объясняется студентам и хорошо показывает, где именно процесс нуждается в автоматизации.
Failure Handling
Хорошая orchestration заранее описывает, что делать, когда что-то идет не так.
Agent Blocked
Симптом:
Implementer не может продолжить без решения по contract.
Правильный route:
InProgress -> Blocked -> Human/Planner -> Planned -> Assigned
Неправильно:
Агент сам выбирает product behavior и продолжает.
Verification Failed
Симптом:
Targeted tests failed.
Правильный route:
ReadyForVerification -> Failed -> InProgress
Handoff должен включать:
- failing command;
- короткий summary failure;
- suspected cause;
- files likely involved;
- whether failure is new or existing.
Reviewer Found Blocking Issue
Симптом:
Reviewer нашел mismatch между spec и final diff.
Правильный route:
Review -> ChangesRequested -> Planned or Assigned
Coordinator должен решить:
- это локальный fix;
- это contract issue;
- это missing test;
- это scope ambiguity;
- это human decision.
Merge Conflict
Симптом:
Branches edit the same file or contract changed.
Правильный route:
ReadyForIntegration -> Integrated with conflict notes -> Verification
Integrator должен зафиксировать:
- какие файлы конфликтовали;
- какой вариант выбран;
- почему это соответствует contract;
- какие checks подтверждают результат.
Scope Expansion
Симптом:
Agent решил заодно переписать auth layer.
Правильный route:
InProgress -> Blocked -> Human Approval or Split Task
Scope expansion не должен автоматически попадать в implementation. Его нужно либо отклонить, либо выделить в новую задачу.
CI Failed After Review
Симптом:
Reviewer approved, но CI failed.
Правильный route:
CI -> CIFailed -> Integration -> Verification -> Review if diff changed
Если fix меняет code behavior, нужен новый review. Если fix только formatting или generated lockfile refresh, review policy может быть легче, но это должно быть правилом проекта.
Orchestration Report
В конце workflow coordinator должен оставить короткий report.
Шаблон:
Orchestration Report
Task:
Final state:
Task DAG:
- node:
- dependencies:
- assigned role:
- status:
Branches / worktrees:
Handoff artifacts:
- planner packet:
- backend packet:
- frontend packet:
- test packet:
- integration packet:
- reviewer packet:
Verification:
- commands run:
- pass/fail:
- not run:
- reason:
Review:
- reviewer context:
- findings:
- status:
CI:
- checks:
- status:
Human approvals:
- decision:
- reason:
Residual risks:
Follow-up tasks:
Этот report важен для обучения. Он показывает не только результат, но и управляемость процесса.
Prompt Templates
Orchestration Plan Prompt
You are the Coordinator for this AI-assisted development task.
Goal:
<feature or change>
Inputs:
- specification:
- acceptance criteria:
- relevant docs:
- constraints:
Produce:
1. A task DAG with dependencies.
2. Candidate parallel branches.
3. Role assignments.
4. Required handoff artifacts for each role.
5. Verification commands per branch.
6. Integration plan.
7. Review packet contents.
8. Human approval points.
9. Stop conditions.
Do not implement code.
Agent Assignment Prompt
You are the <Role> for this branch.
Task:
<specific task>
Inputs:
- contract:
- relevant files:
- acceptance criteria:
Allowed actions:
- <allowed edits/tools>
Forbidden actions:
- <forbidden edits/tools>
Verification:
- <commands or checks>
Output:
- changed files;
- diff summary;
- tests/evidence;
- assumptions;
- blockers;
- recommended next handoff.
Stop if:
- contract is ambiguous;
- task requires out-of-scope edits;
- verification cannot be run;
- risky permission is needed.
Integration Prompt
You are the Integrator.
Inputs:
- approved contract;
- branch packets;
- verification evidence;
- merge order;
- known conflicts.
Goal:
Build one coherent integrated diff.
Check:
1. Branches implement the same contract.
2. No branch silently overwrites another.
3. Tests still match acceptance criteria.
4. Full verification commands are run or explicitly marked not run.
5. Conflict resolutions are documented.
Output:
- final changed files;
- conflict resolution notes;
- full verification evidence;
- risks;
- review packet draft.
Failure Triage Prompt
You are the Coordinator.
Current state:
<state>
Failure:
<command, review finding, conflict or blocker>
Artifacts:
- task brief:
- diff:
- evidence:
- logs summary:
Decide:
1. Is this implementation bug, contract bug, test bug, integration bug or scope issue?
2. Which stage should receive the task?
3. Is human approval required?
4. What is the smallest next action?
5. What evidence is required before returning to the main flow?
Do not hide failed checks.
Review Packet Prompt
Prepare a fresh-context review packet.
Include:
- original specification;
- acceptance criteria;
- task DAG summary;
- final integrated diff;
- changed files;
- verification evidence;
- not-run checks and reasons;
- conflict resolution notes;
- human approvals already received;
- known risks.
Exclude:
- long implementer transcript;
- hidden reasoning;
- unsupported claims;
- irrelevant files.
Типичные Ошибки
Ошибка 1. Orchestration Начинается С Implementation
Плохо:
Backend agent and frontend agent start coding before API contract exists.
Последствие:
- mismatch между API и UI;
- wasted work;
- интеграция превращается в redesign;
- tests пишутся под разные assumptions.
Лучше:
Spec Gate -> Contract Gate -> parallel implementation.
Ошибка 2. Все Агенты Работают В Одной Директории
Плохо:
Three agents edit one worktree.
Последствие:
- lost edits;
- unreadable diff;
- unclear ownership;
- difficult rollback.
Лучше:
Separate branches/worktrees + explicit integration.
Ошибка 3. Handoff Это Чат-Сводка
Плохо:
Agent: "Я сделал backend, все работает."
Последствие:
- невозможно проверить claim;
- reviewer вынужден угадывать;
- coordinator не знает missing evidence.
Лучше:
Diff + changed files + commands/results + risks.
Ошибка 4. Reviewer Проверяет До Integration
Review отдельной ветви полезен, но финальный gate должен смотреть integrated diff.
Плохо:
Backend approved.
Frontend approved.
Tests approved.
Merge without final review.
Лучше:
Branch checks -> Integration -> Full verification -> Independent review.
Ошибка 5. CI Запускается Только В Самом Конце
CI в конце нужен, но если feedback слишком поздний, integration становится дорогой.
Лучше:
- targeted checks на branch level;
- full checks after integration;
- CI before merge;
- failed checks documented immediately.
Ошибка 6. Coordinator Скрывает Неопределенность
Плохо:
There was some ambiguity, but I chose a reasonable default.
Иногда default нужен. Но если ambiguity касается product behavior, security или data, это human approval point.
Лучше:
Blocked: password reset response behavior affects account enumeration.
Need approval between options A/B.
Ошибка 7. Framework Используется Вместо Process
Плохо:
We use an orchestration framework, therefore our multi-agent workflow is controlled.
Framework может запускать nodes. Но он не гарантирует:
- хорошую decomposition;
- правильные gates;
- независимый review;
- корректную integration;
- достаточные tests;
- human approval в risky points.
Process сначала, framework потом.
Минимальный Orchestration Checklist
Перед запуском:
[ ] Есть specification.
[ ] Acceptance criteria проверяемые.
[ ] Out of scope явно указан.
[ ] Есть task DAG, а не просто list.
[ ] Dependencies понятны.
[ ] Parallel branches имеют stable contracts.
[ ] Каждой роли назначены inputs, permissions и outputs.
[ ] Handoff artifacts описаны.
[ ] Verification commands известны.
[ ] Human approval points отмечены.
На уровне каждой ветви:
[ ] Branch/task scope не расширен.
[ ] Changed files перечислены.
[ ] Tests/evals запущены или reason not run указан.
[ ] Known risks указаны.
[ ] No unrelated changes.
[ ] Handoff packet готов.
Перед integration:
[ ] Все required branches verified.
[ ] Merge order выбран.
[ ] Shared contract не изменился без approval.
[ ] Conflicts expected or checked.
[ ] Integration worktree/branch готов.
Перед review:
[ ] Final integrated diff собран.
[ ] Full verification run completed or documented.
[ ] Reviewer packet includes spec, AC, diff and evidence.
[ ] Reviewer starts from fresh context.
Перед merge:
[ ] Review approved or findings resolved.
[ ] CI passed.
[ ] Human approval received where required.
[ ] Residual risks documented.
[ ] Follow-ups separated from current task.
Практика
Возьмите одну feature из capstone-проекта и нарисуйте orchestration.
Минимальная задача:
Feature:
<название>
Acceptance criteria:
1.
2.
3.
Task DAG:
- node:
- depends on:
- can run in parallel:
Roles:
- Planner:
- Backend Agent:
- Frontend Agent:
- Test Agent:
- Integrator:
- Reviewer:
- Verifier:
Handoffs:
- Planner -> Coordinator:
- Implementer -> Verifier:
- Verifier -> Integrator:
- Integrator -> Reviewer:
- Reviewer -> Coordinator:
Gates:
- Spec Gate:
- Contract Gate:
- Verification Gate:
- Integration Gate:
- Review Gate:
- CI Gate:
- Human Approval Gate:
Failure handling:
- if branch tests fail:
- if reviewer finds issue:
- if CI fails:
- if scope expands:
Хороший результат практики - не идеальная схема на 20 ролей. Хороший результат - простая схема, где понятно:
- что можно делать параллельно;
- какие artifacts появляются;
- где workflow может остановиться;
- кто имеет право писать code;
- кто проверяет diff;
- где человек принимает risky decision.
Критерии Хорошей Orchestration
Хорошая orchestration обладает несколькими признаками:
- есть ясный source of truth;
- DAG показывает dependencies;
- roles имеют разные contracts;
- context не смешивается без необходимости;
- reviewer получает fresh packet;
- integration является отдельным stage;
- evidence собирается до approval;
- failed checks не скрываются;
- CI дополняет review, а не заменяет его;
- human approval стоит в risky points;
- final report объясняет, что произошло.
Можно сформулировать еще короче:
Every transition must be justified by an artifact.
Every risky action must have an owner.
Every final claim must have evidence.
Краткое резюме
Orchestration делает multi-agent development управляемым. Она описывает stages, roles, handoffs, gates, permissions и human approval points.
Главный artifact orchestration - не длинный чат между агентами, а проверяемый workflow:
Planner
-> Task DAG
-> parallel agents
-> branch evidence
-> Integration
-> full verification
-> independent review
-> CI
-> human merge/deploy decision
Multi-agent workflow не должен начинаться с параллельного coding. Он должен начинаться со stable contracts и task DAG. Параллельная работа полезна только там, где ветви независимы, outputs проверяемы, а integration запланирована как отдельная работа.
Самый важный принцип:
Do not optimize for many agents.
Optimize for controlled transitions between states.
Вопросы для самопроверки
- Чем orchestration отличается от coordination и implementation?
- Почему task DAG лучше обычного списка задач для multi-agent workflow?
- Какие artifacts должны попасть в handoff от implementer к verifier?
- Почему final reviewer должен смотреть integrated diff, а не только отдельные branches?
- В каких ситуациях human approval обязателен, даже если агент уверен в решении?
Что дальше
В следующем модуле мы перейдем к hooks, automation и guardrails. Orchestration описывает, где стоят gates. Hooks и guardrails помогают сделать часть этих gates автоматическими: форматирование после edit, tests перед commit, security checks перед deploy, ограничения permissions и explicit approval перед risky action.