Agent Dev 101

Модуль 14 · Урок 14.1

Урок 14.1. Capstone Production Flow и минимальный Agent Development Framework

На этой странице
  1. Зачем это нужно
  2. Основная идея
  3. Минимальный Agent Development Framework
  4. Production Flow из 12 stages
  5. Stage 1. Discover
  6. Stage 2. Specify
  7. Stage 3. Clarify
  8. Stage 4. Design
  9. Stage 5. Plan
  10. Stage 6. Tasks
  11. Stage 7. Baseline
  12. Stage 8. Implement
  13. Stage 9. Integration
  14. Stage 10. Review
  15. Stage 11. Acceptance
  16. Stage 12. Learn
  17. Capstone project: SaaS Task Manager
  18. Обязательные capstone artifacts
  19. Capstone flow
  20. Feature scope
  21. Definition of Done для Agent Task
  22. Autonomy levels
  23. Human-in-the-loop gates
  24. Как использовать open-source инструменты в capstone
  25. Итоговая матрица coverage курса
  26. Финальный acceptance checklist capstone
  27. Типичные ошибки capstone
  28. Практика
  29. Критерии готовности
  30. Краткое резюме
  31. Вопросы для самопроверки
  32. Что дальше

Зачем это нужно

К этому моменту курс разобрал отдельные элементы управляемой AI-разработки:

  • LLM failure modes;
  • specification;
  • architecture constraints;
  • task decomposition;
  • context engineering;
  • skills;
  • tools и MCP;
  • agent execution loop;
  • tests;
  • Git и worktrees;
  • multi-agent roles;
  • hooks и guardrails;
  • logs и evals.

Но студенту нужен финальный ответ на главный вопрос:

text
Как собрать все это в один процесс,
который можно применять к реальному проекту?

Capstone нужен, чтобы перестать воспринимать темы курса как отдельные лекции. В production AI Agent Development качество появляется не из одного хорошего prompt, а из связки artifacts, gates, tools, tests и человеческих решений.

Главная цель урока - описать минимальный Agent Development Framework и финальный capstone flow для проекта SaaS Task Manager.

Основная идея

AI Agent Development становится управляемым, когда у проекта есть не только агент, но и среда для агента.

Минимальная формула:

text
Project knowledge
+ small tasks
+ constrained context
+ automated verification
+ Git safety
+ independent review
+ human gates
= predictable agent development

Если убрать хотя бы один элемент, процесс начинает деградировать:

  • без specs агент угадывает;
  • без architecture constraints он ломает boundaries;
  • без tasks он делает слишком большой diff;
  • без tests уверенность не превращается в evidence;
  • без Git нельзя безопасно откатиться;
  • без review ошибки остаются незамеченными;
  • без human gates агент принимает product/security decisions.

Минимальный Agent Development Framework

В исходном плане курса предложена простая vendor-neutral структура:

text
project/
  PROJECT.md
  specs/
  skills/
  scripts/verify

В реальном проекте ее лучше расширить:

text
project/
  docs/
    product/
      vision.md
      glossary.md
    architecture/
      architecture.md
      adr/
        ADR-001-authentication.md
    development/
      coding-standards.md
      testing.md
      guardrails.md
      tool-policy.md
      agent-run-log.md

  specs/
    auth/
      spec.md
      design.md
      tasks.md
    projects/
      spec.md
      design.md
      tasks.md
    notifications/
      spec.md
      design.md
      tasks.md

  skills/
    create-api-endpoint/
      SKILL.md
    review-code/
      SKILL.md

  scripts/
    verify
    test
    lint

  evals/
    add-api-endpoint.md
    fix-null-bug.md
    database-migration.md
    security-fix.md

  src/
  tests/

Эта структура не привязана к одному агенту. Конкретный tool может требовать свои адаптеры:

  • CLAUDE.md;
  • Cursor Rules;
  • .roo/rules/;
  • .cline/rules/;
  • Kiro Steering;
  • Codex project instructions.

Но главный source of truth лучше держать в обычных Markdown, scripts и specs, которые понимают люди, агенты и Git.

Production Flow из 12 stages

Финальный workflow курса:

flowchart TD A[Discover] --> B[Specify] B --> C[Clarify] C --> D[Design] D --> E[Plan] E --> F[Tasks] F --> G[Baseline] G --> H[Implement] H --> I[Integration] I --> J[Review] J --> K[Acceptance] K --> L[Learn] L --> B

Это не бюрократия ради бюрократии. Каждый stage устраняет конкретный failure mode.

Stage 1. Discover

Discover отвечает на вопрос:

text
Зачем мы вообще делаем изменение?

