Step 1: Project Example
Эта глава собирает в один практический blueprint то, как должен выглядеть управляемый OpenCode-проект: stage-based delivery, шаблон AGENTS.md, Stage Report, готовые prompts, тестовая дисциплина и большой end-to-end пример на online shop.
Как должен выглядеть управляемый OpenCode-проект
Правильная модель для OpenCode-проекта звучит не как "попросить агента сделать большой проект", а как "вести проект короткими управляемыми циклами". В центре не объем генерации, а предсказуемость поставки.
Главный сдвиг мышления
Не давайте агенту сразу весь проект. Давайте ему следующий контролируемый этап проекта с четкой целью, ограниченным scope, проверкой, review и понятным следующим шагом.
- У каждого цикла должна быть понятная цель.
- Scope должен быть ограниченным и наблюдаемым.
- Результат должен быть измеримым и демонстрируемым.
- После реализации нужна проверка и отдельный review-проход.
- Завершение этапа должно фиксироваться отчетом и recommended next step.
Четыре рабочих режима
| Режим | Зачем нужен |
|---|---|
| Plan | Понять, что и как делать, зафиксировать scope, риски и способ проверки. |
| Build | Сделать минимальный рабочий инкремент без расползания по репозиторию. |
| Review | Отдельно проверить correctness, contract drift, missing tests и architecture drift. |
| Docs / Report | Зафиксировать, что сделано, что проверено, что осталось и какой следующий этап логичен. |
Готовый шаблон AGENTS.md
Ниже универсальный шаблон, который можно положить в корень репозитория и адаптировать под конкретный стек, процессы и ограничения проекта.
# AGENTS.md
## Purpose
This repository is developed with AI-assisted workflows in OpenCode.
Agents working in this repo must prioritize:
- correctness
- maintainability
- explicit architecture
- testability
- safe incremental delivery
- business value per stage
Do not treat this repo as a one-shot generation task.
Work in small, reviewable increments.
---
## Working model
### Default execution model
For any non-trivial task:
1. Start with a plan.
2. Limit scope to the current stage only.
3. Implement the minimum viable increment.
4. Run relevant verification.
5. Produce a concise change report.
Do not attempt broad uncontrolled rewrites unless explicitly asked.
### Stage discipline
Work must be organized into stages.
Each stage should:
- produce demonstrable value
- be testable
- be reviewable
- have clear acceptance criteria
- have clear out-of-scope boundaries
### End-to-end preference
Prefer vertical slices over layer-by-layer delivery.
Do not build the whole backend first and postpone frontend/integration until later unless explicitly requested.
For product features, prefer:
- backend changes
- frontend changes
- DB changes
- integration
- tests
within the same stage.
---
## Planning rules
Before making large or risky changes, produce a plan that includes:
- objective
- scope
- out of scope
- impacted modules
- data model changes
- API changes
- frontend changes
- risks
- verification strategy
- rollout / migration notes if applicable
If the task is ambiguous, choose the simplest extensible design and state assumptions explicitly.
---
## Code quality rules
### General
- Prefer simple, explicit code over clever abstractions.
- Keep functions and modules cohesive.
- Avoid hidden side effects.
- Avoid premature generalization.
- Follow existing project conventions unless they are clearly harmful.
### Readability
- Write code for future maintainers.
- Use descriptive names.
- Keep files focused.
- Remove dead code when safe to do so.
- Do not leave unexplained hacks.
### Architecture
- Respect module boundaries.
- Do not introduce circular dependencies.
- Keep business logic out of UI glue code.
- Keep transport concerns separate from domain logic.
- Keep persistence concerns separate from application behavior where practical.
### Change safety
- Minimize blast radius.
- Avoid unnecessary rewrites.
- Preserve backward compatibility unless the task explicitly allows breaking changes.
- If a breaking change is introduced, document it clearly.
---
## Testing rules
Testing is required for meaningful changes.
### Minimum expectations
For each completed stage, add or update the appropriate level of tests:
- unit tests for isolated logic
- integration tests for contracts and boundaries
- end-to-end or smoke tests for critical user flows
- migration verification for DB changes
- type checks / lint / static analysis where applicable
### Required mindset
Do not say "done" if code was written but not verified.
If tests cannot be run, state exactly why.
### Test priority
Prioritize tests for:
- critical business flows
- auth / permissions
- money-related logic
- order / workflow transitions
- data integrity
- external integrations
- error handling
---
## Database and migrations
For any DB change:
- prefer explicit migrations
- make schema changes reversible when practical
- document data migration implications
- avoid destructive changes without explicit warning
- preserve production safety
If changing schema:
- update related models
- update seeds / fixtures if needed
- update integration tests
- mention rollout order if relevant
---
## API and contracts
For any API change:
- keep contracts explicit
- update request/response types
- update docs or examples if applicable
- preserve backward compatibility where possible
- document breaking changes clearly
When frontend and backend both change:
- keep payload contracts aligned
- do not leave frontend relying on stale mocks unless explicitly temporary
- state temporary mismatches clearly if they exist
---
## Frontend rules
Frontend changes must prioritize:
- clarity
- predictable state flow
- loading/error/empty states
- accessibility basics
- minimal but consistent UX
Do not build visual complexity before flow correctness.
Prefer working user paths over decorative completeness.
---
## Infrastructure and operations
Treat infra changes as production-sensitive.
### For infra-related tasks
- prefer configuration as code
- show intended changes explicitly
- mention rollout order
- mention rollback path
- do not run destructive commands unless explicitly authorized
### Secrets and safety
- never hardcode secrets
- do not expose credentials in logs or code
- prefer environment-based configuration
- preserve least privilege assumptions
---
## Verification commands
Agents should run the smallest relevant set of checks for the current scope.
Examples (customize for project):
- install deps: `make install` or `pnpm install && pip install -r requirements.txt`
- backend lint: `make lint-backend`
- frontend lint: `make lint-frontend`
- typecheck: `make typecheck`
- backend tests: `make test-backend`
- frontend tests: `make test-frontend`
- integration tests: `make test-integration`
- e2e tests: `make test-e2e`
- full check: `make check`
If project-specific commands differ, use those.
---
## Expected final response format for implementation tasks
At the end of a task, provide:
1. Summary of changes
2. Files/modules affected
3. Verification performed
4. Known risks / tech debt / assumptions
5. Manual QA steps
6. Recommended next step
Do not claim verification that was not actually run.
---
## Review expectations
A review pass should look for:
- correctness issues
- edge cases
- missing tests
- risky migrations
- contract drift
- architecture drift
- unnecessary complexity
- maintainability issues
Review output should separate:
- critical issues
- important follow-ups
- optional improvements
---
## Delivery philosophy
The goal is not maximal code generation.
The goal is controlled delivery of working software.
Favor:
- small stages
- explicit assumptions
- visible progress
- stable contracts
- end-to-end validation
- maintainable code
over:
- giant rewrites
- implicit decisions
- hidden complexity
- unverified output
---
## If unsure
If unsure:
- inspect relevant code first
- propose a small safe plan
- choose the minimal extensible design
- document assumptions
- avoid pretending certainty
Как адаптировать шаблон под проект
Универсальный шаблон полезен только как старт. В боевой версии его нужно насытить проектными деталями, чтобы агент видел реальные слои, границы и команды.
Backend
Укажите стек, слои domain/application/infra, правила миграций, расположение тестов и naming для DTO, schemas и entities.
Frontend
Опишите стек, маршруты, shared UI, API clients, state management и подход к loading/error/form flows.
Database
Зафиксируйте тип БД, создание миграций, наличие seed-данных, rollback-проверки, индексы и constraints.
Infra
Опишите Docker, Compose, K8s, Terraform, обязательные env, staging/prod overrides и способ проверки deploy-safe changes.
Stage Report и Stage Definition
Stage Report нужен для видимости прогресса. Не "агент что-то поделал", а "вот что реально произошло, что проверено и что делать дальше".
Полный шаблон STAGE_REPORT.md
# Stage Report
## Stage
[Stage name]
## Objective
[What this stage was supposed to achieve]
## Scope
[What is included in this stage]
## Out of scope
[What is intentionally not included]
## Business value
[What user or business capability is enabled by this stage]
---
## Implemented
### Backend
- [change]
- [change]
- [change]
### Frontend
- [change]
- [change]
- [change]
### Database
- [schema / migration / seed change]
### Infrastructure / DevEx
- [CI / Docker / config / observability / scripts]
---
## API / contract changes
- [new endpoint]
- [changed payload]
- [breaking change if any]
---
## Files / modules affected
- [module/path]
- [module/path]
- [module/path]
---
## Verification performed
### Automated checks run
- [command] — [result]
- [command] — [result]
- [command] — [result]
### Manual checks performed
- [manual scenario]
- [manual scenario]
### Not verified
- [what could not be verified]
- [why]
---
## Acceptance criteria status
- [criterion] — Done / Partial / Not done
- [criterion] — Done / Partial / Not done
- [criterion] — Done / Partial / Not done
---
## Known issues
- [issue]
- [issue]
## Tech debt introduced or preserved
- [debt]
- [debt]
## Assumptions
- [assumption]
- [assumption]
## Risks
- [risk]
- [risk]
---
## Manual QA checklist
- [step]
- [step]
- [step]
---
## Release notes
### Added
- [item]
### Changed
- [item]
### Fixed
- [item]
### Deferred
- [item]
---
## Recommended next stage
[What should be implemented next and why]
Короткая форма для повседневной работы
# Stage Summary
## Done
- ...
## Verified
- ...
## Not verified
- ...
## Risks / debt
- ...
## QA steps
- ...
## Next
- ...
Шаблон Stage Definition
# Stage Definition
## Name
[Stage name]
## Goal
[User-visible or business-visible capability]
## Business value
[Why this stage matters]
## Scope
- ...
- ...
- ...
## Out of scope
- ...
- ...
- ...
## Backend work
- ...
- ...
## Frontend work
- ...
- ...
## Database work
- ...
- ...
## Infra / DevEx work
- ...
- ...
## Acceptance criteria
- ...
- ...
- ...
## Required tests
- unit:
- integration:
- e2e/smoke:
## Risks
- ...
- ...
## Dependencies
- ...
- ...
## Deliverables
- code
- tests
- stage report
- release notes
- QA checklist
Набор промптов для OpenCode
Готовые prompts полезны не потому, что они "волшебные", а потому что они стабилизируют форму работы. Ниже минимальный набор для stage-based delivery.
Prompt для plan
You are working in a controlled stage-based delivery workflow.
Task:
[describe the task]
Your job now is PLAN ONLY.
Do not modify files yet.
Produce a structured implementation plan with:
1. Objective
2. Scope
3. Out of scope
4. Business value
5. Impacted modules/files
6. Backend changes
7. Frontend changes
8. Database changes
9. API / contract changes
10. Infra / config implications
11. Risks
12. Assumptions
13. Verification plan
14. Recommended implementation order
Constraints:
- prefer the smallest viable increment
- prefer end-to-end deliverable slices
- avoid broad rewrites
- preserve maintainability
- call out breaking changes explicitly
- if ambiguous, choose the simplest extensible design
At the end, include:
- Acceptance criteria
- Suggested stage name
- Estimated blast radius (small / medium / large)
Prompt для build
Implement the approved plan for the current stage.
Rules:
- stay within scope
- do not expand the task unless necessary
- prefer minimal viable implementation
- keep frontend/backend/db aligned
- update tests relevant to the change
- preserve project conventions
- document assumptions in final report
- do not claim verification that was not run
Required final output:
1. Summary of changes
2. Files/modules affected
3. Verification performed
4. Not verified
5. Known risks / tech debt / assumptions
6. Manual QA checklist
7. Recommended next step
Prompt для review
Review the current changes as a strict senior engineer.
Focus on:
- correctness
- maintainability
- architecture drift
- missing tests
- contract drift
- migration risk
- edge cases
- security / auth / data integrity issues
- unnecessary complexity
Output format:
## Critical issues
- ...
## Important follow-ups
- ...
## Nice-to-have improvements
- ...
## Testing gaps
- ...
## Migration / rollout concerns
- ...
## Overall assessment
[Ready / Ready with follow-ups / Not ready]
Prompt для debug
Investigate the issue without making broad unrelated changes.
Problem:
[describe bug]
Your task:
1. identify likely root cause
2. inspect affected flow
3. propose minimal fix
4. list regression risks
5. define verification steps
Prefer the smallest safe correction.
Do not rewrite unrelated modules.
Prompt для stage report
Produce a Stage Report for the work just completed.
Include:
- objective
- implemented backend/frontend/db/infra changes
- contract changes
- verification performed
- not verified
- acceptance criteria status
- known issues
- tech debt
- assumptions
- manual QA checklist
- release notes
- recommended next stage
Пример для Catalog MVP
Для конкретного stage полезно добавлять stage-specific prompts. Например, вот так можно вести первый продуктовый кусок online shop.
Plan the stage "Catalog MVP" for an online shop project.
Goal:
Users can browse the product catalog and open product detail pages.
Produce:
1. objective
2. business value
3. scope
4. out of scope
5. backend changes
6. frontend changes
7. database changes
8. API contracts
9. risks
10. assumptions
11. verification plan
12. implementation order
13. acceptance criteria
Constraints:
- prefer end-to-end delivery
- do not design future stages unless needed for extensibility
- keep architecture simple and scalable
- do not implement cart, checkout, auth, or admin in this stage
Implement the approved stage "Catalog MVP".
Required scope:
- product/category schema
- backend endpoints for product list and product detail
- frontend catalog page
- frontend product detail page
- frontend uses real backend API
- basic loading/error/empty states
- test data / seed
- relevant tests
Do not expand scope into cart/auth/admin.
At the end provide:
- summary of changes
- files/modules affected
- verification performed
- not verified
- known issues / assumptions / tech debt
- manual QA checklist
- recommended next stage
Review the Catalog MVP implementation as a strict senior engineer.
Check:
- correctness of API and UI integration
- schema design sanity
- test coverage gaps
- frontend/backend contract drift
- missing loading/error/empty states
- maintainability concerns
- future risk created by current design
Output:
- critical issues
- important follow-ups
- nice-to-have improvements
- test gaps
- overall assessment
Как дробить большой проект на stages
Самая частая ошибка в AI-assisted разработке — дробить работу по слоям: сначала весь backend, потом вся база, потом весь frontend. Такой подход откладывает интеграцию и прячет реальные риски.
Плохой stage goal
"Реализовать cart service, Redux store и DTO". Это описание внутренних кусков, а не способности системы.
Хороший stage goal
"Пользователь может добавить товар в корзину и управлять ее содержимым через реальный backend API". Это уже конкретная capability.
Правильнее дробить проект по вертикальным capability slices. Stage должен давать работающий кусок бизнес-возможности, а не только новый слой или набор внутренних модулей.
Большой пример: online shop с нуля
Ниже пример того, как можно разложить интернет-магазин на последовательность управляемых этапов. Это не единственно правильная декомпозиция, но она хорошо показывает принцип vertical slices.
Stage 0. Foundation / Bootstrap
Цель этапа — создать минимальный каркас проекта, который можно запускать, тестировать и постепенно развивать.
- Backend: skeleton приложения, health endpoint, конфигурация, базовая структура модулей и подключение к БД.
- Frontend: skeleton приложения, базовая маршрутизация, layout, environment setup и API client skeleton.
- DB: подключение, миграционная система, первая служебная миграция и seed framework.
- Infra: Docker или Compose для локального запуска,
.env.example, базовый CI и lint/test scripts. - Acceptance criteria: проект поднимается локально одной инструкцией, frontend открывается, backend отвечает на
/health, БД подключается и CI запускает хотя бы минимальные проверки.
Stage 1. Catalog MVP
Пользователь может открыть каталог и карточку товара. Это первый stage, который уже можно показать как продукт.
- Backend:
Product,Category, API списка товаров, API карточки товара, базовые фильтры и seed товаров. - Frontend: страница каталога, карточки товаров, страница товара, loading/error/empty states.
- DB: таблицы
productsиcategories, индексы и test seed data. - Acceptance criteria: список грузится с backend, карточка открывается, фронт работает на реальном API, есть интеграционные тесты на список и карточку, есть smoke-проверка UI.
Stage 2. Auth & User Identity
- Goal: пользователь может зарегистрироваться, войти и иметь свой профиль.
- Backend: signup/signin, refresh или session handling, profile endpoint, auth middleware и password hashing.
- Frontend: login/register forms, protected routes, session state, logout и profile page.
- DB:
users,sessionsили storage refresh token-ов, ограничения и индексы. - Acceptance criteria: пользователь регистрируется, входит, выходит, защищенные страницы требуют авторизации, профиль отображается и auth flow покрыт тестами.
Stage 3. Cart MVP
- Goal: пользователь может собирать корзину.
- Backend: сущность корзины, add/remove item, update quantity, get cart.
- Frontend: add to cart, cart page или drawer, update quantity, remove item, subtotal.
- DB:
cartиcart_items, связь с пользователем и/или guest session. - Acceptance criteria: товар добавляется, количество меняется, удаление работает, итоговая сумма видна, корзина синхронизирована с backend.
Stage 4. Checkout Draft
- Goal: пользователь может начать оформление заказа.
- Backend: draft order, адрес доставки, выбор способа доставки, валидация заказа и серверный пересчет суммы.
- Frontend: checkout page, address form, review order, validation errors.
- DB:
orders,order_items,shipping_address,order_status. - Acceptance criteria: из корзины создается черновик заказа, пользователь указывает адрес, итог проверяется сервером, заказ можно подтвердить.
Ключевой риск checkout
Клиент не должен быть source of truth. Пересчет суммы и корректность snapshot order items должны жить на сервере.
Stage 5. Payment Integration Stub / Payment Flow
- Goal: заказ проходит через базовый платежный сценарий.
- Backend: payment intent или stub, обработка payment status, webhook endpoint или mock flow, обновление статусов заказа.
- Frontend: кнопка оплаты, экран результата оплаты, ошибка и retry UX.
- DB: payment records, relation заказа и платежа, status transitions.
- Acceptance criteria: есть успешный и неуспешный сценарий оплаты, статус заказа меняется корректно, переходы статусов покрыты тестами.
Stage 6. Order History & Account
- Goal: пользователь может видеть свои заказы.
- Backend: список заказов пользователя, детали заказа и доступ только к своим данным.
- Frontend: account/orders page, order detail page, базовая визуализация статусов.
- DB: индексы для выборок по пользователю и оптимизация запросов.
- Acceptance criteria: пользователь видит только свои заказы, список и детали корректны, базовые auth rules покрыты тестами.
Stage 7. Admin Product Management
- Goal: администратор может управлять товарами.
- Backend: admin authz, CRUD товаров, изменение цены, остатка и публикации.
- Frontend: admin products list, create/edit forms, inventory field и price management.
- DB: inventory/stock fields и при необходимости audit fields.
- Acceptance criteria: админ может создавать и обновлять товары, обычный пользователь не может, изменения видны в каталоге, authz покрыта тестами.
Stage 8. Admin Order Management
- Goal: администратор может управлять заказами.
- Backend: список заказов, фильтры, смена статусов, отмена или выполнение.
- Frontend: admin orders page, detail view, status actions.
- Acceptance criteria: админ видит заказы, может менять статусы, пользовательская и админская логика не смешиваются, есть тесты на transitions и permissions.
Stage 9. Search / Filters / UX Maturity
- Goal: улучшить каталог до usable-продукта.
- Что добавляется: поиск, сортировки, расширенные фильтры, pagination и более сильные empty/loading/error states.
- Почему это отдельный stage: это enhancement поверх уже работающего end-to-end потока, а не фундаментальный строительный блок.
Stage 10. Reliability / Production Readiness
- Goal: подготовить систему к реальной эксплуатации.
- Что добавляется: observability, structured logging, metrics, tracing basics, error monitoring, rate limiting, backups, migration safety, CI/CD hardening и staging flow.
- Acceptance criteria: есть health/readiness, логирование критичных потоков, наблюдаемость, rollback-safe deployment notes и production checklist.
Как тестировать по stages
На каждом этапе должны появляться проверки нескольких уровней. Иначе stage может выглядеть завершенным, но оставаться слабо контролируемым.
| Уровень | Что проверяет | Примеры |
|---|---|---|
| Unit tests | Чистую бизнес-логику, валидаторы, мапперы, status transitions. | Расчет subtotal, валидация адреса, правила смены статусов заказа. |
| Integration tests | API, DB, auth и межмодульные контракты. | POST /cart/items, GET /orders/:id, auth middleware, миграция с новыми таблицами. |
| Smoke / e2e | Критичные бизнес-сценарии. | Открыть каталог → добавить в корзину → начать checkout. |
Что обязательно тестировать в online shop
- Каталог, корзину, checkout, создание заказа и историю заказов.
- Auth, authz, price calculation, stock rules, order ownership и admin-only operations.
- Миграции, обратную совместимость API, обработку ошибок, идемпотентность опасных действий и data integrity.
Практический минимум тестов на stage
- Для обычного feature stage: 2-5 unit tests, 2-4 integration tests и 1 smoke-сценарий на ключевой путь.
- Для auth, payment и order stages: больше integration, негативные сценарии и обязательные permission checks.
- Для DB stages: проверка применения миграции, сохранности старых данных и интеграционные тесты на новую схему.
Что просить у агента после реализации
- Какие именно тесты он добавил.
- Что покрыто и что не покрыто.
- Какие команды запускались.
- Что упало или не запускалось.
- Какие ручные проверки еще нужны.
Как вести review и infra-проходы
В AI-assisted разработке review нужен не меньше, а больше, чем в обычной: агент может быстро написать код, но так же быстро внести drift, спрятать assumptions и создать невидимый технический долг.
Что должен искать review pass
- Correctness: работает ли логика и нет ли очевидных ошибок.
- Edge cases: пустые данные, невалидные payloads, гонки, неавторизованный доступ, 404/409/422 cases.
- Contract drift: совпадают ли backend payloads и frontend expectations.
- Test gaps: есть ли happy path без негативных сценариев и где логика осталась без тестов.
- Architecture drift: не смешались ли domain, transport и persistence слои.
- Ops risk: безопасны ли миграции и понятен ли rollout order.
Как делать review practically
- Один и тот же агент делает plan и build, потом отдельным проходом делает strict review.
- Или используется отдельный review-agent.
- Для серьезных изменений лучшая схема — AI review плюс человеческий review по Stage Report.
Что должно появиться рано по infra и DevEx
- Единый локальный запуск.
.env.example.- Docker Compose или эквивалент.
- Команды
lint,test,dev. - Хотя бы минимальный CI.
- Health endpoints.
Что должно появиться к production-readiness
- Readiness checks, structured logs и metrics.
- Error reporting и rollback guidance.
- Backup и migration safety.
- Rate limits и secret management hygiene.
Weekly operating mode и Definition of Done
Если вести проект как техлид или менеджер, полезно повторять один и тот же цикл: Stage Definition, plan, scope review, build, Stage Report, review, фиксация release notes и переход к следующему stage.
- Создать
Stage Definition. - Запустить
plan. - Уточнить scope.
- Запустить
build. - Получить
Stage Report. - Запустить
review. - Исправить критичные замечания.
- Зафиксировать release notes.
- Перейти к следующему stage.
Definition of Done для stage
# Definition of Done
A stage is done only if:
- scope is implemented
- acceptance criteria are satisfied
- relevant tests are added or updated
- relevant checks are run
- backend/frontend/db changes are aligned
- known issues are explicitly listed
- assumptions are explicitly listed
- manual QA steps are provided
- stage report is produced
- review pass is completed
Самый практичный совет
Не давайте OpenCode "проект". Давайте ему "следующий управляемый этап проекта". И каждый раз требуйте план, реализацию в рамках scope, проверку, review и Stage Report.
Что делать дальше
- Сразу создать в репозитории
AGENTS.md,docs/stages/,docs/reports/иdocs/release-notes/. - Оформить Stage 0 и Stage 1: Foundation и Catalog MVP.
- Заставить агента всегда завершать stage отчетом, чтобы статус проекта оставался прозрачным.