
Brewcode:E2e
- 6 installs
- 29 repo stars
- Updated August 2, 2026
- kochetkov-ma/claude-brewcode
Helps with ai & agent building tasks.
About
brewcode:e2e is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted development.
- brewcode:e2e
- AI & Agent Building
- AI-coding skill
Brewcode:E2e by the numbers
- 6 all-time installs (skills.sh)
- +1 installs in the week ending Aug 2, 2026 (Skillselion tracking)
- Ranked #12,825 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/kochetkov-ma/claude-brewcode --skill brewcodee2eAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 6 |
|---|---|
| repo stars | ★ 29 |
| Last updated | August 2, 2026 |
| Repository | kochetkov-ma/claude-brewcode ↗ |
What it does
Helps with ai & agent building tasks.
Files
<instructions>
E2E Testing
Full-cycle E2E testing orchestration: setup agents, create BDD scenarios, write autotests, quorum review.
Arguments: $ARGUMENTS
---
Phase 0: Parse Arguments
EXECUTE using Bash tool:
bash "${CLAUDE_SKILL_DIR}/scripts/detect-mode.sh" "$ARGUMENTS" && echo "OK" || echo "FAILED"Output: MODE:xxx and optionally PROMPT:xxx. Store both.
STOP if FAILED -- fix detect-mode.sh before continuing.
---
Phase 1: Display Detection
Output detection result:
Mode: {MODE}
Prompt: {PROMPT or "none"}---
Phase 2: Load Mode Reference
Read the mode-specific reference file:
| MODE | Reference File |
|---|---|
| setup | ${CLAUDE_SKILL_DIR}/references/mode-setup.md |
| create | ${CLAUDE_SKILL_DIR}/references/mode-create.md |
| update | ${CLAUDE_SKILL_DIR}/references/mode-update.md |
| review | ${CLAUDE_SKILL_DIR}/references/mode-review.md |
| rules | ${CLAUDE_SKILL_DIR}/references/mode-rules.md |
| status | ${CLAUDE_SKILL_DIR}/references/mode-status.md |
Also load core references (always):
${CLAUDE_SKILL_DIR}/references/e2e-rules.md-- rules for all agents${CLAUDE_SKILL_DIR}/references/e2e-architecture.md-- architecture reference
STOP if mode reference not found -- report missing file.
---
Phase 3: Execute Mode Flow
Follow the loaded mode reference step by step. Pass PROMPT as context where indicated.
Common patterns across all modes:
Prerequisite Check (all modes except setup and status)
.claude/agents/e2e-*.md count must be >=3. If not -> "Run /brewcode:e2e setup first." STOP. Status mode reports missing infrastructure instead of blocking.
Review Cycle (create, update modes)
MAX_CYCLES=3. Pattern: execute -> reviewer validates -> different agent re-checks -> fix confirmed -> repeat.
Agent Dispatch
All agent work through Task tool. Spawn parallel agents in ONE message when possible.
User Interaction
AskUserQuestion at every key decision point. PROMPT is initial context, not a replacement for confirmation.
---
Error Handling
| Condition | Action |
|---|---|
| Rules file missing | "E2E rules not found at ${CLAUDE_SKILL_DIR}/references/. Re-install plugin." STOP |
| Agents missing (non-setup/status mode) | "Run /brewcode:e2e setup first." STOP |
| Config missing (non-setup mode) | "Run /brewcode:e2e setup first." STOP |
| Review cycle limit (3) reached | AskUserQuestion with remaining issues |
| Compilation fails after fix | Report to user, suggest manual intervention |
| Agent refuses task | Re-assign to suggested colleague, max 2 retries |
---
Output Format
# e2e [{MODE}]
## Detection
| Field | Value |
|-------|-------|
| Arguments | `{raw args}` |
| Mode | `{MODE}` |
| Prompt | `{PROMPT or none}` |
## Results
{Mode-specific output}
## Next Steps
- {recommendations based on mode}</instructions>
MIT License
Copyright (c) 2025-2026 Maxim Kochetkov (kochetkov-ma)
https://github.com/kochetkov-ma/claude-brewcode
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Скилл brewcode:e2e и E2E-агенты
Начальная промт-спецификация. Планирование обязательно перед реализацией — всё ниже является намерением, не финальным решением.
Цель
Скилл brewcode:e2e + набор E2E-агентов для полного цикла тестирования: анализ → сценарии → автотесты → ревью. Модель: скилл-менеджер делегирует через Task tool.
---
1. Скилл: brewcode:e2e
Расположение (уточнить при планировании)
brewcode/skills/e2e/
├── SKILL.md
├── README.md
├── scripts/
│ └── detect-mode.sh # Парсинг аргументов: MODE, PROMPT
├── references/
│ ├── e2e-rules.md # Базовые правила E2E (раздел 3)
│ ├── e2e-architecture.md # Архитектурные паттерны E2E (раздел 4)
│ ├── agent-template.md # Шаблон E2E-агентов (адаптация из teams)
│ └── review-checklist.md # Чеклист ревью тестов и сценариевОткрытые вопросы: нужны ли per-mode/per-agent references? templates/ для сценариев и отчётов?
Frontmatter (черновик)
---
name: brewcode:e2e
description: "TODO: <= 120 символов (optimal ~100), single line, что + 3-5 trigger keywords"
# model, context, allowed-tools, argument-hint — определить при планировании
---Режимы
Каждый режим принимает опциональный промт. Без промта — уточнение через AskUserQuestion. С промтом — используется как контекст, но план всё равно подтверждается.
| Режим | Вызов | Описание |
|---|---|---|
setup (default) | /brewcode:e2e [prompt] или /brewcode:e2e setup [prompt] | Анализ → создание агентов → правила → документация |
create | /brewcode:e2e create [prompt] | Создание сценариев и тестов по описанию flow |
update | /brewcode:e2e update [prompt] | Улучшение существующих сценариев/тестов |
review | /brewcode:e2e review [prompt] | Мультиагентное ревью (3 ревьюера, quorum 2/3) |
rules | /brewcode:e2e rules [prompt] | Создание/обновление правил E2E |
status | /brewcode:e2e status [prompt] | Проверка агентов, правил, сценариев |
Принципы скилла
1. AskUserQuestion всегда — на каждом ключевом этапе. Промт — контекст, не замена подтверждения. 2. Трёхшаговый цикл: Выполнение → Валидация → Перепроверка → Исправление. Повторяется до 0 проблем. 3. Без сценария — не пишем тесты. E2E-тест создаётся исключительно по утверждённому, воспроизводимому вручную сценарию. 4. Делегирование через агентов — скилл только управляет через Task tool.
---
2. Агенты E2E
Расположение, модели, набор инструментов — определить при планировании.
| Агент | Роль |
|---|---|
e2e-manager | QA-менеджер: координация, распределение задач, контроль качества |
e2e-manual-tester | Ручной тестировщик: проверяет UI/API, находит баги, работает с credentials |
e2e-automation-tester | Автоматизатор: пишет E2E-автотесты строго по сценариям и архитектурным правилам |
e2e-scenario-analyst | Сценарный аналитик: создаёт детальные BDD-сценарии по анализу системы |
e2e-reviewer | Ревьюер: качество тестов и сценариев, соответствие правилам (READ-ONLY) |
e2e-architect | E2E-архитектор: анализирует проект, создаёт паттерны, правила, конвенции |
Открытые вопросы: нужныe2e-data-engineer,e2e-infra? Модели иdisallowedTools— определить при планировании.
Шаблон агентов
Источник: brewcode/skills/teams/references/agent-template.md — скопировать и адаптировать под E2E.
Обязательные элементы: Mission / Domain / Character / Last Updated | Immutable Traits (Name, Base Role) | Task Acceptance Protocol | Domain Instructions | Colleagues (таблица E2E-команды)
Дополнительные требования:
- Самокритичность: агент проверяет результат перед отдачей менеджеру.
- Загрузка правил: агенты, пишущие или ревьюящие код, загружают
e2e-rules.mdдо начала работы. Если файл не найден — стоп, сообщить менеджеру. - Eager по умолчанию — загружать и валидировать до начала работы.
lazyтолько если указано явно. - Создание: через
Task(subagent_type="brewcode:agent-creator"), батчами по 3-4. Agentdescription<= 100 chars (optimal ~80), single line, role + 2-3 triggers, no<example>blocks.
---
3. Правила E2E (references/e2e-rules.md)
При setup: WebSearch лучших практик → структурировать полный набор. Правила: короткие, конкретные, actionable. При режиме `rules`: обновить по опыту проекта, перепроверить все источники.
Сценарии
| # | Правило | Пояснение |
|---|---|---|
| S1 | Без сценария — не пишем тест | Тест создаётся исключительно по утверждённому сценарию |
| S2 | Сценарий = полный пользовательский flow | От начала до конца, законченный бизнес-путь |
| S3 | Сценарий воспроизводим вручную | Каждый шаг можно выполнить руками (curl/Postman) |
| S4 | BDD-формат: Given/When/Then | С уточнением после двоеточия: Given: пользователь авторизован как admin |
| S5 | Сценарии могут пересекаться | Авторизация — общий шаг в разных сценариях |
| S6 | Тесты длинные | E2E — полные flow через множество шагов и систем |
Тестовые данные
| # | Правило | Пояснение |
|---|---|---|
| D1 | Максимальный набор тестовых данных | Покрытие основных кейсов с запасом, не минимум |
| D2 | Данные через API, не напрямую в БД | API — идеал. UI — допустимо. Прямая запись в БД — крайний случай с подтверждением |
| D3 | Отдельный слой генерации/хранения данных | Data layer как сервис, вызываемый из тестов |
| D4 | Параметризованные тесты обязательны | Один тест — множество наборов данных |
Интеграция
| # | Правило | Пояснение |
|---|---|---|
| I1 | Полная интеграция, без моков | Моки — только если технически невозможно, с подтверждением |
| I2 | Проверка во всех конечных системах | Основная система + все downstream-зависимости |
| I3 | Тесты проверяют пользовательский flow | Бизнес-результат, не техническую реализацию |
Ассерты
| # | Правило | Пояснение |
|---|---|---|
| A1 | Строгие ассерты: сравнение объектов | Никаких isNotNull(), isNotEmpty(), isGreaterThanOrEqualTo(0) |
| A2 | Конкретные значения | isEqualTo(expectedValue), hasSize(N), полное сравнение объектов |
| A3 | Описание на каждом ассерте | .as("описание") или эквивалент фреймворка |
| A4 | Нет if в тестах | Assert precondition сначала, потом безусловная проверка |
Архитектура (подробнее в e2e-architecture.md)
| # | Правило | Пояснение |
|---|---|---|
| R1 | Steps-слой отделяет бизнес от техники | В тестах — бизнес-шаги, без прямых вызовов API/UI |
| R2 | Базовые классы по доменам | BaseE2E → BaseAuthE2E, BasePaymentE2E |
| R3 | Support-классы вместо Utils | KafkaSupport, DatabaseSupport |
| R4 | Репортер вместо логов | Reporter фреймворка. Никаких print/System.out |
Процесс
| # | Правило | Пояснение |
|---|---|---|
| P1 | Трёхшаговый цикл | Выполнение → Валидация → Перепроверка → Исправление |
| P2 | Перепроверка каждой проблемы после ревью | Ревьюер может ошибиться — убедиться, что проблема реальна |
| P3 | Правила — в документации проекта | Рядом с агентами, доступны для загрузки |
---
4. Архитектура E2E (references/e2e-architecture.md)
┌─────────────────────────────────────────────┐
│ Test Classes (по доменам) │
│ extends BaseE2E / BaseDomainE2E │
│ содержат: @ParameterizedTest + шаги │
├─────────────────────────────────────────────┤
│ Steps Layer (бизнес-шаги) │
│ переиспользуемые across tests │
│ Given/When/Then шаги │
├─────────────────────────────────────────────┤
│ Verification Layer (assertion steps) │
│ строгие проверки, полное сравнение │
├─────────────────────────────────────────────┤
│ Data Layer │
│ генерация / хранение / подготовка данных │
│ через API (не прямая запись в БД) │
├─────────────────────────────────────────────┤
│ Support Layer │
│ KafkaSupport, DatabaseSupport, HttpSupport │
├─────────────────────────────────────────────┤
│ Config Layer │
│ credentials, endpoints, timeouts │
└─────────────────────────────────────────────┘| # | Требование | Детали |
|---|---|---|
| 1 | В тестах нет прямого кода | Всё через Steps — никаких прямых API/UI-вызовов |
| 2 | Steps = бизнес-язык | givenUserIsAuthorized("admin"), не httpClient.post("/auth", ...) |
| 3 | Параметризованные тесты | Один метод — множество наборов данных |
| 4 | Базовые классы | BaseE2E → Base{Domain}E2E → конкретные тесты |
| 5 | Support вместо Utils | {Technology}Support, не {Technology}Utils |
| 6 | Given/When/Then разделение | Через фреймворк или комментарии |
| 7 | Аннотации и метаданные | @DisplayName, @Tag, @Step и т.д. |
| 8 | Репортинг через фреймворк | Reporter > Logger > ничего |
e2e-architect адаптирует архитектуру под стек проекта. Этот документ — отправная точка.---
5. Детализация режимов
5.1 setup
Цель: подготовить проект — создать агентов, правила, документацию. Промт: уточняет scope. Примеры: "focus on payment domain", "only API tests", "use Playwright + Jest".
1. Проверка статуса: если настроено — предложить другой режим 2. Анализ проекта (3-5 Explore-агентов параллельно): структура, тесты, стек, API, инфраструктура 3. AskUserQuestion: результат анализа, scope, подтверждение плана 4. Создание E2E-агентов через agent-creator (батчами) 5. WebSearch лучших практик + анализ архитектуры → правила 6. Валидация правил (e2e-reviewer) 7. Фиксация документации, AskUserQuestion: итог 8. Опционально: краткие правила в .claude/rules/
5.2 create
Цель: создать E2E-сценарии и тесты. Промт: что тестируем. Примеры: "checkout flow with 3D Secure", "user registration and email verification".
1. AskUserQuestion: scope 2. Анализ системы (3-5 Explore параллельно) 3. Создание сценариев (e2e-scenario-analyst) 4. Валидация сценариев (e2e-reviewer) → перепроверка → исправление 5. AskUserQuestion: одобрение сценариев 6. Написание тестов (e2e-automation-tester) 7. Ревью тестов (e2e-reviewer) → цикл до 0 проблем 8. AskUserQuestion: итог
5.3 update
Цель: улучшить существующие сценарии/тесты. Промт: что улучшить. Примеры: "add negative scenarios to payment tests", "refactor auth steps to use new API".
Аналогично create, но начинается с поиска существующих артефактов.
5.4 review
Цель: мультиагентное ревью с quorum. Промт: scope. Примеры: "review only auth e2e tests", "focus on assertion quality".
1. AskUserQuestion: что ревьюим 2. Разделить scope на части 3. На каждую часть — 3 параллельных e2e-reviewer (quorum 2/3) 4. Ревью сценариев: соответствие тестов и сценариев 5. Перепроверка. Проблема подтверждена если 2 из 3 согласны 6. AskUserQuestion: результат, предложение исправлений
5.5 rules
Цель: создать/обновить правила E2E. Промт: фокус. Примеры: "add rules for async messaging tests", "research Playwright best practices".
1. Загрузить текущие правила, проверить актуальность 2. WebSearch актуальных практик для стека (с учётом промта) 3. e2e-architect: анализ проекта, закономерности 4. Обновление правил с перепроверкой источников 5. AskUserQuestion: diff правил, подтверждение 6. Опционально: summary в .claude/rules/ по запросу
При обновлении — все источники перепроверять. Правила: короткие, конкретные, actionable.
5.6 status
Цель: проверка состояния E2E-инфраструктуры. Промт: фильтр вывода. Примеры: "show only missing agents", "check rules freshness".
| Проверка | Что смотрим |
|---|---|
| Агенты | e2e-* в .claude/agents/? |
| Правила | Файл правил E2E? Количество? |
| Сценарии | Написанные сценарии? Расположение? |
| Тесты | E2E-тесты? Структура каталогов? |
| Конфигурация | Стек, фреймворк, базовые классы |
---
6. Технические ориентиры
Направляющие принципы, не финальные решения.
Создание агентов:
- Через
Task(subagent_type="brewcode:agent-creator")— не вручную - Батчами по 3-4 (параллельно)
- После создания — оптимизация через
Skill(skill="brewtools:text-optimize") - Шаблон из
brewcode/skills/teams/references/agent-template.md
Создание скилла:
- Через
Task(subagent_type="brewcode:skill-creator") - Паттерны: Progressive Disclosure, Reference Splitting, Mode Switcher (detect-mode.sh)
${CLAUDE_SKILL_DIR}в SKILL.md,$BC_PLUGIN_ROOTв промтах агентов- Маркер
**EXECUTE** using Bash tool:+&& echo "OK" || echo "FAILED"
Правила и документация:
- Полный набор →
references/e2e-rules.md(для агентов) - Архитектура →
references/e2e-architecture.md - Опционально:
e2e-avoid.mdиe2e-best-practice.mdв.claude/rules/по запросу - При вынесении в
.claude/rules/— дедупликация обязательна
Валидация: каждый артефакт валидируется после создания. Финальное ревью всего результата. Все находки ревью перепроверяются перед исправлением.
---
7. Открытые вопросы (решить при планировании)
| Вопрос | Контекст |
|---|---|
| Точный frontmatter скилла | model, context, allowed-tools, argument-hint |
| Модели для каждого агента | opus/sonnet/haiku — баланс качества и скорости |
| Инструменты для каждого агента | Минимальный набор, disallowedTools |
| Расположение артефактов | Сценарии, отчёты, правила в целевом проекте |
| Дополнительные references | Per-mode, per-agent, per-stack |
| Дополнительные агенты | e2e-data-engineer, e2e-infra — по анализу проекта |
| Порядок реализации | Зависимости, параллелизация, этапы |
| Формат сценариев | Markdown или структурированный YAML? |
| Интеграция с brewcode:start | Как E2E-задачи вписываются в общий workflow |
E2E Testing
End-to-end testing orchestration: setup agents, create BDD scenarios, write autotests, review with quorum.
| Field | Value |
|---|---|
| Command | /brewcode:e2e |
| Model | opus |
| Arguments | setup, create [prompt], update [prompt], review [prompt], rules [prompt], status |
Overview
E2E orchestrates the full end-to-end testing lifecycle. Setup analyzes your project and creates 5 specialized agents (architect, scenario-analyst, automation-tester, manual-tester, reviewer). Create generates BDD scenarios and corresponding autotests with review cycles. Review runs quorum-based quality checks (3 reviewers, 2/3 consensus). Stack-agnostic -- works with Java, Python, JS/TS, and others.
Quick Start
/brewcode:e2e setup # 1. Analyze project, create agents, generate rules
/brewcode:e2e create "checkout flow" # 2. BDD scenarios + autotests
/brewcode:e2e review # 3. Quorum review (3 reviewers, 2/3 consensus)Modes
| Mode | Command | Purpose |
|---|---|---|
| setup | /brewcode:e2e setup | Analyze project, create 5 E2E agents, generate rules, save config |
| create | /brewcode:e2e create [prompt] | Create BDD scenarios and E2E autotests with review cycles |
| update | /brewcode:e2e update [prompt] | Update existing scenarios and tests |
| review | /brewcode:e2e review [prompt] | Multi-agent quorum review (3 reviewers, 2/3 consensus) |
| rules | /brewcode:e2e rules [prompt] | Create or update E2E testing rules via architect + WebSearch |
| status | /brewcode:e2e status | Read-only infrastructure status (agents, rules, config, artifacts) |
Agents (created by setup)
| Agent | Model | Mission |
|---|---|---|
| e2e-architect | opus | Analyzes project, defines patterns, creates rules |
| e2e-scenario-analyst | opus | Creates BDD scenarios from system analysis |
| e2e-automation-tester | opus | Writes E2E autotests from approved scenarios |
| e2e-manual-tester | sonnet | Verifies system via UI/API, finds bugs |
| e2e-reviewer | opus (READ-ONLY) | Reviews quality and rule compliance |
Key Principles
- No scenario, no test -- tests only from approved BDD scenarios
- Three-step cycle -- execute, validate (different agent), re-check, fix
- Quorum review -- 3 reviewers, finding confirmed if 2/3 agree
- Review loops capped at 3 iterations, then user decides
- Stack-agnostic architecture with 6 layers: Test Classes, Steps, Verification, Data, Support, Config
Documentation
Full docs: e2e
<!-- TEMPLATE for agent-creator. Fill {PLACEHOLDERS} based on project analysis. Model: opus (default, confirmed by user during setup). Placement: .claude/agents/{agent-name}.md Agent frontmatter (name, description, model, tools) is added by agent-creator on top. -->
{AGENT_NAME}
Mission: {one sentence} Domain: {area of responsibility} Character: {brief characteristic -- CAN change during update} Last Updated: {ISO_DATE}
Immutable Traits (do NOT change during update)
- Name: {AGENT_NAME}
- Base Role: {role -- if role doesn't fit, delete agent and create a new one}
Scope Constraint
This agent accepts tasks ONLY from /brewcode:e2e skill context. Tasks from other skills/contexts -- refuse with explanation.
Rules Loading Protocol
Before starting ANY task: 1. Read rules: $BC_PLUGIN_ROOT/skills/e2e/references/e2e-rules.md 2. If file not found -- STOP immediately, report: "E2E rules not found at expected path" 3. Keep rules in context throughout task execution
Task Acceptance Protocol
Before accepting ANY task:
| Check | Question | If NO |
|---|---|---|
| Domain | Is this task in my domain? | Refuse -> suggest colleague |
| Duplicate | Has this task already been done? | Refuse -> link to result |
| Best candidate | Would a colleague handle this better? | Refuse -> name colleague |
Self-Check Protocol
Before returning results: 1. Re-read relevant rules from e2e-rules.md 2. Check own output against each applicable rule 3. If violations found -- fix before returning 4. Include "Self-Check: PASS" or list of self-corrections in output
Domain Instructions
{Domain-specific instructions -- filled by agent-creator}
Colleagues
| Agent | Domain | When to suggest |
|---|
{table -- filled when creating the team}
Layered E2E Test Architecture
Stack-agnostic reference for e2e-architect and e2e-automation-tester agents.
Architecture Diagram
┌─────────────────────────────────────────────┐
│ Test Classes (by domain) │
│ extends BaseE2E / BaseDomainE2E │
│ contains: parameterized tests + steps │
├─────────────────────────────────────────────┤
│ Steps Layer (business steps) │
│ reusable across tests │
│ Given/When/Then steps │
├─────────────────────────────────────────────┤
│ Verification Layer (assertion steps) │
│ strict checks, full comparison │
├─────────────────────────────────────────────┤
│ Data Layer │
│ generation / storage / preparation │
│ via API (not direct DB writes) │
├─────────────────────────────────────────────┤
│ Support Layer │
│ KafkaSupport, DatabaseSupport, HttpSupport │
│ technical integration utilities │
├─────────────────────────────────────────────┤
│ Config Layer │
│ test environment settings │
│ credentials, endpoints, timeouts │
└─────────────────────────────────────────────┘Key Architecture Requirements
| # | Requirement | Details |
|---|---|---|
| 1 | No direct code in tests | No API calls, no UI element access -- everything through Steps layer |
| 2 | Steps = business language | givenUserIsAuthorized("admin"), not httpClient.post("/auth", ...) |
| 3 | Parameterized tests | One test method handles multiple data sets; data lives outside test logic |
| 4 | Base classes | BaseE2E (shared) -> Base{Domain}E2E (per domain) -> concrete tests |
| 5 | Support, not Utils | Naming: {Technology}Support (e.g. KafkaSupport, DatabaseSupport) |
| 6 | Given/When/Then separation | Via framework features if available, otherwise via // GIVEN // WHEN // THEN comments |
| 7 | Annotations and metadata | Maximize framework features: display names, tags, step annotations, severity |
| 8 | Reporting via framework | Reporter > Logger > nothing; never rely on stdout for test results |
Layer Details
Test Classes
Purpose: Domain-specific test scenarios. Each class covers one bounded context or feature area.
Naming: {Domain}{Feature}E2ETest (e.g. PaymentRefundE2ETest)
Depends on: Steps, base classes only.
class OrderCreationE2ETest extends BaseOrderE2E:
@ParameterizedTest(dataSets: standardOrders)
@DisplayName("Order is created and confirmed for {orderType}")
test createOrder(orderType, expectedStatus):
// GIVEN
steps.givenAuthenticatedUser("buyer")
steps.givenProductAvailable(orderType.productId)
// WHEN
steps.whenUserCreatesOrder(orderType)
// THEN
verify.thenOrderHasStatus(expectedStatus)Steps Layer
Purpose: Business-readable actions. Each method is one logical step in domain language.
Naming: {Domain}Steps (e.g. OrderSteps, PaymentSteps)
Depends on: Verification, Data, Support layers.
class OrderSteps:
@Step("User creates order of type {orderType}")
whenUserCreatesOrder(orderType):
payload = orderData.buildOrderPayload(orderType)
response = httpSupport.post("/api/orders", payload)
context.storeOrderId(response.body.id)Verification Layer
Purpose: Assertion logic isolated from test flow. Strict checks with full object comparison.
Naming: {Domain}Verification (e.g. OrderVerification)
Depends on: Support layer (to fetch actual state), Config (timeouts).
class OrderVerification:
@Step("Order has status {expectedStatus}")
thenOrderHasStatus(expectedStatus):
orderId = context.getOrderId()
actual = httpSupport.get("/api/orders/{orderId}")
assertThat(actual.status)
.describedAs("Order %s status", orderId)
.isEqualTo(expectedStatus)Data Layer
Purpose: Test data generation, preparation, and cleanup. All mutations through API, never direct DB writes.
Naming: {Domain}Data (e.g. OrderData, UserData)
Depends on: Support layer only.
class OrderData:
buildOrderPayload(orderType):
return OrderPayload(
type: orderType,
items: generateItems(orderType),
timestamp: now()
)
prepareTestProduct(productId):
httpSupport.post("/api/admin/products", defaultProduct(productId))Support Layer
Purpose: Technical integration wrappers. One class per technology. Stateless where possible.
Naming: {Technology}Support (e.g. HttpSupport, KafkaSupport, DatabaseSupport)
Depends on: Config layer only.
class KafkaSupport:
constructor(config):
this.bootstrapServers = config.get("kafka.bootstrap-servers")
this.consumer = createConsumer(this.bootstrapServers)
consumeMessages(topic, timeout):
return this.consumer.poll(topic, timeout)
publishMessage(topic, key, payload):
this.producer.send(topic, key, serialize(payload))Config Layer
Purpose: Environment-specific settings. Single source of truth for endpoints, credentials, timeouts.
Naming: TestConfig, E2EConfig, or framework-specific config file.
Depends on: Nothing. This is the bottom layer.
class TestConfig:
baseUrl = env("BASE_URL", "http://localhost:8080")
dbHost = env("DB_HOST", "localhost")
kafkaServers = env("KAFKA_SERVERS", "localhost:9092")
defaultTimeout = duration("30s")
retryAttempts = 3Stack Mapping
| Concept | Java/JUnit5 | Python/pytest | JS/Playwright | C#/NUnit |
|---|---|---|---|---|
| Test class | class *E2ETest + @ExtendWith | class Test* | test.describe(...) | [TestFixture] class *E2ETest |
| Parameterized | @ParameterizedTest + @MethodSource | @pytest.mark.parametrize | for...of testData | [TestCaseSource] |
| Base class | extends BaseE2E | class BaseE2E: | class BaseE2E | : BaseE2E |
| Steps | Allure @Step methods | allure.step() context | test.step("...", ...) | [AllureStep] attribute |
| Assertions | AssertJ assertThat() | assert + pytest introspection | expect() | FluentAssertions Should() |
| Reporter | Allure / ExtentReports | Allure / pytest-html | Playwright HTML reporter | Allure / ExtentReports |
| Support class | KafkaSupport.java | kafka_support.py | kafkaSupport.ts | KafkaSupport.cs |
| Config | application-test.yml | conftest.py + env | playwright.config.ts | appsettings.test.json |
| Tags/Groups | @Tag("smoke") | @pytest.mark.smoke | test.describe.configure({tag}) | [Category("smoke")] |
| Display name | @DisplayName("...") | docstring or ids= param | test title string | [Description("...")] |
| Lifecycle hooks | @BeforeAll / @AfterAll | setup_class / fixtures | beforeAll / afterAll | [OneTimeSetUp] / [OneTimeTearDown] |
Dependency Rules
Test Classes
|
v
Steps Layer
|
+------+------+
| |
v v
Verification Data Layer
| |
+------+------+
|
v
Support Layer
|
v
Config LayerAllowed dependencies (top-down only):
| Source Layer | Can Access |
|---|---|
| Test Classes | Steps, base classes |
| Steps | Verification, Data, Support |
| Verification | Support, Config |
| Data | Support, Config |
| Support | Config |
| Config | Nothing (leaf layer) |
Forbidden:
| Rule | Reason |
|---|---|
| Test Classes -> Support | Tests must not bypass Steps; keeps tests readable |
| Test Classes -> Data | Data preparation belongs in Steps or base class setup |
| Test Classes -> Config | Access config through base class or Steps |
| Steps -> Test Classes | No upward dependencies; breaks reusability |
| Support -> Steps | Support is generic; must not know about business logic |
| Config -> anything | Config is passive; read-only, no side effects |
| Any layer -> skip layers | Each layer talks only to the layer directly below. Exception: Steps can access Verification, Data, and Support directly (Steps is the fan-out layer) |
E2E Testing Rules
Reference rules for E2E test development. Each category contains actionable rules with review questions for validation.
---
Scenarios
Rules governing what constitutes a valid E2E scenario.
| # | Rule | Detail | Review Question |
|---|---|---|---|
| S1 | No scenario — no test | E2E test ONLY from approved scenario | Does every test trace to an approved scenario? |
| S2 | Scenario = complete user flow | Start to finish, tangible user value. Not a fragment — a complete business path | Does the scenario cover a complete business flow with clear user value? |
| S3 | Scenario is manually reproducible | Every step executable by hand (including API via curl/Postman) | Can every step be performed manually? |
| S4 | BDD format: Given/When/Then | With clarification after colon: Given: user is authorized as admin | Does every scenario follow BDD format with specific clarifications? |
| S5 | Scenarios may overlap | Authorization is a common step across different scenarios. Normal for E2E | N/A (informational) |
| S6 | Tests are long | E2E = full flows. One test traverses multiple steps and systems | Does the test cover the full flow without shortcuts? |
---
Test Data
Rules for test data creation and management.
| # | Rule | Detail | Review Question |
|---|---|---|---|
| D1 | Maximum test data coverage | Not minimal "2 records" — cover main cases with margin | Does test data cover all main cases including edge cases? |
| D2 | Data via API, not direct DB | Public API = ideal. UI = acceptable. Direct DB = last resort with user confirmation | Is test data created through API/UI, not direct DB writes? |
| D3 | Separate data generation layer | Data layer as a service callable from tests | Is there a dedicated data layer/service for test data? |
| D4 | Parameterized tests mandatory | One test method — multiple data sets | Are tests parameterized with multiple data sets? |
---
Integration
Rules for system integration within E2E tests.
| # | Rule | Detail | Review Question |
|---|---|---|---|
| I1 | Full integration, no mocks | Mocks only if integration technically impossible, with user confirmation | Are all integrations real (no mocks without justification)? |
| I2 | Verify ALL downstream systems | Check not just primary system but all downstream dependencies | Are assertions checking all affected systems? |
| I3 | Tests verify user flow | Not technical implementation — business outcome | Do assertions verify business outcomes, not implementation details? |
---
Assertions
Rules for assertion quality and strictness.
| # | Rule | Detail | Review Question |
|---|---|---|---|
| A1 | Strict assertions: object comparison | No isNotNull(), isNotEmpty(), isGreaterThanOrEqualTo(0) | Are all assertions strict with concrete expected values? |
| A2 | Concrete values | isEqualTo(expectedValue), hasSize(N), full object comparison | Does every assertion compare against a specific expected value? |
| A3 | Description on every assertion | .as("description") or framework equivalent | Does every assertion have a descriptive message? |
| A4 | No if in tests | Never if (size > 1) { assert... }. Assert precondition first, then unconditional check | Are there any conditional assertions (if/else around asserts)? |
---
Architecture
Rules for test code organization and layering.
| # | Rule | Detail | Review Question |
|---|---|---|---|
| R1 | Steps layer separates business from tech | Tests use business steps, no direct API/UI calls | Are tests written in business language via Steps layer? |
| R2 | Base classes by domain | BaseE2E -> BaseAuthE2E, BasePaymentE2E etc. | Do test classes extend appropriate domain base classes? |
| R3 | Support classes, not Utils | KafkaSupport, DatabaseSupport — no overlap with library utilities | Are support classes named {Technology}Support (not Utils)? |
| R4 | Reporter instead of logs | Test framework reporter. No print/System.out/console.log | Is reporting done through framework reporter, not print/log statements? |
---
Process
Rules for the development and review workflow.
| # | Rule | Detail | Review Question |
|---|---|---|---|
| P1 | Three-step cycle | Execute -> Validate (different agent) -> Re-check -> Fix | Is every artifact validated by a different agent than its creator? |
| P2 | Re-check EVERY issue after review | Reviewer can be wrong. Verify issue is real before fixing | Are review findings re-checked before applying fixes? |
| P3 | Rules in project documentation | Stored near agents, loadable by all team members | Are rules accessible at the configured path? |
Mode: CREATE
Create BDD scenarios and E2E autotests for a target area.
C0: Prerequisite Check
Check .claude/agents/e2e-*.md count. If <3 → "Run /brewcode:e2e setup first." STOP. Read .claude/e2e/config.json for stack, framework, paths.
C1: Scope Definition
If PROMPT is non-empty → use as initial context, skip to C2 with brief confirmation. If PROMPT is empty → AskUserQuestion: "What flow/area to create E2E tests for?" Provide examples: "checkout flow with 3D Secure", "user registration and email verification"
C2: Target Analysis
Spawn 3-5 Explore agents in ONE message:
| # | Focus |
|---|---|
| 1 | Target area code: controllers, services, models related to scope |
| 2 | Existing tests for this area (if any) |
| 3 | API contracts, endpoints, request/response schemas |
| 4 | Data model: entities, relationships, constraints |
| 5 | External integrations touched by this flow (optional) |
C3: Scenario Creation
Task(subagent_type assigned to e2e-scenario-analyst):
- Input: analysis from C2, scope from C1, rules from config.rulesPath
- Output: BDD scenarios in markdown format
Scenario format:
---
title: "{Descriptive title}"
priority: high|medium|low
tags: [domain, feature]
status: draft
---Given: {precondition with specific values}
When: {action with specific parameters}
Then: {expected outcome with concrete checks}
And: {additional verifications}Location: {config.scenarioDir}/{domain}/ (e.g., .claude/e2e/scenarios/checkout/)
C4: Scenario Review Cycle (MAX_CYCLES=3)
cycle = 0
while cycle < 3:
1. Task(e2e-reviewer): validate scenarios against rules
2. If no issues → break
3. Task(e2e-automation-tester): re-check reviewer findings (cross-domain verification)
4. Confirmed issues → Task(e2e-scenario-analyst): fix
5. cycle++
if cycle == 3 and issues remain:
AskUserQuestion: "Review cycle limit reached. {N} issues remain: {list}. Continue anyway?"C5: User Approval
AskUserQuestion: present all scenarios in table format.
| # | Scenario | Priority | Steps | Status |
|---|
Options: "Approve all" / "Approve with changes" / "Reject — redo"
- If "changes" → AskUser for feedback → back to C3
- If "reject" → back to C1
- Update approved scenarios:
status: approved
C6: Test Automation
Task(e2e-automation-tester):
- Input: approved scenarios, architecture from
$BC_PLUGIN_ROOT/skills/e2e/references/e2e-architecture.md, rules, config - MUST load rules and architecture refs before writing code
- Each test file references its source scenario (comment/annotation)
- Follow layered architecture: Test → Steps → Verification → Data → Support → Config
- Location:
{config.testSourceDir}/{domain}/
C7: Test Review Cycle (MAX_CYCLES=3)
Same pattern as C4:
cycle = 0
while cycle < 3:
1. Task(e2e-reviewer): review tests against rules + architecture
2. If no issues → break
3. Task(e2e-scenario-analyst): re-check findings (different agent = cross-domain)
4. Confirmed issues → Task(e2e-automation-tester): fix
5. cycle++
if cycle == 3 → AskUser with remaining issuesC8: Smoke Validation
Compile/syntax check (stack-dependent):
- Java:
mvn compile -pl {module}orgradle compileTestJava - Python:
python -m py_compile {file} - JS/TS:
npx tsc --noEmitornpx playwright test --list - C#:
dotnet build
If fails → Task(e2e-automation-tester): fix compilation errors. Re-check once.
C9: Final Summary
AskUserQuestion with:
- Scenarios created (count, paths)
- Tests created (count, paths)
- Review cycles used
- Traceability: every approved scenario → >=1 test
- Next steps: "Run tests" /
/brewcode:e2e review//brewcode:e2e create "next flow"
Mode: REVIEW
Multi-agent quorum review of E2E scenarios and tests.
R0: Prerequisite Check
Check .claude/agents/e2e-*.md count. If <3 → "Run /brewcode:e2e setup first." STOP. Read .claude/e2e/config.json for stack, framework, paths.
R1: Scope Definition
If PROMPT is non-empty → use as review filter (e.g., "only auth tests", "focus on assertion quality"). If PROMPT is empty → AskUserQuestion: "What to review?" Options: "All scenarios + tests" / "Only scenarios" / "Only tests" / "Specific domain: ___"
R2: Artifact Scan
1. Scan {config.scenarioDir}/ for scenarios 2. Scan {config.testSourceDir}/ for E2E tests 3. If no artifacts found → "No E2E artifacts found. Run /brewcode:e2e create first." STOP.
R3: Scope Splitting
Split review scope into parts by test file or scenario group. Each part should be reviewable independently.
| Part | Files | Type |
|---|---|---|
| 1 | auth scenarios + tests | domain |
| 2 | payment scenarios + tests | domain |
| ... | ... | ... |
R4: Quorum Review (3x reviewer per part)
For each part, spawn 3 e2e-reviewer agents in parallel via Task tool:
Per reviewer prompt:
- Load rules from {config.rulesPath}
- Review assigned files
- Check against ALL rule categories (S, D, I, A, R, P)
- Use Review Question column from rules as checklist
- Output: findings table with severity (critical/high/medium/low)Quorum consensus (2/3):
| Condition | Classification |
|---|---|
| 2 or 3 reviewers flag same file + same issue category | Confirmed finding |
| Only 1 reviewer flags | Unconfirmed finding (marked for re-check) |
| All 3 agree no issues in a file | Clean |
Merge findings across all 3 reviewers per part.
R5: Cross-Agent Re-check
For confirmed findings only:
- Task(e2e-automation-tester OR e2e-scenario-analyst): re-check confirmed findings
- Different agent type than reviewer = cross-domain verification
- Verify each finding is real and actionable
- May downgrade severity or mark as false positive
For unconfirmed findings:
- Include in report as "unconfirmed — single reviewer"
- Do NOT auto-fix unconfirmed findings
R6: Results Report
AskUserQuestion with full results:
Review Summary
| Metric | Value |
|---|---|
| Parts reviewed | {N} |
| Total findings | {N} |
| Confirmed | {N} |
| Unconfirmed | {N} |
| False positives | {N} |
Confirmed Findings
| # | File | Category | Severity | Description | Fix Proposal |
|---|
Unconfirmed Findings
| # | File | Category | Severity | Description | Reviewer |
|---|
Traceability Check
| Scenario | Status | Test Count | Gap? |
|---|
Options:
- "Fix confirmed issues" → spawn appropriate agents to fix, then re-review fixed files only
- "Export report" → write to
.claude/e2e/reports/{date}_review.md - "Done" → end
Mode: RULES
Create, update, and improve E2E testing rules.
L0: Prerequisite Check
Check .claude/agents/e2e-*.md count. If <3 -> "Run /brewcode:e2e setup first." STOP. Read .claude/e2e/config.json.
L1: Load Current Rules
1. Read base rules: ${CLAUDE_SKILL_DIR}/references/e2e-rules.md 2. Read project rules (if exists): .claude/rules/e2e-conventions.md 3. Check freshness: compare lastSetup date from config with current date 4. Present current state:
| Source | Rules Count | Last Updated |
|---|---|---|
| Base (plugin) | {N} | {date} |
| Project | {N or "none"} | {date or "N/A"} |
L2: Research + Analysis
If PROMPT provided -> use as research focus (e.g., "add async patterns", "Playwright best practices"). If empty -> general improvement based on detected stack.
Parallel: 1. Task(WebSearch): search best practices for {config.stack} E2E testing {PROMPT context}
- Search 2-3 queries, collect actionable rules
2. Task(e2e-architect or architect): analyze project patterns
- Look for recurring issues, anti-patterns, conventions specific to this project
L3: Rules Update
Merge findings into rules:
- Web-sourced rules -> marked with
[WEB]tag - Project-derived rules -> marked with
[PROJECT]tag - Existing rules preserved unless explicitly superseded
Task(e2e-reviewer or reviewer): validate updated rules
- Check for contradictions
- Check for duplicates
- Check actionability (each rule must be checkable)
L4: User Approval
AskUserQuestion with diff of changes:
Rules Diff
| Action | Category | # | Rule | Source |
|---|---|---|---|---|
| ADD | Scenarios | S7 | {new rule} | [WEB] |
| MODIFY | Assertions | A2 | {updated detail} | [PROJECT] |
| KEEP | ... | ... | (unchanged) | ... |
Options:
- "Apply all changes"
- "Select changes" -> AskUser per change
- "Cancel"
L5: Export (Optional)
AskUserQuestion: "Export updated rules to project?" Options:
- "Update .claude/rules/e2e-conventions.md" -> write/update with key rules (~20-30 lines)
- "Update base rules only" -> update e2e-rules.md in plugin (dev mode only)
- "Both"
- "Skip"
Update config.json lastSetup date.
Summary: rules added/modified/removed, sources breakdown.
Mode: SETUP
Setup E2E testing infrastructure: analyze project, create agents, generate rules.
S0: Prerequisites Check
| Check | How | If Missing |
|---|---|---|
| Test framework | Scan build files (pom.xml, package.json, requirements.txt, *.csproj) | AskUser: "No test framework detected. Which to use?" |
| Test source dir | Check common paths (src/test, tests/, __tests__, .test.) | AskUser: "Where should E2E tests live?" |
| Dependencies | Check for E2E-specific deps (Playwright, Selenium, RestAssured, etc.) | Note as missing, suggest in S3 |
S1: Existing Setup Check
Check .claude/agents/e2e-*.md count.
- If >=3 agents exist: AskUserQuestion: "E2E agents already configured ({N} found). What to do?"
Options: "Reconfigure from scratch" / "Keep and continue to rules" / "Cancel"
- If "Keep": skip to S5
- If "Cancel": STOP
S2: Project Analysis
Spawn 3-5 Explore agents in ONE message via Task tool:
| # | Focus |
|---|---|
| 1 | Code structure: modules, packages, domains, architectural layers |
| 2 | Tech stack: build files, frameworks, dependencies, languages |
| 3 | Existing tests: test directories, frameworks, patterns, coverage |
| 4 | API/UI endpoints: REST controllers, GraphQL, UI routes |
| 5 | CI/CD: pipelines, test stages, environments (optional) |
Consolidate into analysis summary.
S3: User Confirmation
AskUserQuestion with analysis results + proposed agent roster:
| Agent | Model | Tools | Mission |
|---|---|---|---|
| e2e-architect | opus | Read,Write,Glob,Grep,Bash,WebSearch,WebFetch | Analyzes project, defines E2E patterns, creates rules |
| e2e-scenario-analyst | opus | Read,Write,Glob,Grep | Creates BDD scenarios from system analysis |
| e2e-automation-tester | opus | Read,Write,Edit,Glob,Grep,Bash | Writes E2E autotests from approved scenarios |
| e2e-manual-tester | sonnet | Read,Write,Glob,Grep,Bash,WebFetch | Verifies system via UI/API, finds bugs |
| e2e-reviewer | opus | Read,Glob,Grep | Reviews quality, rule compliance, coverage (READ-ONLY) |
Options: "Approve roster" / "Modify agents" / "Cancel"
S4: Agent Creation
Create agents via agent-creator in 2 batches:
Batch 1 (3 agents, parallel):
- e2e-architect
- e2e-scenario-analyst
- e2e-automation-tester
Each via: Task(subagent_type="brewcode:agent-creator") Include: agent-template from $BC_PLUGIN_ROOT/skills/e2e/references/agent-template.md, project analysis, colleague table. Agent description <= 100 chars (optimal ~80), single line, role + 2-3 triggers, no <example> blocks.
Batch 2 (2 agents, parallel):
- e2e-manual-tester
- e2e-reviewer (disallowedTools: Write, Edit, Bash)
After each batch: AskUser "Optimize agent prompts with text-optimizer?" If yes, run Skill(skill="brewtools:text-optimize") per agent file.
S5: Rules Generation
1. Task(subagent_type="brewcode:architect"): analyze project patterns + WebSearch best practices for detected stack 2. Merge findings with base rules from ${CLAUDE_SKILL_DIR}/references/e2e-rules.md 3. Task(subagent_type="brewcode:reviewer"): validate generated rules
S6: Config Persistence
Create .claude/e2e/config.json:
{
"stack": "{detected}",
"testFramework": "{detected}",
"testSourceDir": "{detected or user-specified}",
"scenarioDir": ".claude/e2e/scenarios",
"agents": ["e2e-architect", "e2e-scenario-analyst", "e2e-automation-tester", "e2e-manual-tester", "e2e-reviewer"],
"rulesPath": "plugin://brewcode/skills/e2e/references/e2e-rules.md",
"lastSetup": "{ISO_DATE}"
}Optionally generate .claude/rules/e2e-conventions.md (~20-30 lines) with key rules. AskUser: "Export key E2E rules to .claude/rules/?" Options: "Yes" / "No"
S7: Final Summary
AskUserQuestion with:
- Agents created (count + list)
- Rules status
- Config path
- Recommended next step:
/brewcode:e2e create "your first flow"
Mode: STATUS
Read-only status check of E2E testing infrastructure.
T1: Agent Scan
Scan .claude/agents/e2e-*.md:
- Count agents found
- List each with: name, model (from frontmatter), last modified date
T2: Rules Scan
Scan for E2E rules:
${CLAUDE_SKILL_DIR}/references/e2e-rules.md— exists? rule count?.claude/rules/e2e-*.md— project-level rules? count?
T3: Config Check
Read .claude/e2e/config.json:
- If not found → report "Not configured. Run
/brewcode:e2e setup." - If found → extract: stack, testFramework, testSourceDir, scenarioDir, lastSetup
T4: Artifact Scan
Scan configured paths:
- Scenarios at
{config.scenarioDir}/: count, list by domain/directory - Per scenario: title (from frontmatter), status (draft/approved/automated), priority
- Tests at
{config.testSourceDir}/: count E2E test files - Pattern: files matching
*E2E*,*e2e*,*EndToEnd*or in e2e subdirectory
T5: Output Status Table
# E2E Status
## Infrastructure
| Component | Status | Details |
|-----------|--------|---------|
| Agents | {N}/5 configured | {list} |
| Base rules | {exists/missing} | {N} rules |
| Project rules | {exists/missing} | {N} rules |
| Config | {exists/missing} | stack: {X}, framework: {Y} |
## Artifacts
| Type | Count | Location |
|------|-------|----------|
| Scenarios (draft) | {N} | {path} |
| Scenarios (approved) | {N} | {path} |
| Scenarios (automated) | {N} | {path} |
| Test files | {N} | {path} |
## Freshness
| Item | Last Updated |
|------|-------------|
| Config | {date} |
| Last scenario | {date} |
| Last test | {date} |
## Recommendations
- {if agents < 5}: "Missing agents. Run `/brewcode:e2e setup`."
- {if scenarios with status=approved but no test}: "Approved scenarios without tests. Run `/brewcode:e2e create`."
- {if config.lastSetup > 30 days}: "Setup is stale. Consider `/brewcode:e2e rules` to refresh."No AskUserQuestion — purely informational output.
Mode: UPDATE
Update existing E2E scenarios and tests.
U0: Prerequisite Check
Check .claude/agents/e2e-*.md count. If <3 → "Run /brewcode:e2e setup first." STOP. Read .claude/e2e/config.json for stack, framework, paths.
U1: Scope Definition
If PROMPT is non-empty → use as update context. If PROMPT is empty → AskUserQuestion: "What to update?" Provide examples: "add negative scenarios to payment tests", "refactor auth steps to use new API", "update data layer for new schema"
U2: Find Existing Artifacts
1. Scan {config.scenarioDir}/ for existing scenarios 2. Scan {config.testSourceDir}/ for existing E2E tests 3. Match scope from U1 to found artifacts
Present to user:
| # | Type | File | Status | Matches Scope? |
|---|
AskUserQuestion: "Found {N} scenarios and {M} tests matching scope. Confirm update targets?"
U3: Apply Updates
Based on update type:
| Type | Agent | Action |
|---|---|---|
| New scenarios for existing flow | e2e-scenario-analyst | Add scenarios, preserve existing |
| Modify existing scenarios | e2e-scenario-analyst | Edit scenarios, update status to draft |
| New tests from approved scenarios | e2e-automation-tester | Write tests following architecture |
| Modify existing tests | e2e-automation-tester | Edit tests, maintain traceability |
| Refactor steps/support | e2e-automation-tester | Refactor shared layers |
| Architecture changes | e2e-architect | Update patterns, base classes |
Spawn appropriate agent(s) via Task tool.
U4: Review Cycle (MAX_CYCLES=3)
Same pattern as CREATE mode C4/C7:
cycle = 0
while cycle < 3:
1. Task(e2e-reviewer): validate changes against rules
2. If no issues → break
3. Task(different agent): re-check reviewer findings (cross-domain verification)
4. Confirmed issues → Task(original agent): fix
5. cycle++
if cycle == 3 and issues remain:
AskUserQuestion: "Review cycle limit reached. {N} issues remain: {list}. Continue anyway?"U5: Final Summary
AskUserQuestion with:
- Files modified (diff summary: added/changed/removed lines)
- Scenarios updated/added
- Tests updated/added
- Traceability check: every approved scenario still has >=1 test
- Next:
/brewcode:e2e reviewrecommended after significant changes
#!/bin/sh
set -eu
ARGS="${1:-}"
# Parse first word and remainder
FIRST=""
REST=""
if [ -n "$ARGS" ]; then
TRIMMED=$(printf '%s' "$ARGS" | sed 's/^[[:space:]]*//')
FIRST=$(printf '%s' "$TRIMMED" | cut -d' ' -f1)
REST="${TRIMMED#"$FIRST"}"
REST=$(printf '%s' "$REST" | sed 's/^[[:space:]]*//')
fi
is_keyword() {
case "$1" in
setup|create|update|review|rules|status) return 0 ;;
*) return 1 ;;
esac
}
MODE=""
PROMPT=""
if [ -z "$FIRST" ]; then
# No args: detect mode from agent file count
AGENT_COUNT=$(ls .claude/agents/e2e-*.md 2>/dev/null | wc -l | tr -d ' ')
if [ "$AGENT_COUNT" -ge 3 ]; then
MODE="status"
else
MODE="setup"
fi
elif is_keyword "$FIRST"; then
MODE="$FIRST"
PROMPT="$REST"
else
# Non-keyword first word: setup with full args as prompt
MODE="setup"
PROMPT="$ARGS"
fi
printf 'MODE:%s\n' "$MODE"
[ -n "$PROMPT" ] && printf 'PROMPT:%s\n' "$PROMPT"
exit 0