Artifacts:

  • business problem;
  • goals;
  • non-goals;
  • constraints;
  • stakeholders;
  • risk notes.

Пример для capstone:

text
Business problem:
Small teams need a simple task manager with projects,
assignment notifications and audit trail.

Goal:
Allow team members to create projects and tasks,
assign owners and track important changes.

Non-goals:
- billing
- public marketplace
- mobile app
- advanced reporting

Constraints:
- audit log for security-relevant actions
- tests required for core flows
- no production deploy without human approval

Agent на этом этапе может помочь структурировать вопросы, но product decision принимает человек.

Stage 2. Specify

Specify превращает цель в behavior.

Artifacts:

text
spec.md

Содержание:

  • goal;
  • non-goals;
  • actors;
  • current behavior;
  • desired behavior;
  • requirements;
  • acceptance criteria;
  • edge cases;
  • security requirements;
  • open questions.

Пример requirement:

text
REQ-PROJ-001:
Authenticated user can create a project inside a team
where they have member or admin role.

Пример acceptance criterion:

text
AC-PROJ-001:
Given an authenticated team member,
when they submit valid project name,
then API returns 201 with project id, name, team id and created_at.

Stage 3. Clarify

Clarify нужен, чтобы агент не закрывал пробелы догадками.

Workflow:

text
draft spec
-> ambiguity review
-> questions
-> human decisions
-> approved spec

Пример questions:

  • Должны ли project names быть уникальными внутри team?
  • Может ли viewer создавать project?
  • Что делать с archived team?
  • Нужно ли писать audit log при failed create attempt?
  • Какой error code возвращать при duplicate name?

После ответов человека spec обновляется. Без approved spec агент не должен переходить к design/code.

Stage 4. Design

Design переводит behavior в technical approach.

Artifacts:

text
design.md

Содержание:

  • components;
  • interfaces;
  • data model;
  • sequence diagrams;
  • security considerations;
  • dependencies;
  • migrations;
  • alternatives;
  • risks.

Пример design decision:

text
Project creation goes through ProjectService.
Controller must not write directly to database.
AuditLogService records PROJECT_CREATED after successful transaction.

Если решение влияет на многие future tasks, оно оформляется как ADR.

Stage 5. Plan

Plan задает implementation strategy.

Artifact:

text
plan.md

План отвечает:

  • в каком порядке менять части системы;
  • какие tests писать сначала;
  • какие migrations нужны;
  • какие contracts обновить;
  • где integration point;
  • какие риски требуют human gate.

Плохой plan:

text
Implement backend and frontend.

Хороший plan:

text
1. Add project table migration.
2. Add domain model and repository tests.
3. Add ProjectService with validation.
4. Add POST /api/projects controller and API tests.
5. Update OpenAPI contract.
6. Add frontend form.
7. Add E2E happy path.
8. Run full verification.

Stage 6. Tasks

Tasks превращают plan в маленькие Agent Tasks.

Artifact:

text
tasks.md

Пример:

text
[ ] PROJ-01 Create project table migration
[ ] PROJ-02 Add ProjectRepository tests and implementation
[ ] PROJ-03 Add ProjectService validation
[ ] PROJ-04 Add POST /api/projects endpoint
[ ] PROJ-05 Update OpenAPI contract and generated types
[ ] PROJ-06 Add frontend create project form
[ ] PROJ-07 Add E2E create project flow

Каждая task должна иметь:

  • goal;
  • inputs;
  • allowed scope;
  • do not modify;
  • acceptance criteria;
  • verification command;
  • expected output.

Stage 7. Baseline

Baseline отвечает на вопрос:

text
Проект был green до изменений?

Команды:

bash
scripts/verify

или отдельно:

bash
npm run lint
npm run typecheck
npm test
npm run build

Если baseline red, агент не сможет отличить старую проблему от новой. Нужно либо исправить baseline, либо явно зафиксировать known failures.

Baseline record:

text
Baseline:
- command: scripts/verify
- result: PASS
- commit: abc123
- notes: no known failures

Stage 8. Implement

Implementation проходит task by task.

Loop:

text
Read task
-> Read relevant spec/design
-> Inspect code
-> Write or update failing test
-> Implement
-> Run focused verification
-> Review diff
-> Commit

Agent не должен начинать с edit. Он начинает с чтения и понимания boundaries.

Пример agent prompt:

text
Implement TASK PROJ-04 only.

Read:
- specs/projects/spec.md
- specs/projects/design.md
- specs/projects/tasks.md

