Зачем это нужно
В предыдущем уроке мы разобрали, что multi-agent development нужен не всегда. Он полезен только тогда, когда есть task DAG, независимые ветви, tests, Git safety и понятные handoff artifacts.
Теперь нужно ответить на следующий вопрос:
Если агентов несколько, чем именно они отличаются?
Наивный ответ:
Один агент пишет backend, другой frontend, третий tests.
Это иногда полезно, но недостаточно. Главная идея role-based workflow не в том, что агенты называются по-разному. Главная идея в том, что у них разные:
- contexts;
- permissions;
- instructions;
- responsibilities;
- output contracts;
- stop conditions;
- handoff artifacts.
Иначе получится не multi-agent engineering, а несколько одинаковых write-capable agents, которые параллельно меняют файлы и подтверждают друг друга.
Практичная минимальная схема:
Planner
↓
Implementer
↓
Verifier
↓
Reviewer
Не обязательно использовать разные модели. Важнее иметь разные роли.
Основная идея
Роль агента - это не имя. Роль агента - это execution contract.
У каждой роли должны быть:
Goal
Inputs
Allowed context
Allowed tools
Forbidden actions
Output artifact
Stop conditions
Handoff target
Например:
Reviewer
Goal:
Find correctness, scope, security and test issues in a diff.
Inputs:
Specification, acceptance criteria, diff, relevant code, test evidence.
Allowed tools:
Read files, inspect diff, run read-only commands if needed.
Forbidden:
Do not implement fixes by default.
Do not approve without verification evidence.
Output:
Review findings ordered by severity.
Такой role contract полезнее, чем просто сказать:
Ты reviewer.
Ключевые термины
| Термин | Значение |
|---|---|
| Role | Ограниченная ответственность агента в workflow. |
| Role separation | Разделение planning, implementation, verification и review между разными contexts/permissions. |
| Context boundary | Какие документы, diffs, logs и history получает агент. |
| Permission boundary | Какие tools и действия разрешены роли. |
| Responsibility | За что роль отвечает и за что не отвечает. |
| Output contract | Формат результата, который роль должна передать дальше. |
| Handoff artifact | Проверяемый artifact между ролями: plan, task DAG, diff, test evidence, findings. |
| Role mixing | Смешивание ответственностей: reviewer чинит код, implementer меняет spec, verifier меняет tests. |
| Fresh context | Контекст без reasoning и assumptions предыдущего агента. |
| Approval gate | Точка, где дальнейшее действие требует evidence или human approval. |
Почему разные роли важнее разных моделей
Можно использовать разные модели, но это не главное.
Если у всех агентов:
- одинаковый context;
- одинаковые instructions;
- одинаковые tools;
- одинаковое право писать в любые файлы;
- одинаковая задача "сделай хорошо";
то они отличаются только именем.
Даже если один называется Planner, второй Reviewer, а третий Verifier, фактически это один и тот же агент с разными табличками.
Настоящая role separation появляется, когда:
- Planner не пишет production code;
- Implementer не меняет acceptance criteria;
- Verifier не переписывает tests ради pass;
- Reviewer не наследует assumptions implementer'а;
- Coordinator не silently resolves conflicts;
- каждый handoff содержит evidence.
Принцип:
Different roles can use the same model.
They must not have the same context, permissions and output contract.
Минимальная схема ролей
В маленьком workflow роли могут выполняться последовательно одним агентом, но с явным mode switch.
В multi-agent workflow роли лучше разделять по context и permissions.
Planner
Planner отвечает за структуру работы до implementation.
Цель Planner:
Понять задачу, ограничения, dependencies и подготовить execution plan.
Planner не должен сразу писать код. Его ценность в том, что он уменьшает неопределенность до того, как появится diff.
Inputs Planner
Planner получает:
- user request;
- specification;
- acceptance criteria;
- architecture/design docs;
- task graph, если есть;
- relevant repository map;
- known constraints;
- testing expectations;
- Git/worktree constraints;
- risks.
Planner может читать файлы, но не должен менять production code.
Responsibilities Planner
Planner должен:
- уточнить goal;
- выделить in scope и out of scope;
- определить dependencies;
- найти missing information;
- предложить task DAG или next task;
- отметить parallel-ready branches;
- определить verification strategy;
- предложить stop conditions;
- предложить role assignment, если multi-agent нужен.
Planner не должен:
- делать implementation;
- менять tests;
- менять spec без явного запроса;
- принимать product decisions вместо человека;
- скрывать uncertainty;
- расширять scope без approval.
Planner output
Хороший output:
Task:
AUTH-RESET-04: reject reused reset tokens.
In scope:
- regression test
- token consumed-state check
Out of scope:
- password policy
- UI
- email templates
Dependencies:
- reset token repository exists
Verification:
- targeted regression test
- password reset test file
Stop conditions:
- schema migration required
- error contract unclear
Recommended role:
- Implementer can proceed in branch fix/auth-token-reuse.
Плохой output:
Нужно поправить auth, добавить тесты и все проверить.
Это не plan. Это vague intent.
Implementer
Implementer отвечает за scoped change.
Цель Implementer:
Выполнить одну Agent Task как один reviewable diff.
Implementer работает внутри task boundary. Он не владеет всей feature и не должен менять правила игры.
Inputs Implementer
Implementer получает:
- task brief;
- acceptance criteria;
- in scope / out of scope;
- relevant code;
- tests/evals to update;
- expected files;
- verification commands;
- stop conditions;
- Git branch/worktree information.
Implementer не должен получать слишком широкий context, если это не нужно. Большой context повышает риск drift.
Responsibilities Implementer
Implementer должен:
- inspect relevant code;
- follow local patterns;
- add/update tests when practical;
- make minimal production-quality change;
- keep diff scoped;
- run targeted verification;
- report changed files;
- report commands/results;
- stop on scope expansion.
Implementer не должен:
- менять acceptance criteria под свой code;
- ослаблять tests ради green;
- делать drive-by refactor;
- менять unrelated files;
- выполнять destructive Git commands;
- approve собственный diff;
- скрывать failed/not-run checks.
Implementer output
Хороший output:
Task:
AUTH-RESET-04
Changed files:
- src/auth/resetTokenService.ts: rejects consumed token
- tests/auth/resetToken.test.ts: regression test
Verification:
- pytest tests/auth/test_reset_token.py::test_reuse_rejected: passed
- pytest tests/auth/test_reset_token.py: passed
Not run:
- browser E2E reset flow
Residual risk:
- concurrent double-submit not covered
Это output для Verifier и Reviewer.
Verifier
Verifier отвечает за evidence.
Цель Verifier:
Проверить, что claims implementer'а подтверждаются executable checks.
Verifier не обязан писать код. Часто его роль read/run/report.
Inputs Verifier
Verifier получает:
- task brief;
- implementation diff or branch;
- test/eval names;
- claimed verification commands;
- expected behavior;
- environment instructions;
- known not-run checks.
Verifier должен иметь доступ к запуску проверок, но не обязательно к edit tools.
Responsibilities Verifier
Verifier должен:
- rerun targeted tests/evals;
- inspect command results;
- confirm failure/pass status;
- distinguish test failure from setup failure;
- run broader regression when risk justifies it;
- report failed checks honestly;
- report not-run checks;
- verify output claims against tool logs, if possible.
Verifier не должен:
- чинить implementation by default;
- менять tests ради pass;
- менять acceptance criteria;
- approve merge;
- превращать failed checks в "minor issue";
- скрывать flaky behavior.
Verifier output
Хороший output:
Verification Report
Task:
AUTH-RESET-04
Commands run:
- pytest tests/auth/test_reset_token.py::test_reuse_rejected
Result: passed
- pytest tests/auth/test_reset_token.py
Result: passed
Not run:
- full E2E suite
Reason: not configured locally
Evidence status:
- targeted regression: confirmed
- nearby tests: confirmed
- broader browser flow: not confirmed
Risks:
- no concurrency test
Этот report идет Reviewer'у.
Reviewer
Reviewer отвечает за independent judgment.
Цель Reviewer:
Найти несоответствия spec, bugs, missing tests, scope creep и risk перед acceptance.
Reviewer должен быть максимально независимым от implementer context. Это будет подробно в следующем уроке.
Inputs Reviewer
Reviewer получает:
- specification;
- acceptance criteria;
- task brief;
- diff;
- relevant code;
- test/evidence report;
- known risks;
- project rules relevant to review.
Reviewer не должен получать полный reasoning implementer'а как основной input. Он может получить summary, но review должен идти по spec, diff и evidence.
Responsibilities Reviewer
Reviewer должен:
- проверить spec compliance;
- проверить, что diff соответствует task boundary;
- посмотреть tests/evals first;
- найти missing negative cases;
- проверить architecture constraints;
- проверить security-sensitive behavior;
- проверить, не ослаблены ли tests;
- проверить, не смешаны ли unrelated changes;
- сформулировать findings by severity;
- назвать open questions;
- сказать, если findings нет.
Reviewer не должен:
- просто спрашивать implementer "ты уверен?";
- approve без test evidence;
- чинить код by default;
- проводить style review вместо correctness review;
- игнорировать scope creep;
- наследовать assumptions implementer'а;
- менять task goal.
Reviewer output
Хороший output:
Review Findings
High:
- tests/auth/resetToken.test.ts does not assert password remains unchanged after second token use.
Risk: second request could still mutate password while returning error.
Medium:
- resetTokenService rejects consumed token, but controller maps all token errors to INVALID_TOKEN.
Confirm whether AUTH-RESET-04 requires TOKEN_ALREADY_USED.
No issues:
- Diff scope is limited to reset token service and tests.
Open questions:
- Should consumed token response hide token state for security?
Reviewer output не должен быть просто:
Looks good.
Если проблем нет, reviewer должен сказать, что проверил и где residual risk.
Coordinator
Coordinator не всегда отдельный агент. Часто это человек.
Цель Coordinator:
Управлять task DAG, role assignment, handoffs, branches, integration и gates.
Coordinator не должен быть "самым умным агентом, который делает все". Это control-plane роль.
Coordinator responsibilities:
- выбрать single-agent или multi-agent;
- назначить roles;
- подготовить worktrees/branches;
- определить handoff artifacts;
- следить за dependencies;
- решать, когда task blocked;
- запускать integration step;
- не допускать silent merge conflicts;
- требовать evidence before approval.
Coordinator output:
Orchestration Plan:
- Planner produces task DAG.
- Backend Implementer works in feature/auth-api.
- UI Implementer waits for API contract.
- Verifier reruns backend and UI tests.
- Reviewer reviews final integration diff.
В маленьком workflow Coordinator - это human developer, который дает агентам задачи.
Integrator
Integrator становится полезным, когда несколько branches нужно собрать вместе.
Цель Integrator:
Объединить результаты branches и проверить, что они работают вместе.
Integrator responsibilities:
- follow merge order;
- resolve conflicts carefully;
- preserve each branch's behavior;
- run integration tests;
- report conflicts and resolutions;
- stop if contract mismatch appears;
- not introduce new feature behavior during merge.
Integrator не должен:
- silently change API contract;
- hide conflicts;
- rewrite implementation during integration;
- skip tests because branches were green separately.
Integrator output:
Integration Report
Merged:
- feature/auth-reset-api
- feature/auth-reset-ui
- test/auth-reset-e2e
Conflicts:
- web/routes.tsx route order, resolved by keeping both routes
Verification:
- API tests: passed
- UI tests: passed
- E2E password reset: passed
Risks:
- full browser suite not run
В базовой схеме Integrator можно не выделять, но для реальных multi-agent ветвей он быстро становится нужен.
Specialist роли
Иногда Implementer делится по specialization:
- Backend Implementer;
- Frontend Implementer;
- Test Agent;
- Docs Agent;
- Migration Agent;
- Security Reviewer;
- Performance Reviewer;
- RAG Eval Agent;
- Tool Policy Agent.
Но specialization должна оставаться связанной с task boundary.
Плохо:
Backend Agent делает backend, UI, tests и docs, потому что увидел проблему.
Хорошо:
Backend Agent:
- endpoint and service
- API tests
- no UI
Frontend Agent:
- form and component tests
- no backend
Test Agent:
- E2E scenario
- no product implementation unless approved
Specialist role нужна, если она уменьшает context и risk. Если она просто добавляет label, она не помогает.
Permission Matrix
Permissions должны отличаться по роли.
| Role | Read files | Edit plan/spec | Edit production | Edit tests/evals | Run tests | Git commit | Merge/approve |
|---|---|---|---|---|---|---|---|
| Planner | yes | plan only | no | no | maybe | no | no |
| Implementer | scoped | no | scoped | scoped | yes | maybe | no |
| Test Agent | scoped | no | no by default | yes | yes | maybe | no |
| Verifier | yes | no | no | no by default | yes | no | no |
| Reviewer | yes | no | no by default | no | maybe | no | recommend only |
| Integrator | yes | no | conflict resolution only | conflict resolution only | yes | maybe | no by default |
| Coordinator | yes | plan/orchestration | no by default | no by default | maybe | maybe | gate decision |
Это пример, не универсальный закон. Но он показывает важный принцип:
Write permissions should be narrower than read permissions.
Approval permissions should be narrower than write permissions.
Context Matrix
Разные roles должны получать разный context.
| Role | Нужный context | Лишний или опасный context |
|---|---|---|
| Planner | User request, spec, architecture docs, task graph | Full implementation history of failed attempts |
| Implementer | Task brief, relevant files, local patterns, tests | Entire repository if task small |
| Verifier | Task brief, branch/diff, commands to run, expected behavior | Implementation reasoning as proof |
| Reviewer | Spec, AC, diff, relevant code, test evidence | Long implementer reasoning trace |
| Integrator | Branches, merge order, contracts, tests | Unrelated task discussions |
| Coordinator | DAG, role states, risks, blockers | Low-level code details unless needed |
Context is power. Too little context causes mistakes. Too much context causes drift and inherited assumptions.
Output Contracts
Каждая роль должна отдавать структурированный artifact.
| Role | Output artifact |
|---|---|
| Planner | Task brief, DAG, dependencies, role assignment, stop conditions |
| Implementer | Diff summary, changed files, tests run, residual risks |
| Verifier | Command evidence, pass/fail/not-run status, environment notes |
| Reviewer | Findings by severity, open questions, approval recommendation |
| Integrator | Merge report, conflict resolutions, integration test evidence |
| Coordinator | Decision log, next actions, blocked tasks, gate decisions |
Если output не структурирован, следующий agent получает conversation noise вместо usable handoff.
Handoff artifacts
Handoff artifact должен быть проверяемым и достаточно маленьким.
Плохой handoff:
Я вроде все сделал, проверь.
Хороший handoff:
Task:
AUTH-RESET-04
Branch:
fix/auth-token-reuse
Diff:
- src/auth/resetTokenService.ts
- tests/auth/resetToken.test.ts
Verification:
- targeted regression: passed
- password reset test file: passed
Not run:
- browser E2E
Risk:
- concurrent double-submit not covered
Handoff не должен требовать чтения всего agent transcript.
Handoff chain
Обратите внимание: Reviewer получает diff и evidence, а не просто final answer implementer'а.
Role Card Template
Для каждой роли можно завести role card.
# Role: <name>
## Goal
## Inputs
## Allowed Context
## Tools / Permissions
## Responsibilities
## Forbidden Actions
## Stop Conditions
## Output Contract
## Handoff Target
Role card можно хранить в:
docs/development/agent-roles.md;- project instructions;
- skill;
- orchestration config;
- team playbook.
Важно не сделать role card огромной. Она должна быть operational.
Role Card: Planner
# Role: Planner
## Goal
Turn user request and specification into a task DAG or scoped Agent Task.
## Inputs
- user request
- specification
- architecture/design docs
- existing task graph
- constraints and risks
## Tools / Permissions
- read files
- inspect repository structure
- no production code edits
- no commits
## Responsibilities
- define in scope / out of scope
- identify dependencies
- mark parallel-ready tasks
- define verification strategy
- define stop conditions
## Forbidden Actions
- implement code
- change product behavior
- silently expand scope
## Output Contract
- task brief
- dependencies
- expected files
- verification
- risks
- recommended next step
Role Card: Implementer
# Role: Implementer
## Goal
Complete one scoped Agent Task as one reviewable diff.
## Inputs
- task brief
- acceptance criteria
- relevant code
- tests/evals
- verification commands
- stop conditions
## Tools / Permissions
- edit scoped files
- add/update scoped tests
- run tests
- no merge
- no destructive Git commands
## Responsibilities
- follow local patterns
- keep diff focused
- add/update tests when practical
- run targeted verification
- report changed files and evidence
## Forbidden Actions
- change acceptance criteria
- weaken tests for green
- edit unrelated files
- approve own work
## Output Contract
- summary
- changed files
- verification commands/results
- not-run checks
- residual risks
Role Card: Verifier
# Role: Verifier
## Goal
Confirm that claimed behavior is supported by executable evidence.
## Inputs
- task brief
- branch/diff
- claimed tests/evals
- expected behavior
- environment notes
## Tools / Permissions
- read files
- run tests/evals
- inspect logs
- no production edits by default
- no test weakening
## Responsibilities
- rerun targeted checks
- run broader checks when justified
- report pass/fail/not-run honestly
- identify flaky or setup failures
## Forbidden Actions
- fix implementation by default
- rewrite tests to pass
- approve merge
## Output Contract
- verification report
- commands/results
- failures
- not-run checks
- residual risks
Role Card: Reviewer
# Role: Reviewer
## Goal
Find correctness, scope, security, architecture and test issues before approval.
## Inputs
- specification
- acceptance criteria
- task brief
- diff
- relevant code
- verification report
## Tools / Permissions
- read files
- inspect diff
- run read-only checks if needed
- no edits by default
## Responsibilities
- check spec compliance
- check tests/evidence
- find missing cases
- identify scope creep
- report findings by severity
## Forbidden Actions
- rely on implementer self-review
- approve without evidence
- focus on style before correctness
- silently fix code
## Output Contract
- findings by severity
- open questions
- residual risk
- approval recommendation
Combining roles
В маленьких workflows роли можно объединять, но нужно понимать risk.
Допустимо:
Single agent acts as Planner, then Implementer,
but switches modes and outputs plan before edits.
Допустимо:
Human acts as Coordinator and Reviewer.
Agent acts as Implementer.
CI acts as partial Verifier.
Рискованно:
Same agent writes code, writes tests, verifies them,
reviews own diff and approves merge.
Если роли объединяются, нужно усилить external checks:
- tests/evals;
- Git diff review;
- CI;
- human approval;
- independent reviewer for high-risk changes.
Когда роли нужно разделять физически
Разделять роли разными agent sessions/worktrees стоит, когда:
- change high-risk;
- diff large;
- task security-sensitive;
- implementer wrote tests and code;
- требуется independent review;
- несколько branches интегрируются;
- есть риск inherited assumptions;
- нужно parallel execution;
- разные permissions действительно нужны;
- context для одной роли мешает другой.
Пример:
Permission bug in project settings.
Здесь можно оставить implementation single-agent, но reviewer лучше fresh.
Role mixing
Role mixing - одна из главных ошибок multi-agent workflow.
Примеры:
| Mixing | Что идет не так |
|---|---|
| Planner начинает писать code | Plan не reviewится до implementation. |
| Implementer меняет spec | Реализация подгоняет цель под себя. |
| Implementer меняет tests after failure | Green может быть ложным. |
| Verifier чинит tests | Evidence становится зависимым от verifier edits. |
| Reviewer сам исправляет code | Findings и fix смешиваются. |
| Coordinator silently resolves conflicts | Integration decisions не reviewятся. |
| Test Agent меняет production code | Test coverage task превращается в feature task. |
Правило:
If a role needs to cross its boundary, stop and create a new explicit task or ask for approval.
Роли и Plan/Act Mode
Из модуля 8:
Plan Mode:
read, reason, propose
Act Mode:
edit, run, verify
Roles дополняют modes.
| Role | Typical mode |
|---|---|
| Planner | Plan Mode |
| Implementer | Act Mode |
| Verifier | Mostly run/inspect mode |
| Reviewer | Review/read-only mode |
| Coordinator | Planning/control mode |
Важно:
Role is responsibility.
Mode is allowed action style.
Planner в Act Mode опасен. Reviewer с write permission опасен. Implementer без Act Mode бессилен.
Роли и Git
Git artifacts должны соответствовать ролям.
| Role | Git interaction |
|---|---|
| Planner | может читать history/diff, но не commit |
| Implementer | работает в task branch/worktree |
| Verifier | checkout branch, run checks, no edits by default |
| Reviewer | review diff against base |
| Integrator | merge branches in planned order |
| Coordinator | manages branch/worktree plan |
Implementer output должен быть:
branch + diff + verification
Reviewer input должен быть:
spec + diff + evidence
Это делает review независимым от agent transcript.
Роли и tests/evals
Разные roles отвечают за разные части quality loop.
| Role | Test responsibility |
|---|---|
| Planner | определить verification strategy |
| Implementer | добавить/update tests when practical |
| Test Agent | расширить coverage по scoped behavior |
| Verifier | запустить tests/evals и report results |
| Reviewer | проверить, что tests доказывают AC |
| Coordinator | требовать evidence before merge |
Опасный pattern:
Implementer написал tests.
Implementer запустил tests.
Implementer сказал, что tests достаточны.
Reviewer не смотрел tests.
Лучше:
Implementer adds tests.
Verifier reruns tests.
Reviewer reviews test intent against AC.
Роли и permissions для tools/MCP
Если agent имеет tools, role boundaries должны включать tool permissions.
Пример:
| Tool | Planner | Implementer | Verifier | Reviewer | Coordinator |
|---|---|---|---|---|---|
read_file |
yes | yes | yes | yes | yes |
apply_patch |
no | scoped | no by default | no by default | no by default |
run_tests |
maybe | yes | yes | maybe | maybe |
git_diff |
yes | yes | yes | yes | yes |
git_commit |
no | with approval | no | no | with approval |
comment_on_pr |
no | maybe | maybe | yes | yes |
merge_pr |
no | no | no | no | with approval |
run_migration |
no | with approval | with approval in test env | no | with approval |
deploy |
no | no | no | no | usually no in course |
Роли должны ограничивать опасные side effects.
Если tool может удалять, deploy'ить, менять permissions, billing или production data, prompt-rule недостаточно. Нужны hard guardrails, approvals и audit. Это будет подробнее в модуле 12.
Роли для Password Reset
Feature:
Password Reset
Role plan:
| Role | Responsibility | Output |
|---|---|---|
| Planner | Build task DAG and identify API/UI/test branches | tasks.md, worktree plan |
| Backend Implementer | Request/reset endpoints and service tests | backend branch diff + test evidence |
| Frontend Implementer | Reset form using stable API contract | UI branch diff + component test evidence |
| Test Agent | E2E reset flow and negative cases | E2E branch diff + run evidence |
| Verifier | Rerun backend/UI/E2E checks | verification report |
| Reviewer | Review spec compliance and security cases | findings |
| Integrator | Merge branches and run integration tests | integration report |
Не все роли обязаны быть отдельными agents. Для курса можно сделать так:
Human:
Coordinator
Agent 1:
Planner
Agent 2:
Backend Implementer
Agent 3:
Frontend Implementer
Agent 4:
Verifier/Reviewer in fresh contexts
Важнее не количество agents, а ясность boundaries.
Роли для AI Agent workflow
Task:
AGENT-WF-01:
Plan Mode must not edit files.
Role plan:
| Role | Responsibility |
|---|---|
| Planner | Define mode policy and eval strategy |
| Policy Implementer | Add mode gate or instructions |
| Eval Agent | Add tool trace evals |
| Verifier | Run evals and inspect tool traces |
| Reviewer | Check that policy cannot be bypassed by prompt wording |
| Coordinator | Decide whether prompt rule is enough or hard tool gate needed |
Important handoff:
Forbidden tools in Plan Mode:
- apply_patch
- file write commands
- dependency install
- migration execution
Without this shared contract, each role may interpret "read-only" differently.
Роли для RAG feature
Task:
RAG assistant must answer with citations from retrieved sources.
Role plan:
| Role | Responsibility |
|---|---|
| Planner | Define retrieval/citation requirements |
| Retrieval Implementer | Improve retrieval/reranking |
| Answering Implementer | Update prompt/formatter |
| Eval Agent | Build citation/source support eval |
| Verifier | Run dataset regression |
| Reviewer | Check unsupported claims and citation semantics |
Potential role boundary:
Retrieval Implementer must not weaken citation eval.
Eval Agent must not tune dataset to current output.
Reviewer must inspect examples, not only aggregate score.
Handoff templates
Planner to Implementer
Task Brief
Task ID:
Goal:
Acceptance Criteria:
In scope:
Out of scope:
Expected files:
Verification:
Dependencies:
Stop conditions:
Risks:
Implementer to Verifier
Implementation Handoff
Task ID:
Branch/worktree:
Changed files:
- path: reason
Tests/evals added or updated:
Commands run:
- command: result
Not run:
- check: reason
Known risks:
Verifier to Reviewer
Verification Handoff
Task ID:
Commands rerun:
- command: result
Failures:
Flaky checks:
Not run:
Evidence status:
- targeted:
- nearby:
- integration:
Residual risk:
Reviewer to Implementer
Review Findings
Task ID:
High:
- finding
Medium:
- finding
Low:
- finding
Open questions:
Required changes before approval:
Optional follow-ups:
These templates keep the workflow boring in a good way.
Prompt-шаблоны для ролей
Planner prompt
Act as Planner.
Goal:
Turn the request into a scoped task or task DAG.
Permissions:
- read files;
- inspect specs and architecture docs;
- do not edit production code;
- do not change tests;
- do not commit.
Output:
- task ID and goal;
- in scope / out of scope;
- dependencies;
- parallel-ready tasks;
- verification strategy;
- stop conditions;
- recommended next role.
Request:
<request>
Implementer prompt
Act as Implementer.
Task brief:
<brief>
Permissions:
- edit only scoped files;
- add/update tests for this task;
- run targeted verification;
- do not modify unrelated files;
- do not change acceptance criteria;
- do not approve or merge.
Stop if:
- scope must expand;
- contract is unclear;
- migration or dependency change is required but not approved.
Final output:
- changed files;
- verification commands/results;
- not-run checks;
- residual risks.
Verifier prompt
Act as Verifier.
Inputs:
- task brief;
- branch/diff;
- implementer evidence.
Permissions:
- read files;
- run tests/evals;
- inspect logs;
- no edits by default.
Verify:
- targeted checks;
- nearby regression when justified;
- failed/not-run checks are reported honestly.
Output:
Verification report with commands, results, failures and residual risks.
Reviewer prompt
Act as Reviewer.
Inputs:
- specification;
- acceptance criteria;
- task brief;
- diff;
- relevant code;
- verification report.
Do not use implementer reasoning as proof.
Do not edit files by default.
Review in order:
1. Spec compliance
2. Tests/evidence
3. Scope creep
4. Architecture constraints
5. Security/risk
6. Maintainability
Output findings by severity.
Role design checklist
Для каждой роли проверьте:
[ ] Role has one clear goal
[ ] Inputs are defined
[ ] Context is bounded
[ ] Permissions are explicit
[ ] Forbidden actions are explicit
[ ] Output contract is structured
[ ] Stop conditions are defined
[ ] Handoff target is clear
[ ] Role does not approve itself
[ ] Role can be evaluated
Если роль не может быть evaluated, она слишком расплывчатая.
Как тестировать роли
Role behavior можно проверять evals.
Примеры:
| Role | Eval |
|---|---|
| Planner | Given vague feature, outputs DAG and stop conditions, no code edits. |
| Implementer | Given scoped task, edits only expected files and reports evidence. |
| Verifier | Given failed test output, reports failure honestly. |
| Reviewer | Given diff with missing negative test, reports finding. |
| Coordinator | Given dependent tasks, does not run them in parallel. |
AI Agent development требует tests не только для product behavior, но и для workflow behavior.
Практика 1. Описать роли для capstone feature
Feature:
Password Reset
Заполните:
| Role | Goal | Inputs | Permissions | Output |
|---|---|---|---|---|
| Planner | ||||
| Backend Implementer | ||||
| Frontend Implementer | ||||
| Test/Verifier | ||||
| Reviewer | ||||
| Integrator |
Дополнительно:
Shared contract:
Branch/worktree plan:
Integration point:
Approval gate:
Практика 2. Найти role mixing
Scenario:
Planner прочитал spec, сразу изменил код.
Implementer добавил tests, test failed, затем изменил expected result.
Verifier увидел failure и поправил production code.
Reviewer получил полный transcript implementer'а и написал "looks good".
Coordinator merged branch without integration tests.
Найдите нарушения:
| Action | Role mixing problem | Fix |
|---|---|---|
| Planner changed code | ||
| Implementer changed expected result | ||
| Verifier fixed code | ||
| Reviewer used full transcript | ||
| Coordinator merged without tests |
Практика 3. Permission matrix
Task:
Build agent workflow for bug fixes:
- reproduce bug;
- add regression test;
- implement fix;
- verify;
- review.
Заполните permissions:
| Role | Can read | Can edit tests | Can edit production | Can run tests | Can approve |
|---|---|---|---|---|---|
| Planner | |||||
| Implementer | |||||
| Verifier | |||||
| Reviewer | |||||
| Coordinator |
Возможный принцип:
Only Implementer edits production.
Only Reviewer recommends approval.
Only Coordinator or human performs final gate.
Verifier runs tests but does not rewrite them.
Практика 4. Handoff artifact
Составьте handoff от Implementer к Reviewer для task:
AGENT-WF-01:
Plan Mode must not edit files.
Handoff должен включать:
- task ID;
- acceptance criterion;
- changed files;
- evals added;
- commands/results;
- not-run checks;
- residual risks;
- diff scope.
Пример:
Task:
AGENT-WF-01
AC:
Plan Mode produces plan and no write/edit tools are called.
Changed files:
- agent/policy/modes.ts: adds plan-mode write-tool guard
- evals/agent_workflow/plan_mode_no_write_tools.yaml: regression eval
Verification:
- npm run eval -- plan-mode: passed
Not run:
- external MCP tool integration
Residual risks:
- only local tool trace fixture tested
Практика 5. Написать role card
Выберите одну роль:
- Planner;
- Implementer;
- Verifier;
- Reviewer;
- Integrator.
Заполните:
# Role:
## Goal
## Inputs
## Allowed Context
## Tools / Permissions
## Responsibilities
## Forbidden Actions
## Stop Conditions
## Output Contract
## Handoff Target
Проверьте:
Can another agent use this role card without asking what the role means?
Типичные ошибки
| Ошибка | Симптом | Исправление |
|---|---|---|
| Роль задана только названием | "Reviewer" делает implementation | Role card with permissions and forbidden actions. |
| Все роли имеют одинаковые tools | Role separation фиктивна | Tool permissions by role. |
| Planner пишет код | Plan не проходит gate | Planner read-only. |
| Implementer меняет spec | Goal подгоняется под code | Spec changes require approval. |
| Verifier меняет tests | Evidence перестает быть независимым | Verifier runs/reports, no edits by default. |
| Reviewer чинит code | Findings и implementation смешиваются | Reviewer outputs findings, fix is separate task. |
| Handoff как chat summary | Следующий агент наследует шум | Structured artifacts: spec, diff, evidence. |
| Reviewer без fresh context | Self-confirmation | Give spec, diff, code, evidence, not full reasoning. |
| No stop conditions | Agent crosses boundary silently | Define stop conditions per role. |
| No output contract | Невозможно проверить role performance | Structured role outputs. |
| Coordinator делает все | Нет separation | Coordinator manages flow, not implementation by default. |
Критерии готовности
После урока студент должен уметь:
- объяснить role separation;
- описать Planner, Implementer, Verifier и Reviewer;
- отличить role от model name;
- задать contexts и permissions by role;
- составить role card;
- определить output contract роли;
- описать handoff artifacts между ролями;
- заметить role mixing;
- решить, когда роли можно объединять, а когда нужно разделять;
- применить роли к capstone feature;
- подготовиться к independent reviewer workflow.
Краткое резюме
Multi-agent workflow становится управляемым только тогда, когда роли имеют четкие boundaries.
Практичная базовая схема:
Planner -> Implementer -> Verifier -> Reviewer
Роли не обязаны использовать разные модели. Но они должны иметь разные:
- contexts;
- permissions;
- instructions;
- responsibilities;
- output contracts;
- stop conditions.
Planner превращает goal в task boundary. Implementer делает scoped diff. Verifier подтверждает evidence. Reviewer ищет несоответствия в fresh context. Coordinator или human управляет gates и integration.
Главное правило:
Do not let one role silently cross into another role.
If boundary must change, create a new explicit task or ask for approval.
Вопросы для самопроверки
- Почему разные роли важнее, чем разные модели?
- Какие permissions должен иметь Planner?
- Почему Verifier не должен переписывать tests by default?
- Какие inputs нужны Reviewer'у для качественного review?
- Что такое role mixing и почему оно опасно?
Что дальше
В следующем уроке мы углубимся в самую важную роль для качества: independent Reviewer. Разберем, почему self-review того же agent context ненадежен, какие inputs должен получать fresh reviewer и как строить review по spec, diff, relevant code и test evidence.