Allowed scope:
- src/projects/*
- tests/projects/*
- api/openapi.yaml

Do not modify:
- auth subsystem
- billing
- existing migrations except adding a new migration

Verification:
- pytest tests/projects/test_create_project.py
- npm run openapi:lint
- scripts/verify

Stage 9. Integration

Integration является отдельным этапом, а не побочным эффектом.

Особенно при worktrees и parallel agents:

text
backend branch
frontend branch
contract branch
tests branch
-> integration branch
-> conflict resolution
-> integration tests
-> E2E

Integration проверяет:

  • совпадают ли API и frontend expectations;
  • не сломаны ли migrations;
  • нет ли race conditions между changes;
  • не нарушены ли architecture boundaries;
  • проходит ли full verification.

Stage 10. Review

Review выполняется в строгом порядке:

text
Specification Compliance
-> Architecture Compliance
-> Code Quality
-> Security
-> Tests

Почему именно так?

Код может быть красивым, но реализовывать неправильное поведение.

Tests могут проходить, но проверять не те acceptance criteria.

Architecture может быть нарушена, даже если feature работает локально.

Security риск может не проявиться в happy path.

Review prompt:

text
Review this change as an independent reviewer.

Use only:
- approved spec
- design
- task
- diff
- relevant code
- test output

Check in order:
1. Specification compliance
2. Architecture compliance
3. Code quality
4. Security
5. Tests

Return findings with severity and file references.

Stage 11. Acceptance

Acceptance закрывает каждое AC явно.

Пример:

text
AC-PROJ-001 PASS
Evidence: tests/projects/test_create_project.py::test_create_project_success

AC-PROJ-002 PASS
Evidence: tests/projects/test_create_project.py::test_create_project_requires_name

AC-PROJ-003 PASS
Evidence: tests/projects/test_create_project.py::test_duplicate_project_name

AC-PROJ-004 MANUAL PASS
Evidence: reviewer checked audit log event in diff

Нельзя писать:

text
Вроде все готово.

Acceptance должен показывать evidence.

Stage 12. Learn

После delivery проект должен стать умнее.

Вопросы:

text
Появилось стабильное правило?
-> Update project rules

Появилась повторяемая процедура?
-> Create or update skill

Появилось архитектурное решение?
-> Write ADR

Изменилось product behavior?
-> Update spec

Появился типовой failure?
-> Add regression test or eval

Так формируется накопленная память проекта, но не в виде бесконечного prompt. Знания распределяются по правильным artifacts.

Capstone project: SaaS Task Manager

Финальный проект курса:

text
SaaS Task Manager with:
- registration
- teams
- projects
- tasks
- notifications
- audit log

Главное ограничение:

text
Запрещено реализовывать проект одной командой.

Студент должен провести проект через весь pipeline.

Обязательные capstone artifacts

text
docs/product/vision.md
docs/product/glossary.md
docs/architecture/architecture.md
docs/architecture/adr/ADR-001-authentication.md
docs/development/coding-standards.md
docs/development/testing.md
docs/development/guardrails.md

specs/auth/spec.md
specs/auth/design.md
specs/auth/tasks.md

specs/projects/spec.md
specs/projects/design.md
specs/projects/tasks.md

specs/notifications/spec.md
specs/notifications/design.md
specs/notifications/tasks.md

skills/create-api-endpoint/SKILL.md
skills/review-code/SKILL.md

scripts/verify

evals/add-api-endpoint.md
evals/fix-null-bug.md
evals/database-migration.md
evals/security-fix.md

Capstone flow

flowchart TD A[Vision] --> B[PRD] B --> C[Architecture] C --> D[ADR] D --> E[Feature Specs] E --> F[Acceptance Criteria] F --> G[Task DAG] G --> H[Skills] H --> I[MCP / Tools policy] I --> J[Worktrees] J --> K[Agent Implementation] K --> L[Tests] L --> M[Independent Agent Review] M --> N[CI] N --> O[Release] O --> P[Learn: specs / skills / evals]

Feature scope

Auth

Minimum behavior:

  • user can register;
  • user can sign in;
  • authenticated session is represented consistently;
  • auth decisions are captured in ADR;
  • security requirements are explicit.

Artifacts:

  • specs/auth/spec.md;
  • specs/auth/design.md;
  • specs/auth/tasks.md;
  • docs/architecture/adr/ADR-001-authentication.md.

Projects

Minimum behavior:

  • team member can create project;
  • project belongs to team;
  • validation rules are explicit;
  • API contract is updated if API exists;
  • audit log records project creation.

Artifacts:

  • specs/projects/spec.md;
  • specs/projects/design.md;
  • specs/projects/tasks.md.

Notifications

Minimum behavior:

  • user receives notification on task assignment;
  • failed delivery is represented;
  • retry/non-retry behavior is specified;
  • audit log captures relevant events;
  • privacy and security concerns are written down.

Artifacts:

  • specs/notifications/spec.md;
  • specs/notifications/design.md;
  • specs/notifications/tasks.md.

Definition of Done для Agent Task

Agent task не готова, пока не выполнен DoD.

text
[ ] Requirement understood
[ ] Existing implementation inspected
[ ] Scope respected
[ ] Tests added or updated
[ ] Tests pass
[ ] Typecheck passes
[ ] Lint passes
[ ] Build passes
[ ] Acceptance criteria verified
[ ] No unrelated files changed
[ ] Diff reviewed
[ ] Documentation updated if necessary
[ ] No secrets introduced
[ ] No debug code remains

Минимальный report агента:

text
Task:
TASK PROJ-04

Changed files:
- src/projects/controller.ts
- tests/projects/create-project.test.ts
- api/openapi.yaml

Verification:
- npm test -- create-project: PASS
- npm run openapi:lint: PASS
- npm run typecheck: PASS

Acceptance:
- AC-PROJ-001 PASS
- AC-PROJ-002 PASS

Notes:
- No unrelated files changed.
- Full scripts/verify should run before merge.

Autonomy levels

Курс должен учить постепенной автономности.

Level Что делает AI Что делает человек
0 Предлагает идеи и объяснения Пишет код сам
1 Редактирует маленькие фрагменты Одобряет почти каждое изменение
2 Реализует одну task Проверяет diff и evidence
3 Выполняет несколько tasks с checkpoints Принимает milestone decisions
4 Несколько agents работают в worktrees Человек утверждает integration/merge
5 Автоматизированный pipeline с сильными guardrails Человек вмешивается по exceptions

Не нужно прыгать с Level 1 на Level 5. Автономность должна расти вместе с verification.

Правило:

text
Больше автономности
требует больше specs, tests, logs, guardrails и rollback.

Human-in-the-loop gates

В курсе обязательно фиксируются четыре gates:

Gate Когда нужен человек Почему
Product Decision Меняется смысл продукта или user behavior Агент не владелец product intent.
Major Architecture Decision Выбор auth, data model, integration boundary, storage strategy Ошибка дорого стоит и влияет на многие tasks.
High-risk Action Delete, deploy, billing, secrets, permissions, irreversible migration Нужна ответственность и risk control.
Final Merge Изменение входит в main branch Нужна финальная проверка соответствия цели.

Все остальное можно постепенно делегировать, если есть:

  • clear scope;
  • verification;
  • logs;
  • rollback;
  • review.

Как использовать open-source инструменты в capstone

Capstone не должен зависеть от одного vendor tool. Лучше мыслить слоями:

Слой Возможные инструменты
Coding agent harness Codex, Claude Code, Cursor, Kiro, Cline, Roo Code, Aider
SDD workflow простая структура spec/design/tasks, Spec Kit, OpenSpec, Kiro Specs, BMAD, Superpowers, Agent-OS
API contracts OpenAPI, AsyncAPI, JSON Schema, TypeScript types, Swagger tools, Specmatic, Redocly, Stoplight / Elements
Tools/MCP read-only resources, controlled tools, scripts, MCP servers
Runtime frameworks OpenAI Agents SDK, LangGraph, AutoGen, CrewAI, если capstone расширяется до agentic product
Verification unit/integration/E2E/contract tests, CI, evals

Для учебного проекта лучший старт:

text
Git
+ normal project toolchain
+ one coding agent
+ Markdown SDD artifacts
+ scripts/verify
+ tests
+ CI

Open-source tooling полезен, когда он:

  • оставляет понятные файлы в repository;
  • запускается локально;
  • поддерживает CLI;
  • легко подключается к CI;
  • имеет понятную лицензию;
  • не прячет source of truth в UI.

Итоговая матрица coverage курса

Тема из исходных планов Где закрывается
LLM failure modes Module 01
Chatbot, agent, coding agent Module 01
Tooling landscape Module 01, lesson 1.4
Specification-Driven Development Module 02
SDD toolkits Module 02, lesson 2.6
API specification tools Module 02, lesson 2.6
Architecture and ADR Module 03
Task decomposition and DAG Module 04
Context engineering and project instructions Module 05
Skills Module 06
Tools and MCP Module 07
Agent execution loop Module 08
Testing and TDD Module 09
Git, worktrees, checkpoints Module 10
Multi-agent roles and orchestration Module 11
Agent runtime frameworks Module 11, lesson 11.5
Hooks and guardrails Module 12
Observability and evals Module 13
Production flow and capstone Module 14

Финальный acceptance checklist capstone

text
[ ] Есть vision и glossary.
[ ] Есть architecture.md.
[ ] Есть минимум один ADR.
[ ] Auth имеет spec/design/tasks.
[ ] Projects имеет spec/design/tasks.
[ ] Notifications имеет spec/design/tasks.
[ ] Каждая task имеет allowed scope.
[ ] Каждая task имеет verification command.
[ ] Есть skills/create-api-endpoint/SKILL.md.
[ ] Есть skills/review-code/SKILL.md.
[ ] Есть scripts/verify.
[ ] Есть eval scenarios.
[ ] Есть traceability matrix requirement -> AC -> test.
[ ] Automated checks проходят.
[ ] Independent review выполнен после implementation.
[ ] Review проверял spec, architecture, code, security, tests.
[ ] Human gates зафиксированы.
[ ] Студент может объяснить, какие решения делегированы агенту, а какие оставлены человеку.

Типичные ошибки capstone

Ошибка 1. Делать capstone одной командой

Это разрушает смысл курса. Capstone проверяет process, а не способность модели нагенерировать много кода.

Ошибка 2. Писать specs после кода

Specs, написанные после implementation, часто становятся оправданием текущего решения. В SDD они должны направлять implementation.

Ошибка 3. Считать green tests полным acceptance

Tests могут проходить, но не покрывать все acceptance criteria. Нужна traceability matrix.

Ошибка 4. Не отделять generated changes

Generated clients, migrations и formatted files могут создать шумный diff. Их лучше выделять отдельными tasks или явно отмечать в review.

Ошибка 5. Не фиксировать learning

Если после каждого failure не обновлять rules, skills, tests или evals, проект не становится устойчивее. Следующий agent повторит ту же ошибку.

Практика

Практика 1. Соберите skeleton capstone

Создайте только структуру artifacts без реализации:

text
docs/product/vision.md
docs/product/glossary.md
docs/architecture/architecture.md
docs/architecture/adr/ADR-001-authentication.md
docs/development/testing.md
docs/development/guardrails.md
specs/auth/spec.md
specs/auth/design.md
specs/auth/tasks.md
scripts/verify

Цель: проверить, что проект можно вести через artifacts, а не через один prompt.

Практика 2. Проведите одну feature через 12 stages

Выберите:

text
POST /api/projects

И пройдите:

text
Discover
-> Specify
-> Clarify
-> Design
-> Plan
-> Tasks
-> Baseline
-> Implement
-> Integration
-> Review
-> Acceptance
-> Learn

Минимальный результат:

  • spec.md;
  • design.md;
  • tasks.md;
  • один implementation diff;
  • tests;
  • verification output;
  • review notes;
  • updated rule/skill/eval if needed.

Практика 3. Определите autonomy level

Для каждой capstone task укажите:

text
Autonomy level:
Human gates:
Allowed tools:
Verification:
Rollback plan:

Пример:

text
TASK AUTH-01 Authentication ADR
Autonomy level: 1
Human gates: Major Architecture Decision
Allowed tools: read files, draft ADR
Verification: human approval
Rollback plan: Git diff discard before commit

Критерии готовности

После урока студент должен уметь:

  • собрать минимальный Agent Development Framework в repository;
  • пройти feature через 12-stage production flow;
  • объяснить роль каждого artifact;
  • применить Definition of Done к agent task;
  • выбрать разумный autonomy level;
  • указать human gates;
  • доказать acceptance через evidence;
  • объяснить, как specs, skills, rules, tests и evals обновляются после delivery.

Краткое резюме

Capstone соединяет весь курс. Управляемая AI-разработка строится не вокруг одного prompt, а вокруг системы artifacts и gates: vision, specs, design, tasks, skills, tools policy, tests, Git, review, CI, evals и learning loop.

Минимальный Agent Development Framework можно реализовать обычными файлами в repository. Инструменты могут отличаться, но роли artifacts остаются стабильными.

Вопросы для самопроверки

  1. Почему capstone нельзя реализовывать одной командой?
  2. Какие artifacts обязательны для SaaS Task Manager?
  3. Чем Acceptance отличается от green tests?
  4. Какие четыре human-in-the-loop gates должны быть в проекте?
  5. Почему autonomy level должен расти вместе с verification?

Что дальше

После capstone студент может адаптировать framework под свой рабочий проект: выбрать конкретный coding agent, SDD toolkit, contract tooling, CI checks, skills, MCP resources и eval suite. Главное - сохранить принцип: агент получает маленькую задачу, ограниченный контекст и внешнюю verification.

Обновлено 03.10.2026